Example #1
0
        private static bool ValidateRelations(Collection <RelationEntity> Relations)
        {
            bool result = true;

            for (int i = 0; i < Relations.Count; i++)
            {
                RelationEntity item = Relations[i];
                if (item.RelationType < 0)
                {
                    item.Errors.Add(new Error("RelationType", "RelationType", "El tipo de relación no puede ser cero"));
                    result = false;
                }
                if (item.IdTarget < 0)
                {
                    item.Errors.Add(new Error("IdTarget", "IdTarget", "IdTarget no puede estar vacío"));
                    result = false;
                }
                if (item.IdSource < 0)
                {
                    item.Errors.Add(new Error("IdSource", "IdSource", "IdSource no puede estar vacío"));
                    result = false;
                }
            }
            return(result);
        }
Example #2
0
 public IResultResponse ChangeIsOpen(int connectorId, int id, int status)
 {
     try
     {
         int             val       = 0;
         ConnectorEntity connector = (ConnectorEntity) new ConnectorBusiness(_dapperFactory).GetEntity("Id=" + connectorId);
         if (connector == null || Utils.ToInt(connector.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在该上游"));
         }
         RelationEntity entRelation = (RelationEntity) new RelationBusiness(_dapperFactory).GetEntity("Id=" + id);
         if (entRelation == null || Utils.ToInt(entRelation.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在合作关系"));
         }
         entRelation.IsOpen = status;
         val = DbAccess.ExecuteUpdate(TableName, entRelation, new string[] { "Id" });
         if (val > 0)
         {
             return(ResultResponse.GetSuccessResult(1));
         }
         else
         {
             return(ResultResponse.ExceptionResult("修改权限失败"));
         }
     }
     catch (Exception ex)
     {
         return(ResultResponse.ExceptionResult(ex));
     }
 }
Example #3
0
        public int InsertDownConnectorRelation(int downConnectorId, int upConnectorId)
        {
            int val = 0;
            //快马接口查询
            int upBuyerId = 0;
            //检查信息是否存在
            ConnectorEntity downConnector = (ConnectorEntity) new ConnectorBusiness().GetEntity("Id=" + downConnectorId);

            if (downConnector == null || Utils.ToInt(downConnector.Id) == 0)
            {
                return(-2);
            }
            RelationEntity entRelation = (RelationEntity) new RelationBusiness().GetEntity("DownConnectorId=" + downConnectorId);

            if (entRelation != null && Utils.ToInt(entRelation.Id) != 0)
            {
                return(-1);
            }
            RelationEntity ent = new RelationEntity();

            ent.UpConnectorId   = upConnectorId;
            ent.UpBuyerId       = upBuyerId;
            ent.DownConnectorId = downConnector.Id;
            ent.Status          = 0;//0待处理
            ent.AddTime         = DateTime.Now;
            ent.UpdateTime      = DateTime.Now;
            ent.InvitedFrom     = 1;
            val = DbAccess.ExecuteInsert(TableName, ent);
            return(val);
        }
Example #4
0
        protected void RelateInternal(IClassifiable relatable, IClassifiable related, RelationDirection direction, TaxonomyNode type)
        {
            var currentRelation = GetRelation(relatable, related, type);

            if (direction == RelationDirection.Undefined)
            {
                if (currentRelation != null)
                {
                    relationRepo.Delete(currentRelation);
                }
                //do nothing if direction is undefined
            }
            else
            {
                if (currentRelation == null)
                {
                    currentRelation = RelationEntity.Create(relatable, related, type == null?null:type.entity, direction);
                    relationRepo.Save(currentRelation);
                }
                else
                {
                    currentRelation.Direction = direction;
                    relationRepo.Update(currentRelation);
                }
            }
        }
Example #5
0
        public IResultResponse ValidateCode(int connectorId, int upConnectorId, string validateCode)
        {
            ConnectorEntity connector = (ConnectorEntity) new ConnectorBusiness(_dapperFactory).GetEntity("Id=" + connectorId);

            if (connector == null || connector.Id == null || connector.Id < 1)
            {
                return(ResultResponse.ExceptionResult("您尚未成为连接器合作商"));
            }

            string mobile = DES.Encode(string.Format("{0}|{1}|{2}|{3}|{4}|{5}", connector.Mobile, connector.Mobile, connector.Mobile, connector.Mobile, connector.Mobile, connector.Mobile));

            GroupEntity     group = (GroupEntity) new GroupBusiness(_dapperFactory).GetEntity("Id=" + connector.GroupId);
            IResultResponse res   = ApiRequest.GetResponse(group.Domain, "vast.account.supplier.validatecode.validate", new Dictionary <string, string>()
            {
                { "Mobile", mobile },
                { "ValidateCode", validateCode },
                { "ProprietorId", connector.SellerId.ToString() },
            });

            if (res.Success)
            {
                int co = Utils.ToInt(DbAccess.GetValue(TableName, "count(0) as co", "upconnectorId=" + upConnectorId + " and status<>-1"));
                if (co >= 1000)
                {
                    return(ResultResponse.ExceptionResult("已经达到最大限制,请联系上游"));
                }
                int val = 0;
                //ConnectorEntity upConnector = (ConnectorEntity)new ConnectorBusiness().GetEntity("Id=" + upConnectorId);
                RelationEntity myRelation = (RelationEntity) new RelationBusiness(_dapperFactory).GetEntity("DownConnectorId=" + connectorId + " and UpConnectorId=" + upConnectorId);
                if (myRelation != null && Utils.ToInt(myRelation.Id) != 0)
                {
                    myRelation.Status      = 0;
                    myRelation.InvitedFrom = 0;
                    val = DbAccess.ExecuteUpdate(TableName, myRelation, new string[] { "Id" });
                }
                else
                {
                    RelationEntity ent = new RelationEntity();
                    ent.UpConnectorId   = upConnectorId;
                    ent.UpBuyerId       = 0;
                    ent.DownConnectorId = connectorId;
                    ent.Status          = 0;//0待处理
                    ent.AddTime         = DateTime.Now;
                    ent.UpdateTime      = DateTime.Now;
                    ent.InvitedFrom     = 0;
                    val = DbAccess.ExecuteInsert(TableName, ent);
                }
                if (val > 0)
                {
                    return(ResultResponse.GetSuccessResult("您已成功申请成为该商家的下游合作商,请等待审核"));
                }
            }
            return(ResultResponse.ExceptionResult(res.Message));
        }
Example #6
0
        /// <summary>
        /// Function to Load the relation Source from database.
        /// </summary>
        /// <param name="relation">RelationEntity parent</param>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="relation"/> is not a <c>RelationEntity</c>.
        /// </exception>
        public void LoadRelationSource(RelationEntity relation, Dictionary <string, IEntity> scope)
        {
            if (relation == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            bool closeConnection = false;

            try
            {
                // Create a new connection if needed
                if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0)
                {
                    closeConnection = true;
                    dbConnection    = dataAccess.GetNewConnection();
                    dbConnection.Open();
                }
                // Create a command

                string           cmdText    = "SELECT idSource FROM [Relation] WHERE idRelation = @idRelation";
                IDbCommand       sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                IDbDataParameter parameter  = dataAccess.GetNewDataParameter("@idRelation", DbType.Int32);
                // Set command parameters values

                parameter.Value = relation.Id;
                sqlCommand.Parameters.Add(parameter);
                // Execute commands

                object idRelation = sqlCommand.ExecuteScalar();
                if (idRelation != null && ((int)idRelation) > 0)
                {
                    // Create data access objects and set connection objects
                    TableDataAccess tableDataAccess = new TableDataAccess();
                    tableDataAccess.SetConnectionObjects(dbConnection, dbTransaction);
                    // Load related object

                    relation.Source = tableDataAccess.Load(((int)idRelation), true, scope);
                }
            }
            catch (DbException dbException)
            {
                // Catch and rethrow as custom exception
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Close connection if initiated by me
                if (closeConnection)
                {
                    dbConnection.Close();
                }
            }
        }
Example #7
0
        public IResultResponse InsertDownConnectorRelation(int downConnectorId, int upConnectorId)
        {
            int val = 0;
            //快马接口查询
            int upBuyerId = 0;
            //检查信息是否存在
            ConnectorEntity downConnector = (ConnectorEntity) new ConnectorBusiness(_dapperFactory).GetEntity("Id=" + downConnectorId);

            if (downConnector == null || Utils.ToInt(downConnector.Id) == 0)
            {
                return(ResultResponse.ExceptionResult("不存在该合作商"));
            }
            DataTable allRecord = DBTable("DownConnectorId=" + downConnectorId + " and Status=1");

            if (allRecord != null && allRecord.Rows.Count > 0)
            {
                return(ResultResponse.ExceptionResult("该合作商已存在上游合作商"));
            }
            int co = Utils.ToInt(DbAccess.GetValue(TableName, "count(0) as co", "upconnectorId=" + upConnectorId + " and status<>-1"));

            if (co >= 1000)
            {
                return(ResultResponse.ExceptionResult("已经达到最大限制,您不能再发出邀请"));
            }

            RelationEntity myRelation = (RelationEntity) new RelationBusiness(_dapperFactory).GetEntity("DownConnectorId=" + downConnectorId + " and UpConnectorId=" + upConnectorId);

            if (myRelation != null && Utils.ToInt(myRelation.Id) != 0)
            {
                myRelation.Status      = 0;
                myRelation.InvitedFrom = 1;
                val = DbAccess.ExecuteUpdate(TableName, myRelation, new string[] { "Id" });
            }
            else
            {
                RelationEntity ent = new RelationEntity();
                ent.UpConnectorId   = upConnectorId;
                ent.UpBuyerId       = upBuyerId;
                ent.DownConnectorId = downConnector.Id;
                ent.Status          = 0;//0待处理
                ent.AddTime         = DateTime.Now;
                ent.UpdateTime      = DateTime.Now;
                ent.InvitedFrom     = 1;
                val = DbAccess.ExecuteInsert(TableName, ent);
            }
            if (val > 0)
            {
                return(ResultResponse.GetSuccessResult(1));
            }
            return(ResultResponse.ExceptionResult("添加合作商失败"));
        }
Example #8
0
        /// <summary>
        /// 删除授权关系记录
        /// </summary>
        /// <param name="id">授权ID</param>
        /// <returns>大于0成功,否则失败</returns>
        /// <remarks>
        /// <list type="bullet">
        /// <item></item>
        /// </list>
        /// </remarks>
        public int Delete(int id, int connectorId)
        {
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("DownConnectorId", connectorId);
            dic.Add("Id", id);
            RelationEntity entRelation = DbAccess.GetEntity <RelationEntity>(TableName, dic);

            if (entRelation == null)
            {
                return(-1);
            }
            return(base.Delete(id));
        }
Example #9
0
        /// <summary>
        /// Adds the specified relation.
        /// </summary>
        /// <param name="relationEntity">Border.</param>
        public void Add(RelationEntity relationEntity)
        {
            Tuple <string, string> key = new Tuple <string, string>(relationEntity.SourceFactionId, relationEntity.TargetFactionId);

            try
            {
                relationEntitiesStore.Add(key, relationEntity);
            }
            catch
            {
                throw new DuplicateEntityException(
                          $"{relationEntity.SourceFactionId}-{relationEntity.TargetFactionId}",
                          nameof(BorderEntity).Replace("Entity", ""));
            }
        }
Example #10
0
        /// <summary>
        /// 插入授权关系信息
        /// </summary>
        /// <returns>大于0成功,否则失败</returns>
        /// <remarks>
        /// <list type="bullet">
        /// </list>
        /// </remarks>
        public int InsertUpConnectorRelation(string mobile, int downConnectorId)
        {
            int val = 0;
            //快马接口查询
            int upBuyerId = 0;
            //检查信息是否存在
            Dictionary <string, object> dic1 = new Dictionary <string, object>();

            dic1.Add("Mobile", mobile);
            ConnectorEntity entConnector = DbAccess.GetEntity <ConnectorEntity>(ConnectorBusiness._TableName, dic1);

            if (entConnector == null)
            {
                return(-2);
            }
            if (entConnector.Id == downConnectorId)
            {
                return(-1);
            }
            Dictionary <string, object> dic2 = new Dictionary <string, object>();

            //dic2.Add("UpConnectorId", entConnector.Id);
            //dic2.Add("UpBuyerId", upBuyerId);
            dic2.Add("DownConnectorId", downConnectorId);

            RelationEntity entRelation = DbAccess.GetEntity <RelationEntity>(TableName, dic2);

            if (entRelation != null && entRelation.UpConnectorId != 0)
            {
                return(-1);
            }
            RelationEntity ent = new RelationEntity();

            ent.UpConnectorId   = entConnector.Id;
            ent.UpBuyerId       = upBuyerId;
            ent.DownConnectorId = downConnectorId;
            ent.Status          = 0;//0待处理
            ent.AddTime         = DateTime.Now;
            ent.UpdateTime      = DateTime.Now;
            ent.InvitedFrom     = 0;
            val = DbAccess.ExecuteInsert(TableName, ent);
            return(val);
        }
Example #11
0
        /// <summary>
        /// Get the relation with the specified faction identifiers.
        /// </summary>
        /// <returns>The border.</returns>
        /// <param name="sourceFactionId">Source faction identifier.</param>
        /// <param name="targetFactionId">Target faction identifier.</param>
        public RelationEntity Get(string sourceFactionId, string targetFactionId)
        {
            Tuple <string, string> key = new Tuple <string, string>(sourceFactionId, targetFactionId);

            if (!relationEntitiesStore.ContainsKey(key))
            {
                return(null);
            }

            RelationEntity relationEntity = relationEntitiesStore[key];

            if (relationEntity == null)
            {
                throw new EntityNotFoundException(
                          $"{sourceFactionId}-{targetFactionId}",
                          nameof(BorderEntity).Replace("Entity", ""));
            }

            return(relationEntity);
        }
Example #12
0
        /// <summary>
        /// 通过下游卖家mobile获取信息
        /// </summary>
        /// <param name="mobile">卖家mobile</param>
        /// <returns>大于0成功,否则失败</returns>
        /// <remarks>
        /// <list type="bullet">
        /// <item></item>
        /// </list>
        /// </remarks>
        public IResultResponse CheckDownConnector(string mobile, int upConnectorId)
        {
            //检查信息是否存在
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("Mobile", mobile);
            List <ConnectorEntity> entConnectors = DbAccess.GetEntity <List <ConnectorEntity> >(ConnectorBusiness._TableName, dic);

            if (entConnectors == null || entConnectors.Count == 0)
            {
                return(ResultResponse.ExceptionResult("您尚未成为连接器合作商"));
            }
            IResultResponse resultResponse = null;

            foreach (ConnectorEntity entConnector in entConnectors)
            {
                Dictionary <string, object> dic2 = new Dictionary <string, object>();
                dic2.Add("DownConnectorId", entConnector.Id);
                dic2.Add("Status", 1);
                RelationEntity relate = DbAccess.GetEntity <RelationEntity>(TableName, dic2);
                if (relate != null && relate.Id > 0)
                {
                    if (relate.UpConnectorId == upConnectorId)
                    {
                        resultResponse = ResultResponse.ExceptionResult("您已成为该合作商的下游合作商");
                    }
                    else
                    {
                        resultResponse = ResultResponse.ExceptionResult("您已拥有上游合作商,不能再添加");
                    }
                    continue;
                }
                GroupEntity group = (GroupEntity) new GroupBusiness(_dapperFactory).GetEntity("Id=" + entConnector.GroupId);
                Dictionary <string, object> result = new Dictionary <string, object>();
                result.Add("Id", entConnector.Id);
                result.Add("Domain", group.Domain);
                resultResponse = ResultResponse.GetSuccessResult(result.ToJson());
                break;
            }
            return(resultResponse);
        }
Example #13
0
        private void FillSaveParameters(RelationEntity relation, IDbCommand sqlCommand)
        {
            IDbDataParameter parameter;

            parameter = dataAccess.GetNewDataParameter("@relationType", DbType.Int32);

            parameter.Value = relation.RelationType;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@idTarget", DbType.Int32);

            parameter.Value = relation.IdTarget;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@idSource", DbType.Int32);

            parameter.Value = relation.IdSource;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@idDataModel", DbType.Int32);

            parameter.Value = relation.IdDataModel;
            sqlCommand.Parameters.Add(parameter);
        }
Example #14
0
        public IResultResponse ValidateCode(int connectorId, int upConnectorId, string validateCode)
        {
            ConnectorEntity connector = (ConnectorEntity) new ConnectorBusiness().GetEntity("Id=" + connectorId);

            if (connector == null || connector.Id == null || connector.Id < 1)
            {
                return(ResultResponse.ExceptionResult("您尚未成为连接器合作商"));
            }
            string mobile = DES.Encode(string.Format("{0}|{1}|{2}|{3}|{4}|{5}", connector.Mobile, connector.Mobile, connector.Mobile, connector.Mobile, connector.Mobile, connector.Mobile));

            GroupEntity     group = (GroupEntity) new GroupBusiness().GetEntity("Id=" + connector.GroupId);
            IResultResponse res   = ApiRequest.GetResponse(group.Domain, "vast.account.supplier.validatecode.validate", new Dictionary <string, string>()
            {
                { "Mobile", mobile },
                { "ValidateCode", validateCode },
                { "ProprietorId", connector.SellerId.ToString() },
            });

            if (res.Success)
            {
                ConnectorEntity upConnector = (ConnectorEntity) new ConnectorBusiness().GetEntity("Id=" + upConnectorId);
                RelationEntity  ent         = new RelationEntity();
                ent.UpConnectorId   = upConnectorId;
                ent.UpBuyerId       = 0;
                ent.DownConnectorId = connectorId;
                ent.Status          = 0;//0待处理
                ent.AddTime         = DateTime.Now;
                ent.UpdateTime      = DateTime.Now;
                ent.InvitedFrom     = 0;
                int val = DbAccess.ExecuteInsert(TableName, ent);
                if (val > 0)
                {
                    return(ResultResponse.GetSuccessResult("您已成功申请成为该商家的下游合作商,请等待审核"));
                }
            }
            return(ResultResponse.ExceptionResult(res.Message));
        }
        /// <summary>
        /// Busca una relacion en el modelo de datos y la retorna como un RelationWpf
        /// </summary>
        /// <param name="dataModel">modelo de datos</param>
        /// <param name="relationEntity">relacion</param>
        /// <returns>Un RelationWpf si existe la relacion en el modelo de datos, null si no existe.</returns>
        public static RelationWpf GetRelationFromDataModelEntity(DataModel dataModel, RelationEntity relationEntity)
        {
            TableWpf source = null;
            TableWpf target = null;

            foreach (TableWpf table in dataModel.Tables)
            {
                if (String.CompareOrdinal(relationEntity.Source.Name, table.Name) == 0)
                {
                    source = table;
                }
                if (String.CompareOrdinal(relationEntity.Target.Name, table.Name) == 0)
                {
                    target = table;
                }
            }
            if (source != null && target != null)
            {
                RelationWpf relation = new RelationWpf(source, target, (RelationType)relationEntity.RelationType);
                return(relation);
            }
            return(null);
        }
Example #16
0
 /// <summary>
 /// Function to Save a RelationEntity in the database.
 /// </summary>
 /// <param name="relation">RelationEntity to save</param>
 /// <exception cref="ArgumentNullException">
 /// if <paramref name="relation"/> is not a <c>RelationEntity</c>.
 /// </exception>
 /// <exception cref="UtnEmallDataAccessException">
 /// If an DbException occurs in the try block while accessing the database.
 /// </exception>
 public void Save(RelationEntity relation)
 {
     Save(relation, null);
 }
Example #17
0
 public IResultResponse CheckUpConnector(int downConnectorId, int id, int status)
 {
     try
     {
         ClearCache();
         int             val           = 0;
         ConnectorEntity downConnector = (ConnectorEntity) new ConnectorBusiness(_dapperFactory).GetEntity("Id=" + downConnectorId);
         if (downConnector == null || Utils.ToInt(downConnector.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在该下游"));
         }
         RelationEntity entRelation = (RelationEntity) new RelationBusiness(_dapperFactory).GetEntity("Id=" + id + " and DownConnectorId=" + downConnectorId);
         if (entRelation == null || Utils.ToInt(entRelation.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在合作关系"));
         }
         ConnectorEntity connector = (ConnectorEntity) new ConnectorBusiness(_dapperFactory).GetEntity("Id=" + entRelation.UpConnectorId);
         if (connector == null || Utils.ToInt(connector.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在该上游"));
         }
         GroupEntity group = (GroupEntity) new GroupBusiness(_dapperFactory).GetEntity("Id=" + connector.GroupId);
         if (group == null || Utils.ToInt(group.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在该上游机组"));
         }
         if (status == 1 && entRelation.UpBuyerId == 0)
         {
             DataTable allRecord = DBTable("DownConnectorId=" + downConnectorId + " and Status=1");
             if (allRecord != null && allRecord.Rows.Count > 0)
             {
                 return(ResultResponse.ExceptionResult("已存在上游合作商"));
             }
             //快马上游插入下游客户账户
             long ts = Utils.ToUnixTime(DateTime.Now.AddMinutes(1));
             Dictionary <string, string> dic = new Dictionary <string, string>()
             {
                 { "fk_id", connector.SellerId.ToString() },
                 { "expire", ts.ToString() },
                 { "mobile", downConnector.Mobile }
             };
             string          json   = dic.ToJson();
             string          token  = ECF.Security.AES.Encode(json);
             IResultResponse result = ApiRequest.GetResponse(group.Domain, "account.add.downconnector", new Dictionary <string, string>()
             {
                 { "exchange_token", HttpUtility.UrlEncode(token) },
             });
             if (result.Success)
             {
                 Dictionary <string, object> content = result.Content as Dictionary <string, object>;
                 int storeId = content.ToInt("StoreId", 0);
                 entRelation.IsDefault = 1;
                 entRelation.UpBuyerId = storeId;
             }
             else
             {
                 return(ResultResponse.ExceptionResult("上游零售商关联失败,请稍后在试"));
             }
         }
         entRelation.IsDefault  = 1;
         entRelation.Status     = status;
         entRelation.UpdateTime = DateTime.Now;
         val = DbAccess.ExecuteUpdate(TableName, entRelation, new string[] { "Id" });
         if (val > 0)
         {
             return(ResultResponse.GetSuccessResult(1));
         }
         return(ResultResponse.ExceptionResult("接受邀请失败"));
     }
     catch (Exception ex)
     {
         return(ResultResponse.ExceptionResult(ex));
     }
 }
Example #18
0
        /// <summary>
        /// Function to Save a RelationEntity in the database.
        /// </summary>
        /// <param name="relation">RelationEntity to save</param>
        /// <param name="scope">Interna structure to avoid circular reference locks. Provide an instance when calling from other data access object.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="relation"/> is not a <c>RelationEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// If an DbException occurs in the try block while accessing the database.
        /// </exception>
        public void Save(RelationEntity relation, Dictionary <string, IEntity> scope)
        {
            if (relation == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Create a unique key to identify the object in the internal scope
            string scopeKey = relation.Id.ToString(NumberFormatInfo.InvariantInfo) + "Relation";

            if (scope != null)
            {
                // If it's on the scope return it, don't save again
                if (scope.ContainsKey(scopeKey))
                {
                    return;
                }
            }
            else
            {
                // Create a new scope if it's not provided
                scope = new Dictionary <string, IEntity>();
            }

            try
            {
                // Open a DbConnection and a new transaction if it isn't on a higher level one
                if (!isGlobalTransaction)
                {
                    dbConnection = dataAccess.GetNewConnection();
                    dbConnection.Open();
                    dbTransaction = dbConnection.BeginTransaction();
                }

                string commandName = "";
                bool   isUpdate    = false;
                // Check if it is an insert or update command

                if (relation.IsNew || !DataAccessConnection.ExistsEntity(relation.Id, "Relation", "idRelation", dbConnection, dbTransaction))
                {
                    commandName = "SaveRelation";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UpdateRelation";
                }
                // Create a db command
                IDbCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction);
                sqlCommand.CommandType = CommandType.StoredProcedure;
                // Add parameters values to current command

                IDbDataParameter parameter;
                if (isUpdate)
                {
                    parameter       = dataAccess.GetNewDataParameter("@idRelation", DbType.Int32);
                    parameter.Value = relation.Id;
                    sqlCommand.Parameters.Add(parameter);
                }

                FillSaveParameters(relation, sqlCommand);
                // Execute the command
                if (isUpdate)
                {
                    sqlCommand.ExecuteNonQuery();
                }
                else
                {
                    IDbDataParameter parameterIdOutput = dataAccess.GetNewDataParameter("@idRelation", DbType.Int32);
                    parameterIdOutput.Direction = ParameterDirection.ReturnValue;
                    sqlCommand.Parameters.Add(parameterIdOutput);

                    sqlCommand.ExecuteNonQuery();
                    relation.Id = Convert.ToInt32(parameterIdOutput.Value, NumberFormatInfo.InvariantInfo);
                }

                scopeKey = relation.Id.ToString(NumberFormatInfo.InvariantInfo) + "Relation";
                // Add entity to current internal scope

                scope.Add(scopeKey, relation);
                // Save collections of related objects to current entity
                // Save objects related to current entity
                // Update
                // Close transaction if initiated by me
                if (!isGlobalTransaction)
                {
                    dbTransaction.Commit();
                }
                // Update new and changed flags

                relation.IsNew   = false;
                relation.Changed = false;
            }
            catch (DbException dbException)
            {
                // Rollback transaction
                if (!isGlobalTransaction)
                {
                    dbTransaction.Rollback();
                }
                // Rethrow as custom exception
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Close connection if initiated by me
                if (!isGlobalTransaction)
                {
                    dbConnection.Close();
                    dbConnection  = null;
                    dbTransaction = null;
                }
            }
        }
Example #19
0
 /// <summary>
 /// Function to Delete a RelationEntity from database.
 /// </summary>
 /// <param name="relation">RelationEntity to delete</param>
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="relation"/> is not a <c>RelationEntity</c>.
 /// </exception>
 /// <exception cref="UtnEmallDataAccessException">
 /// If an DbException occurs in the try block while accessing the database.
 /// </exception>
 public void Delete(RelationEntity relation)
 {
     Delete(relation, null);
 }
Example #20
0
        /// <summary>
        /// Function to Delete a RelationEntity from database.
        /// </summary>
        /// <param name="relation">RelationEntity to delete</param>
        /// <param name="scope">Internal structure to avoid circular reference locks. Must provide an instance while calling from other data access object.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="relation"/> is not a <c>RelationEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// If an DbException occurs in the try block while accessing the database.
        /// </exception>
        public void Delete(RelationEntity relation, Dictionary <string, IEntity> scope)
        {
            if (relation == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            try
            {
                // Open connection and initialize a transaction if needed
                if (!isGlobalTransaction)
                {
                    dbConnection = dataAccess.GetNewConnection();
                    dbConnection.Open();
                    dbTransaction = dbConnection.BeginTransaction();
                }
                // Reload the entity to ensure deletion of older data

                relation = this.Load(relation.Id, true);
                if (relation == null)
                {
                    throw new UtnEmallDataAccessException("Error retrieving data while trying to delete.");
                }
                // Create a command for delete
                string     cmdText    = "DeleteRelation";
                IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                sqlCommand.CommandType = CommandType.StoredProcedure;
                // Add values to parameters

                IDbDataParameter parameterID = dataAccess.GetNewDataParameter("@idRelation", DbType.Int32);
                parameterID.Value = relation.Id;
                sqlCommand.Parameters.Add(parameterID);
                // Execute the command

                sqlCommand.ExecuteNonQuery();
                // Delete related objects
                // Commit transaction if is mine
                if (!isGlobalTransaction)
                {
                    dbTransaction.Commit();
                }
                // Remove entity from loaded objects

                inMemoryEntities.Remove(relation.Id);
                // Remove entity from current internal scope

                if (scope != null)
                {
                    string scopeKey = relation.Id.ToString(NumberFormatInfo.InvariantInfo) + "Relation";
                    scope.Remove(scopeKey);
                }
            }
            catch (DbException dbException)
            {
                // Rollback transaction
                if (!isGlobalTransaction)
                {
                    dbTransaction.Rollback();
                }
                // Rethrow as custom exception
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Close connection if it was initiated by this instance
                if (!isGlobalTransaction)
                {
                    dbConnection.Close();
                    dbConnection  = null;
                    dbTransaction = null;
                }
            }
        }
Example #21
0
        /// <summary>
        /// Function to load a RelationEntity from database.
        /// </summary>
        /// <param name="id">The ID of the record to load</param>
        /// <param name="loadRelation">if is true load the relation</param>
        /// <param name="scope">Internal structure used to avoid circular reference locks, must be provided if calling from other data access object</param>
        /// <returns>The entity instance</returns>
        /// <exception cref="UtnEmallDataAccessException">
        /// If a DbException occurs while accessing the database.
        /// </exception>
        public RelationEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope)
        {
            // Build a key for internal scope object
            string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "Relation";

            if (scope != null)
            {
                // If scope contains the object it was already loaded,
                // return it to avoid circular references
                if (scope.ContainsKey(scopeKey))
                {
                    return((RelationEntity)scope[scopeKey]);
                }
            }
            else
            {
                // If there isn't a current scope create one
                scope = new Dictionary <string, IEntity>();
            }

            RelationEntity relation = null;

            // Check if the entity was already loaded by current data access object
            // and return it if that is the case

            if (inMemoryEntities.ContainsKey(id))
            {
                relation = inMemoryEntities[id];
                // Add current object to current load scope

                scope.Add(scopeKey, relation);
            }
            else
            {
                bool closeConnection = false;
                try
                {
                    // Open a new connection if it isn't on a transaction
                    if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0)
                    {
                        closeConnection = true;
                        dbConnection    = dataAccess.GetNewConnection();
                        dbConnection.Open();
                    }

                    string cmdText = "SELECT idRelation, relationType, idTarget, idSource, idDataModel, timestamp FROM [Relation] WHERE idRelation = @idRelation";
                    // Create the command

                    IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                    // Create the Id parameter for the query

                    IDbDataParameter parameter = dataAccess.GetNewDataParameter("@idRelation", DbType.Int32);
                    parameter.Value = id;
                    sqlCommand.Parameters.Add(parameter);
                    // Use a DataReader to get data from db

                    IDataReader reader = sqlCommand.ExecuteReader();
                    relation = new RelationEntity();

                    if (reader.Read())
                    {
                        // Load fields of entity
                        relation.Id = reader.GetInt32(0);

                        relation.RelationType = reader.GetInt32(1);
                        relation.IdTarget     = reader.GetInt32(2);
                        relation.IdSource     = reader.GetInt32(3);
                        relation.IdDataModel  = reader.GetInt32(4);
                        // Add current object to the scope

                        scope.Add(scopeKey, relation);
                        // Add current object to cache of loaded entities

                        inMemoryEntities.Add(relation.Id, relation);
                        // Read the timestamp and set new and changed properties

                        relation.Timestamp = reader.GetDateTime(5);
                        relation.IsNew     = false;
                        relation.Changed   = false;
                        // Close the reader

                        reader.Close();
                        // Load related objects if required

                        if (loadRelation)
                        {
                            LoadRelationTarget(relation, scope);
                            LoadRelationSource(relation, scope);
                        }
                    }
                    else
                    {
                        reader.Close();
                    }
                }
                catch (DbException dbException)
                {
                    // Catch DBException and rethrow as custom exception
                    throw new UtnEmallDataAccessException(dbException.Message, dbException);
                }
                finally
                {
                    // Close connection if it was opened by ourself
                    if (closeConnection)
                    {
                        dbConnection.Close();
                    }
                }
            }
            // Return the loaded entity
            return(relation);
        }