示例#1
0
 /// <summary>
 /// Adds the record to list.
 /// </summary>
 /// <param name="list">The list.</param>
 /// <param name="record">The record.</param>
 private static void AddRecordToList(List <IActiveRecord> list, IActiveRecord record)
 {
     lock (list)
     {
         list.Add(record);
     }
 }
示例#2
0
        protected override Module CreateRecord(IActiveRecord activeRecord)
        {
            ModuleX dalModule = (ModuleX)activeRecord;

            return(new Module(dalModule.Id, dalModule.ProjectID, dalModule.Name, dalModule.Description,
                              dalModule.StartDate, dalModule.ExpEndDate, dalModule.ActEndDate));
        }
示例#3
0
        public virtual DataTable Join(IActiveRecord that, Func <dynamic, dynamic, bool> condition, params ScopedAttribute[] selectedColumns)
        {
            var results = BuildMergeResultsSet(that);

            var thisIdx = Index;
            var thatIdx = that.Index;

            DataRow[] leftData = new DataRow[GetData().Rows.Count],
            rightData = new DataRow[(that.GetData().Rows.Count)];

            GetData().Rows.CopyTo(leftData, 0);
            that.GetData().Rows.CopyTo(rightData, 0);

            var data = from leftRow in leftData
                       from rightRow in rightData
                       let left                         = new VariablesWrapper(vn => leftRow[vn], (vn, v) => leftRow[vn] = v)
                                              let right = new VariablesWrapper(vn => rightRow[vn], (vn, v) => rightRow[vn] = v)
                                                          where condition(left, right)
                                                          select BuildMergeResultRow(results, leftRow, rightRow);

            foreach (var row in data)
            {
                results.Rows.Add(row);
            }

            //selectedColumns = selectedColumns?.SelectFrom(n => n.ToLowerInvariant());
            results = results.ReduceColumnsToAliases(selectedColumns);
            //FinalizeColumns(results, selectedColumns);

            GoTo(thisIdx);
            that.GoTo(thatIdx);
            return(results);
        }
        public T CreateActiveRecord(IObject esriObject)
        {
            IActiveRecord objectWrapper = (IActiveRecord)Activator.CreateInstance(typeof(T));

            objectWrapper.UnderlyingObject = esriObject;
            return((T)objectWrapper);
        }
示例#5
0
        private static object FindRelatedObjects(this IActiveRecord wrapper, FieldAttribute relationshipAttribute)
        {
            List <IActiveRecord> result;

            if (!(relationshipAttribute is RelationshipAttribute))
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(),
                                                         "O atributo não é do tipo HasMany. Não foi possível retornar os objetos relacionados.");
            }

            var attribute = relationshipAttribute as RelationshipAttribute;

            if (attribute.GetType() == typeof(HasManyAttribute))
            {
                return(HasMany(wrapper, relationshipAttribute));
            }

            if (attribute.GetType() == typeof(OneToOneAttribute))
            {
                return(OneToOne(wrapper, relationshipAttribute));
            }

            if (attribute.GetType() == typeof(BelongsToAttribute))
            {
                return(Belongs(wrapper, relationshipAttribute));
            }

            throw new ActiveRecordAttributeException(wrapper.GetType(), "Não foi possível buscar os objetos relacionados.");
        }
示例#6
0
        /// <summary>
        /// This method is responsible for translanting between coded domain names
        /// and their values, setting into UnderlyingObject the correct value.
        /// </summary>
        /// <remarks>
        /// Imagine a ICodedDomain like:
        /// 1 = "Alphanumeric"
        /// 2 = "Geographic"
        ///
        /// This method will aways set the value to 1 when passed
        /// "Alphanumeric"
        /// </remarks>
        /// <exception cref="ActiveRecrdAttributeException"></exception>
        /// <param name="wrapper"></param>
        /// <param name="propertyName"></param>
        /// <param name="displayValue"></param>
        /// <returns></returns>
        private static void SetDisplayValue(this IActiveRecord wrapper, FieldAttribute fieldAtt, string displayValue)
        {
            if (wrapper.UnderlyingObject == null)
            {
                FetchUnderlyingObject(wrapper);
            }

            if (!(fieldAtt is DomainFieldAttribute))
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(), "O atributo não é tipo domínio.");
            }

            DomainFieldAttribute domainField = fieldAtt as DomainFieldAttribute;
            ICodedValueDomain    domain      = wrapper.UnderlyingObject.Fields.get_Field(domainField.Index).Domain as ICodedValueDomain;

            if (domain == null)
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(), "Não foi possível localizar o domínio.");
            }

            for (var i = 0; i <= domain.CodeCount - 1; i++)
            {
                if (domain.get_Name(i) == displayValue)
                {
                    object codedValue = domain.get_Value(i);
                    wrapper.UnderlyingObject.set_Value(domainField.Index, codedValue);
                }
            }
        }
示例#7
0
 protected override Task CreateRecord(IActiveRecord activeRecord)
 {
     DAL.Task dalTask = (DAL.Task)activeRecord;
     return(new Task(dalTask.Id, dalTask.ModuleID, dalTask.Name, dalTask.Description,
                     (TaskComplexity)dalTask.Complexity, dalTask.StartDate, dalTask.ExpEndDate,
                     dalTask.ActEndDate));
 }
        /// <summary>
        /// This method retrieves an IActiveRecord by it's ObjectID.
        /// </summary>
        /// <param name="oid">int</param>
        /// <exception cref="RepositoryQueryException"></exception>
        /// <returns>T (IActiveRecord)</returns>
        public T SingleByOID(int oid)
        {
            ITable  table      = GetTable;
            IObject esriObject = null;

            try
            {
                esriObject = table.GetRow(oid) as IObject;
            }
            catch (COMException comEx)
            {
                _log.Error("Ocorreu um erro COM ao tentar buscar o objeto via OBJECTID.", comEx);
            }
            catch (Exception ex)
            {
                _log.Error("Ocorreu um erro desconhecido ao tentar buscar o objeto via OBJECTID", ex);
            }

            if (esriObject == null)
            {
                throw new RepositoryQueryException(
                          "O objeto pesquisado não pode ser encontrado.",
                          GetWorkspaceDefinition, GetTableDefinition, IsBeingEdited,
                          String.Format("OID = {0}", oid.ToString()));
            }

            IActiveRecordFactory <T> factory = new ActiveRecordFactory <T>();

            IActiveRecord objectWrapper = factory.CreateActiveRecord(esriObject);

            return((T)objectWrapper);
        }
        public T CreateActiveRecord(int oid)
        {
            IActiveRecord objectWrapper = (IActiveRecord)Activator.CreateInstance(typeof(T));

            objectWrapper.ObjectId = oid;
            return((T)objectWrapper);
        }
        public List <T> Filter(IQueryFilter filter)
        {
            var     results = new List <T>();
            var     table   = this.GetTable;
            ICursor cursor  = null;

            if (table == null)
            {
                throw new ActiveRecordAttributeException(
                          this.GetType(),
                          "Não foi possível encontrar o atributo de tabela.");
            }

            try
            {
                var count = table.RowCount(filter);

                if (count == 0)
                {
                    return(results);
                }

                // if we have more records then treshold,
                // just grab the object id field
                if (count > GetTableDefinition.RecordTreshold)
                {
                    filter.SubFields = table.OIDFieldName;
                }

                cursor = table.Search(filter, false);
                IActiveRecordFactory <T> factory = new ActiveRecordFactory <T>();
                IObject tempObject = null;

                while ((tempObject = cursor.NextRow() as IObject) != null)
                {
                    if (count <= GetTableDefinition.RecordTreshold)
                    {
                        IActiveRecord wrapper = factory.CreateActiveRecord(tempObject);
                        results.Add((T)wrapper);
                    }
                    else
                    {
                        IActiveRecord proxyWrapper = factory.CreateActiveRecord(tempObject.OID);
                        results.Add((T)proxyWrapper);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (cursor != null)
                {
                    Marshal.ReleaseComObject(cursor);
                }
            }
            return(results);
        }
        /// <summary>
        /// Retrieves a collection of IActiveRecord using a specific filter.
        /// </summary>
        /// <param name="filter">Filtering rules</param>
        /// <returns>List(T) (IActiveRecord)</returns>
        public List <T> FilterLazy(IQueryFilter filter)
        {
            List <T> results = new List <T>();
            ITable   table   = this.GetTable;
            ICursor  cursor  = null;

            if (table == null)
            {
                throw new RepositoryException(
                          "Não foi possível obter a tabela para pesquisa",
                          GetWorkspaceDefinition,
                          GetTableDefinition,
                          IsBeingEdited);
            }

            // lets just grab the object id field to speed things up a bit
            filter.SubFields = table.OIDFieldName;

            try
            {
                int count = table.RowCount(filter);

                if (count == 0)
                {
                    return(results);
                }

                cursor = table.Search(filter, false);
                IActiveRecordFactory <T> factory = new ActiveRecordFactory <T>();
                IObject tempObject = null;

                while ((tempObject = cursor.NextRow() as IObject) != null)
                {
                    IActiveRecord proxyWrapper = factory.CreateActiveRecord(tempObject.OID);
                    results.Add((T)proxyWrapper);
                }
            }
            catch (COMException comEx)
            {
                throw new RepositoryQueryException(
                          "Ocorreu um erro durante a pesquisa.",
                          comEx,
                          GetWorkspaceDefinition,
                          GetTableDefinition,
                          IsBeingEdited,
                          filter.WhereClause);
            }
            finally
            {
                if (cursor != null)
                {
                    Marshal.ReleaseComObject(cursor);
                }
            }
            return(results);
        }
示例#12
0
        public static RepositoryAttribute GetRepositoryDefinition(this IActiveRecord wrapper)
        {
            object[] attributes = wrapper.GetType().GetCustomAttributes(typeof(RepositoryAttribute), true);

            if (attributes.Length != 1)
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(), "Não foi possível definir o atributo repositório para este tipo.");
            }

            return(attributes[0] as RepositoryAttribute);
        }
示例#13
0
        private static object HasMany(this IActiveRecord wrapper, FieldAttribute relationshipAttribute)
        {
            if (!(relationshipAttribute is RelationshipAttribute))
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(),
                                                         "O atributo não é do tipo HasMany. Não foi possível retornar os objetos relacionados.");
            }

            HasManyAttribute hasMany = relationshipAttribute as HasManyAttribute;

            object[] customAttributes = hasMany.ClassType.GetCustomAttributes(typeof(RepositoryAttribute), true);
            if (customAttributes.Length != 1)
            {
                throw new ActiveRecordAttributeException(hasMany.ClassType, "Não foi possível encontrar o controlador da classe.");
            }

            RepositoryAttribute controlled = (RepositoryAttribute)customAttributes[0];
            object relatedController       = Activator.CreateInstance(controlled.ControllerType);

            if (relatedController == null)
            {
                throw new ActiveRecordAttributeException(controlled.ControllerType, "Não foi possível instanciar o controller.");
            }

            PrimaryFieldAttribute pkAtt = wrapper.GetPrimaryKeyDefinition();

            if (pkAtt == null)
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(), "Não foi possível encontrar a chave primária da classe.");
            }

            IQueryFilter filter = new QueryFilterClass();

            filter.WhereClause = String.Format(pkAtt.QuoteValue ? "{0} = '{1}'" : "{0} = {1}", hasMany.FieldName, wrapper.UnderlyingObject.get_Value(pkAtt.Index));

            if (!String.IsNullOrEmpty(hasMany.OrderBy))
            {
                IQueryFilterDefinition definition = filter as IQueryFilterDefinition;
                definition.PostfixClause = hasMany.OrderBy;
            }

            // prepare the method for invoke
            // check if the method is lazy or not
            MethodInfo filterMethod = null;

            filterMethod = controlled.ControllerType.GetMethod(hasMany.Lazy ? "FilterLazy" : "Filter");

            var parameters = new object[1];

            parameters[0] = filter;

            // invoke and return
            return(filterMethod.Invoke(relatedController, parameters));
        }
        public List <T> FindAll()
        {
            var results = new List <T>();
            var table   = GetTable;

            ICursor cursor = null;

            if (table == null)
            {
                throw new ArgumentException("Não foi possível obter a tabela para pesquisa.");
            }

            try
            {
                IQueryFilter filter = new QueryFilterClass {
                    WhereClause = String.Empty
                };

                var count = table.RowCount(filter);

                if (count > GetTableDefinition.RecordTreshold)
                {
                    filter.SubFields = table.OIDFieldName;
                }

                cursor = table.Search(null, false);
                IActiveRecordFactory <T> factory = new ActiveRecordFactory <T>();
                IObject tempObject = null;

                while ((tempObject = cursor.NextRow() as IObject) != null)
                {
                    if (count <= GetTableDefinition.RecordTreshold)
                    {
                        IActiveRecord wrapper = factory.CreateActiveRecord(tempObject);
                        results.Add((T)wrapper);
                    }
                    else
                    {
                        IActiveRecord proxyWrapper = factory.CreateActiveRecord(tempObject.OID);
                        results.Add((T)proxyWrapper);
                    }
                }
            }
            finally
            {
                if (cursor != null)
                {
                    Marshal.ReleaseComObject(cursor);
                }
            }
            return(results);
        }
        public T Create()
        {
            ITable table = this.GetTable;

            if (table == null)
            {
                throw new ArgumentException("A tabela não pode ser obtida.");
            }

            IActiveRecordFactory <T> factory       = new ActiveRecordFactory <T>();
            IActiveRecord            objectWrapper = factory.CreateActiveRecord(table.CreateRow() as IObject);

            return((T)objectWrapper);
        }
示例#16
0
        protected virtual DataTable BuildMergeResultsSet(IActiveRecord that)
        {
            var col     = that.GetData().Columns;
            var results = new DataTable();

            foreach (DataColumn c in Data.Columns)
            {
                results.Columns.Add(new DataColumn($"{this.TableName}.{c.ColumnName}"));
            }
            foreach (DataColumn c in col)
            {
                results.Columns.Add(new DataColumn($"{that.TableName}.{c.ColumnName}"));
            }
            return(results);
        }
示例#17
0
        public static IActiveRecordState ValidateCar(IActiveRecord record)
        {
            IActiveRecordState state = new ActiveRecordState();

            state.Record = record;

            var car = (Car)record;

            if (car.CarName.Length > 10)
            {
                state.AddRuleViolation("CarName", "O nome do carro não pode ter mais de 10 letras.");
            }

            return(state);
        }
        protected virtual DataTable BuildMergeResultsSet(IActiveRecord left, IActiveRecord right)
        {
            var colL    = left.GetData().Columns;
            var colR    = right.GetData().Columns;
            var results = new DataTable();

            foreach (DataColumn c in colL)
            {
                results.Columns.Add(new DataColumn($"{left.TableName}.{c.ColumnName}"));
            }
            foreach (DataColumn c in colR)
            {
                results.Columns.Add(new DataColumn($"{right.TableName}.{c.ColumnName}"));
            }
            return(results);
        }
示例#19
0
        public void Delete(IActiveRecord record)
        {
            if (record == null)
            {
                return;
            }

            if (Deleted.Contains(record))
            {
                return;
            }

            OnBeforeDelete(new ActiveRecordTransactionEventArgs(record));

            _deleted.Add(record);
        }
示例#20
0
        /// <summary>
        /// Gets the Owner of a specific IActiveRecord
        /// </summary>
        /// <param name="wrapper">IActiveRecord</param>
        /// <param name="propertyName">string</param>
        /// <returns>object</returns>
        private static object Belongs(this IActiveRecord wrapper, FieldAttribute relationshipAttribute)
        {
            if (!(relationshipAttribute is RelationshipAttribute))
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(),
                                                         "O atributo não é do tipo HasMany. Não foi possível retornar os objetos relacionados.");
            }

            var attribute = relationshipAttribute as BelongsToAttribute;

            object[] customAttributes = attribute.ClassType.GetCustomAttributes(typeof(RepositoryAttribute), true);
            if (customAttributes.Length != 1)
            {
                throw new ActiveRecordAttributeException(attribute.ClassType, "Não foi possível encontrar o controlador da classe.");
            }

            RepositoryAttribute controlled = (RepositoryAttribute)customAttributes[0];
            object relatedController       = Activator.CreateInstance(controlled.ControllerType);

            if (relatedController == null)
            {
                throw new ActiveRecordAttributeException(controlled.ControllerType, "Não foi possível instanciar o controller.");
            }

            IQueryFilter filter = new QueryFilterClass();

            filter.WhereClause = String.Format(attribute.QuoteValue ? "{0} = '{1}'" : "{0} = {1}", attribute.FieldName, wrapper.UnderlyingObject.get_Value(attribute.ParentValueFieldIndex));

            // prepare the method for invoke
            // check if the method is lazy or not
            MethodInfo singleMethod = null;

            singleMethod = controlled.ControllerType.GetMethod("SingleByPrimaryKey");

            var parameters = new object[1];

            parameters[0] = wrapper.UnderlyingObject.get_Value(attribute.ParentValueFieldIndex);
            //case not exist value in foreign key, return null
            if (parameters[0] == null || parameters[0].ToString().Equals(""))
            {
                return(null);
            }

            // invoke and return
            return(singleMethod.Invoke(relatedController, parameters));
        }
示例#21
0
        public static void SetBlobValue(this IActiveRecord wrapper, FieldAttribute attribute, object value)
        {
            if (!(value is IPersistStream))
            {
                throw new ActiveRecordException("Nâo é possível persistir um objeto que não implementa IPersistStream.");
            }

            IMemoryBlobStream memStream = new MemoryBlobStreamClass();
            IObjectStream     objStream = new ObjectStreamClass();

            objStream.Stream = memStream;
            IPersistStream persist = (IPersistStream)value;

            persist.Save(memStream, 0);

            wrapper.UnderlyingObject.set_Value(attribute.Index, memStream);
        }
        /// <summary>
        /// Presets the message details.
        /// </summary>
        /// <param name="msg">The MSG.</param>
        private void PresetMessageDetails(IActiveRecord rec)
        {
            if (rec.GetType() == typeof(IncomingMessage))
            {
                IncomingMessage msg = rec as IncomingMessage;
                txtMessageContent.Text = msg.Message;
                pnlMessage.Visible = true;
                pnlWapPush.Visible = false;
            }
            else if (rec.GetType() == typeof(OutgoingMessage))
            {
                 OutgoingMessage msg = rec as OutgoingMessage;
                 OutgoingMessageType messageType = (OutgoingMessageType)StringEnum.Parse(typeof(OutgoingMessageType), msg.MessageType);
                 if (messageType == OutgoingMessageType.SMS)
                 {
                     txtMessageContent.Text = msg.Message;
                     pnlMessage.Visible = true;
                     pnlWapPush.Visible = false;
                 }
                 else if (messageType == OutgoingMessageType.WAPPush)
                 {
                     cboMessageType.Text = msg.MessageType;
                     txtWapPushMessage.Text = msg.Message;
                     txtWapPushUrl.Text = msg.WapUrl;
                     cboWapPushSignal.Text = msg.WapSignal;

                     if (msg.WapCreateDate.HasValue)
                     {
                         chkWapPushCreated.Checked = true;
                         dtpWapPushCreated.Value = msg.WapCreateDate.Value;
                     }

                     if (msg.WapExpiryDate.HasValue)
                     {
                         chkWapPushExpiry.Checked = true;
                         dtpWapPushExpiryDate.Value = msg.WapExpiryDate.Value;
                     }

                     pnlMessage.Visible = false;
                     pnlWapPush.Visible = true;
                 }
            }
        }
示例#23
0
        /// <summary>
        /// This method is responsible for translating between coded domain values
        /// and their names, returning the correct name.
        /// </summary>
        /// Imagine a ICodedDomain like:
        /// 1 = "Alphanumeric"
        /// 2 = "Geographic"
        ///
        /// This method will always return "Alphanumeric" for the value 1,
        /// fetched from UnderlyingObject
        /// </remarks>
        /// <exception cref="ActiveRecrdAttributeException"></exception>
        /// <param name="wrapper">IActiveRecord</param>
        /// <param name="propertyName">string</param>
        /// <returns>string</returns>
        private static string GetDisplayValue(this IActiveRecord wrapper, FieldAttribute fieldAtt)
        {
            if (wrapper.UnderlyingObject == null)
            {
                FetchUnderlyingObject(wrapper);
            }

            if (!(fieldAtt is DomainFieldAttribute))
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(), "Não é possível obter o atributo de domínio.");
            }

            DomainFieldAttribute domainField = fieldAtt as DomainFieldAttribute;
            ICodedValueDomain    domain      = wrapper.UnderlyingObject.Fields.get_Field(domainField.Index).Domain as ICodedValueDomain;

            if (domain == null)
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(),
                                                         String.Format("Não foi possível localizar o domínio {0}.", domainField.DomainName));
            }

            string codedValue   = wrapper.UnderlyingObject.get_Value(domainField.Index).ToString();
            string displayValue = String.Empty;

            for (int i = 0; i <= domain.CodeCount - 1; i++)
            {
                if (domain.get_Value(i).ToString() == codedValue)
                {
                    displayValue = domain.get_Name(i);
                    break;
                }
            }

            if (displayValue == String.Empty)
            {
                return(codedValue);
            }
            else
            {
                return(displayValue);
            }
        }
示例#24
0
        public static object GetBlobValue(this IActiveRecord wrapper, FieldAttribute attribute)
        {
            IMemoryBlobStream blobStream = wrapper.UnderlyingObject.get_Value(attribute.Index) as IMemoryBlobStream;

            if (blobStream == null)
            {
                return(null);
            }

            IObjectStream stream = new ObjectStreamClass()
            {
                Stream = blobStream
            };

            IPersistStream blob = new PropertySetClass();

            blob.Load(blobStream);

            return(blob as IPropertySet);
        }
示例#25
0
        /// <summary>
        /// This method is responsible for fetching lazy IObjects;
        /// </summary>
        /// <exception cref="ActiveRecordAttributeException"></exception>
        /// <exception cref="ArgumentException"></exception>
        private static void FetchUnderlyingObject(this IActiveRecord wrapper)
        {
            // we can only fetch this object if it's a proxy
            if (!wrapper.IsProxy && wrapper.UnderlyingObject != null)
            {
                return;
            }

            if (wrapper.ObjectId == 0)
            {
                return;
            }

            // find out which controller is responsible for this type of object
            RepositoryAttribute controlledAtt = null;
            var customAtts = wrapper.GetType().GetCustomAttributes(typeof(RepositoryAttribute), true);

            // test if out attribute is configured properly
            if (customAtts.Length == 1)
            {
                controlledAtt = (RepositoryAttribute)customAtts[0];
            }

            if (controlledAtt == null)
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(), "Não foi possível localizar o atributo controller.");
            }

            var controllerType = controlledAtt.ControllerType;
            var controller     = Activator.CreateInstance(controllerType);

            // lets get the method we need and set our parameters
            var singleMethod = controllerType.GetMethod("SingleByOID");
            var parameters   = new object[1];

            parameters[0] = wrapper.ObjectId;

            // finally invoke the method and set our underlyingObject.
            wrapper.UnderlyingObject =
                ((IActiveRecord)singleMethod.Invoke(controller, parameters)).UnderlyingObject;
        }
        protected virtual DataTable Join(IExecutionContext ctx, IActiveRecord left, IActiveRecord right)
        {
            var results   = BuildMergeResultsSet(left, right);
            var condition = _join;
            var leftIdx   = left.Index;
            var rightIdx  = right.Index;

            for (left.MoveFirst(); !left.IsAtEnd; left.MoveNext())
            {
                for (right.MoveFirst(); !right.IsAtEnd; right.MoveNext())
                {
                    if (!left.IsAtEnd && !right.IsAtEnd && (bool)condition.GetGenericValue(ctx))
                    {
                        var dr = AddMergeResultRow(results, left.CurrentRow, right.CurrentRow);
                    }
                }
            }

            left.GoTo(leftIdx);
            right.GoTo(rightIdx);
            return(results);
        }
示例#27
0
        /// <summary>
        /// Retrieves the Primary Key attribute without the need to know
        /// the property name
        /// </summary>
        /// <param name="wrapper">IActiveRecord</param>
        /// <returns>PrimaryFieldAttribute</returns>
        public static PrimaryFieldAttribute GetPrimaryKeyDefinition(this IActiveRecord wrapper)
        {
            PrimaryFieldAttribute pkAttribute = null;
            var t = wrapper.GetType();

            try
            {
                PropertyInfo[] properties = t.GetProperties();
                foreach (PropertyInfo pi in properties)
                {
                    object[] attributes = pi.GetCustomAttributes(typeof(PrimaryFieldAttribute), true);

                    if (attributes.Length != 1)
                    {
                        continue;
                    }

                    pkAttribute = (PrimaryFieldAttribute)attributes[0];
                    break;
                }
            }
            catch (AmbiguousMatchException ambEx)
            {
                throw new ActiveRecordAttributeException(
                          wrapper.GetType(),
                          String.Format("A classe {0} possui dois ou mais atributos de chave primária.", t.Name),
                          ambEx);
            }
            catch (ArgumentException argEx)
            {
                throw new ActiveRecordAttributeException(
                          wrapper.GetType(),
                          String.Format("A classe {0} não possui nenhum atributo de chave primária.", t.Name),
                          argEx);
            }

            return(pkAttribute);
        }
示例#28
0
        protected override User CreateRecord(IActiveRecord activeRecord)
        {
            //TODO: optimize UserService.CreateRecord()
            DAL.User    dalUser = ((DAL.User)activeRecord);
            UserProfile profile = new UserProfile(dalUser.Id);

            User user = new User(dalUser.Id, (UserRole)dalUser.Role, dalUser.Username, dalUser.Password)
            {
                Address     = profile.Address,
                City        = profile.City,
                Email       = profile.Email,
                Enabled     = dalUser.Enabled,
                FirstName   = profile.FirstName,
                LastName    = profile.LastName,
                PhoneNumber = profile.PhoneNumber,
                State       = profile.State,
                ZipCode     = profile.Zip
            };

            user.ManagerID = GetManagerID(user.ID);

            return(user);
        }
示例#29
0
        /// <summary>
        /// Retrieves the Primary Keys attributes without the need to know
        /// the property name
        /// </summary>
        /// <param name="wrapper">IActiveRecord</param>
        /// <returns>List of PrimaryFieldAttribute</returns>
        public static List <PrimaryFieldAttribute> GetPrimarysKeyDefinitions(this IActiveRecord wrapper)
        {
            var lstPkAttribute = new List <PrimaryFieldAttribute>();
            var t = wrapper.GetType();

            try
            {
                var properties = t.GetProperties();
                foreach (var pi in properties)
                {
                    var attributes = pi.GetCustomAttributes(typeof(PrimaryFieldAttribute), true);

                    if (Equals(attributes.Length, 0))
                    {
                        continue;
                    }

                    lstPkAttribute.AddRange(attributes.Cast <PrimaryFieldAttribute>());
                }
            }
            catch (AmbiguousMatchException ambEx)
            {
                throw new ActiveRecordAttributeException(
                          wrapper.GetType(),
                          String.Format("A classe {0} possui dois ou mais atributos de chave primária.", t.Name),
                          ambEx);
            }
            catch (ArgumentException argEx)
            {
                throw new ActiveRecordAttributeException(
                          wrapper.GetType(),
                          String.Format("A classe {0} não possui nenhum atributo de chave primária.", t.Name),
                          argEx);
            }

            return(lstPkAttribute);
        }
示例#30
0
        /// <summary>
        /// Gets a value from a specific property.
        /// </summary>
        /// <remarks>
        /// If the IObjectWrapper is a proxy, this method fetches the IObject
        /// from the database and assigns it to this.UnderlyingObject
        /// </remarks>
        /// <exception cref="ActiveRecordAttributeException"></exception>
        /// <param name="propertyName">string</param>
        /// <returns>object</returns>
        public static object GetValue(this IActiveRecord wrapper, string propertyName)
        {
            if (wrapper.IsProxy)
            {
                wrapper.FetchUnderlyingObject();
            }

            if (wrapper.Deleted)
            {
                throw new ActiveRecordException("O objeto foi deletado e não é possível acessar seus atributos.");
            }

            FieldAttribute att = wrapper.GetFieldDefinition(typeof(FieldAttribute), propertyName);

            if (att == null)
            {
                throw new ActiveRecordAttributeException(wrapper.GetType(),
                                                         String.Format("Não foi possível localizar o atributo de campo para a propriedade {0}", propertyName));
            }

            if (att is DomainFieldAttribute)
            {
                return(GetDisplayValue(wrapper, att));
            }
            if (att is RelationshipAttribute)
            {
                return(FindRelatedObjects(wrapper, att));
            }

            if (att.FieldType == esriFieldType.esriFieldTypeBlob)
            {
                return(GetBlobValue(wrapper, att));
            }

            return(att.Index == -1 ? null : wrapper.UnderlyingObject.get_Value(att.Index));
        }
 public ActiveRecordTransactionEventArgs(IActiveRecord record)
 {
     _record = record;
 }
        public void Update(IActiveRecord record)
        {
            if (record == null)
                return;

            if (Updated.Contains(record))
                return;

            OnBeforeUpdate(new ActiveRecordTransactionEventArgs(record));

            _updated.Add(record);
        }
 /// <summary>
 /// This method is responsible for
 /// binding the control data to the
 /// database object.
 /// </summary>
 /// <returns></returns>
 public virtual ActiveRecordState BindToDatabase(IActiveRecord record, object control)
 {
     throw new NotImplementedException();
 }