Example #1
0
        /// <summary>Audit entity deleted.</summary>
        /// <param name="entry">The entry.</param>
        /// <param name="record">The record.</param>
        /// <param name="prefix">The prefix.</param>
        public static void AuditEntityDeleted(AuditEntry entry, ObjectStateEntry objectStateEntry, DbDataRecord record, string prefix = "")
        {
            for (var i = 0; i < record.FieldCount; i++)
            {
                var name  = record.GetName(i);
                var value = record.GetValue(i);

                if (entry.Parent.Configuration.UseNullForDBNullValue && value == DBNull.Value)
                {
                    value = null;
                }

                var valueRecord = value as DbDataRecord;
                if (valueRecord != null)
                {
                    // Complex Type
                    AuditEntityDeleted(entry, objectStateEntry, valueRecord, string.Concat(prefix, name, "."));
                }
                else if (objectStateEntry.EntityKey.EntityKeyValues.Any(x => x.Key == name) || entry.Parent.CurrentOrDefaultConfiguration.IsAuditedProperty(entry.Entry, string.Concat(prefix, name)))
                {
                    var auditEntryProperty = entry.Parent.Configuration.AuditEntryPropertyFactory != null?
                                             entry.Parent.Configuration.AuditEntryPropertyFactory(new AuditEntryPropertyArgs(entry, objectStateEntry, string.Concat(prefix, name), value, null)) :
                                                 new AuditEntryProperty();

                    auditEntryProperty.IsKey = objectStateEntry.EntitySet.ElementType.KeyMembers.Any(x => x.Name == name);

                    auditEntryProperty.Build(entry, string.Concat(prefix, name), value, null);
                    entry.Properties.Add(auditEntryProperty);
                }
            }
        }
        /// <summary>Audit entity modified.</summary>
        /// <param name="audit">The audit to use to add changes made to the context.</param>
        /// <param name="entry">The entry.</param>
        /// <param name="objectStateEntry">The object state entry.</param>
        /// <param name="orginalRecord">The orginal record.</param>
        /// <param name="currentRecord">The current record.</param>
        /// <param name="prefix">The prefix.</param>
        public static void AuditEntityModified(Audit audit, AuditEntry entry, ObjectStateEntry objectStateEntry, DbDataRecord orginalRecord, DbUpdatableDataRecord currentRecord, string prefix = "")
        {
            for (var i = 0; i < orginalRecord.FieldCount; i++)
            {
                var name          = orginalRecord.GetName(i);
                var originalValue = orginalRecord.GetValue(i);
                var currentValue  = currentRecord.GetValue(i);

                var valueRecord = originalValue as DbDataRecord;
                if (valueRecord != null)
                {
                    // Complex Type
                    AuditEntityModified(audit, entry, objectStateEntry, valueRecord, currentValue as DbUpdatableDataRecord, string.Concat(prefix, name, "."));
                }

                else if (objectStateEntry.EntityKey.EntityKeyValues.Any(x => x.Key == name) ||
                         entry.Parent.CurrentOrDefaultConfiguration.IsAuditedProperty(entry.Entry, name))
                {
                    if (!audit.Configuration.IgnorePropertyUnchanged ||
                        objectStateEntry.EntityKey.EntityKeyValues.Any(x => x.Key == name) ||
                        !Equals(currentValue, originalValue))
                    {
                        var auditEntryProperty = entry.Parent.Configuration.AuditEntryPropertyFactory != null?
                                                 entry.Parent.Configuration.AuditEntryPropertyFactory(new AuditEntryPropertyArgs(entry, objectStateEntry, string.Concat(prefix, name), originalValue, currentValue)) :
                                                     new AuditEntryProperty();

                        auditEntryProperty.Build(entry, string.Concat(prefix, name), originalValue, currentValue);
                        entry.Properties.Add(auditEntryProperty);
                    }
                }
            }
        }
        // </Snippet5>
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (Data != null)
            {
                if (Data is System.Data.Common.DbDataRecord)
                {
                    DbDataRecord temp = (DbDataRecord)Data;
                    for (int i = 0; i < temp.FieldCount; ++i)
                    {
                        writer.Write("<TD>");
                        writer.Write(temp.GetValue(i).ToString());
                        writer.Write("</TD>");
                    }
                }
                else
                {
                    writer.Write("<TD>" + Data.ToString() + "</TD>");
                }
            }

            else
            {
                writer.Write("<TD>This is a test</TD>");
            }
        }
Example #4
0
        /// <summary>
        /// Checks to see if the specified <see cref="EntityObject"/> has modified properties.
        /// If all properties have the same values, set the state to Unchanged.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entity">The entity.</param>
        public static void CheckIfModified(this ObjectContext context, EntityObject entity)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (entity.EntityState == EntityState.Modified)
            {
                ObjectStateEntry   state          = context.ObjectStateManager.GetObjectStateEntry(entity);
                DbDataRecord       originalValues = state.OriginalValues;
                CurrentValueRecord currentValues  = state.CurrentValues;

                for (int i = 0; i < originalValues.FieldCount; i++)
                {
                    object original = originalValues.GetValue(i);
                    object current  = currentValues.GetValue(i);
                    if (!original.Equals(current))// && (!(original is byte[]) || !((byte[])original).SequenceEqual((byte[])current)))
                    {
                        // Something has actually changed.  We can return now.
                        return;
                    }
                }

                // We made it through the loop without finding any changed properties
                state.ChangeState(EntityState.Unchanged);
            }
        }
        internal static T GetValueOrDefault <T>(this DbDataRecord record, string name)
        {
            var idx = record.GetOrdinal(name);

            return(record.IsDBNull(idx)
                ? default
                : (T)record.GetValue(idx));
        }
        public static T GetValueOrDefault <T>([NotNull] this DbDataRecord record, [NotNull] string name)
        {
            var idx = record.GetOrdinal(name);

            return(record.IsDBNull(idx)
                ? default
                : (T)record.GetValue(idx));
        }
        public static object GetValue(this DbDataRecord dr, string columnName)
        {
            Check.ArgNotNull(dr, nameof(dr));

            int ordinal = dr.GetOrdinal(columnName);

            return(dr.GetValue(ordinal));
        }
Example #8
0
        static void TestProduct(string esqlQuery, Dictionary <string, object> parametes)
        {
            using (EntityConnection conn =
                       new EntityConnection("name=AdventureWorksEntities"))
            {
                conn.Open();

                try
                {
                    // Create an EntityCommand.
                    using (EntityCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = esqlQuery;
                        foreach (KeyValuePair <string, object> kvp in parametes)
                        {
                            cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
                        }

                        // Execute the command.
                        using (EntityDataReader rdr =
                                   cmd.ExecuteReader(CommandBehavior.SequentialAccess))
                        {
                            // The result returned by this query contains
                            // Address complex Types.
                            while (rdr.Read())
                            {
                                int col = rdr.FieldCount;
                                if (rdr.FieldCount > 3)
                                {
                                    col = 3;
                                }
                                for (int i = 0; i < col; i++)
                                {
                                    Console.Write("{0}   ", rdr[i]);
                                }
                                Console.WriteLine();
                                if (rdr.Depth > 0)
                                {
                                    // Display Address information.
                                    DbDataRecord nestedRecord =
                                        rdr[0] as DbDataRecord;
                                    for (int i = 0; i < nestedRecord.FieldCount; i++)
                                    {
                                        Console.WriteLine("  " + nestedRecord.GetName(i) +
                                                          ": " + nestedRecord.GetValue(i));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (EntityException ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                conn.Close();
            }
        }
        public override void Hook(IIdentifiable entity, HookEntityMetadata metadata)
        {
            //// Check is auditable context, contains auditlog table
            IAuditableContext context = metadata.CurrentContext as IAuditableContext;

            if (context == null)
            {
                return;
            }

            //// Get current username
            var userName = "******";

            if (this.HttpContext != null)
            {
                userName = this.HttpContext.User.Identity.Name;
            }

            //// Get entry, entity type and associate etadata
            var entry      = ((IObjectContextAdapter)metadata.CurrentContext).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity);
            var entityType = entity.GetType();

            TypeDescriptor.AddProvider(new AssociatedMetadataTypeTypeDescriptionProvider(entityType), entityType);

            //// Get is entity modified property contains requireAudit Field, and add auditlog
            var properties = TypeDescriptor.GetProperties(entityType);

            foreach (string propertyName in entry.GetModifiedProperties())
            {
                //// Check is property need io
                var propertyDescriptor = properties.Find(propertyName, true);
                var propRequireAudit   = propertyDescriptor.Attributes.OfType <RequireAuditAttribute>().FirstOrDefault();
                if (propRequireAudit == null)
                {
                    continue;
                }

                //// Get original value
                DbDataRecord original = entry.OriginalValues;
                string       oldValue = original.GetValue(original.GetOrdinal(propertyName)).ToString();

                //// Get new value
                CurrentValueRecord current  = entry.CurrentValues;
                string             newValue = current.GetValue(current.GetOrdinal(propertyName)).ToString();

                //// Write Audit Log
                AuditLog auditLog = new AuditLog();
                auditLog.IdentifyKey  = entity.IdentifyKey;
                auditLog.IdentifyName = entityType.Name;
                auditLog.OriginValue  = oldValue;
                auditLog.NewValue     = newValue;
                auditLog.CreatedAt    = DateTime.Now;
                auditLog.CreatedBy    = userName;

                context.AuditLogs.Add(auditLog);
            }
        }
Example #10
0
 /// <summary>
 /// Sets the primary key of a <seealso cref="DBObject"/> using the specified <paramref name="record"/>.
 /// </summary>
 /// <param name="record"><seealso cref="DbDataRecord"/> to get the primary key from.</param>
 internal void SetPrimaryKey(DbDataRecord record)
 {
     for (int i = 0; i < record.FieldCount; i++)
     {
         if (record.GetName(i) == PrimaryKeyPropertyInfo.Name)
         {
             SetPrimaryKey((int)record.GetValue(i));
         }
     }
 }
Example #11
0
        /// <summary>
        /// 获得值
        /// </summary>
        /// <param name="record">DbDataRecord</param>
        /// <param name="name">名称</param>
        /// <returns></returns>
        public static object GetValue(this DbDataRecord record, [NotNull] string name)
        {
            int ordinal = record.GetOrdinal(name);

            if (!record.IsDBNull(ordinal))
            {
                return(record.GetValue(ordinal));
            }
            return(null);
        }
Example #12
0
        /// <summary>
        /// 获得值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="record">DbDataRecord</param>
        /// <param name="name">名称</param>
        /// <returns></returns>
        public static T GetValueOrDefault <T>(
            [NotNull] this DbDataRecord record,
            [NotNull] string name)
        {
            int ordinal = record.GetOrdinal(name);

            if (!record.IsDBNull(ordinal))
            {
                return((T)GetValue <T>(record.GetValue(ordinal)));
            }
            return(default(T));
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DbDataRecord d = value as DbDataRecord;

            if (d == null)
            {
                return(null);
            }
            object r = d.GetValue(System.Convert.ToInt32(parameter));

            return(r);
        }
Example #14
0
        static private void ComplexTypeWithEntityCommand()
        {
            //<snippetComplexTypeWithEntityCommand>
            using (EntityConnection conn =
                       new EntityConnection("name=CustomerComplexAddrContext"))
            {
                conn.Open();

                // Create a query that returns Address complex type.
                string esqlQuery =
                    @"SELECT VALUE customers FROM
                        CustomerComplexAddrContext.CCustomers
                        AS customers WHERE customers.CustomerId < 3";
                try
                {
                    // Create an EntityCommand.
                    using (EntityCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = esqlQuery;
                        // Execute the command.
                        using (EntityDataReader rdr =
                                   cmd.ExecuteReader(CommandBehavior.SequentialAccess))
                        {
                            // The result returned by this query contains
                            // Address complex Types.
                            while (rdr.Read())
                            {
                                // Display CustomerID
                                Console.WriteLine("Customer ID: {0}",
                                                  rdr["CustomerId"]);
                                // Display Address information.
                                DbDataRecord nestedRecord =
                                    rdr["Address"] as DbDataRecord;
                                Console.WriteLine("Address:");
                                for (int i = 0; i < nestedRecord.FieldCount; i++)
                                {
                                    Console.WriteLine("  " + nestedRecord.GetName(i) +
                                                      ": " + nestedRecord.GetValue(i));
                                }
                            }
                        }
                    }
                }
                catch (EntityException ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                conn.Close();
            }
            //</snippetComplexTypeWithEntityCommand>
        }
        protected void GridViewOrders_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                TableCell tc = e.Row.Cells[e.Row.Cells.Count - 1];

                DbDataRecord    ddr = e.Row.DataItem as DbDataRecord;
                URLPopUpControl upc = LoadControl("URLPopUpControl.ascx") as URLPopUpControl;

                upc.URLToPopup = "WebFormPopup.aspx?UC=OrderBase&OrderId=" + ddr.GetValue(0).ToString();
                upc.Text       = "Toon order";
                tc.Controls.Add(upc);
            }
        }
Example #16
0
        private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int          QuestionNumber;
                DbDataRecord selectedRow = (DbDataRecord)QuestionDataGridView.SelectedItem; // get the values of the selected row
                QuestionNumber = Convert.ToInt16(selectedRow.GetValue(0));

                BL.Question deletedQuestion = new BL.Question();
                deletedQuestion.DeletedQuestion(QuestionNumber);

                FillDataGrid();
            }
            catch { return; }
        }
        /// <summary>
        ///   Converts a single DbDataRecord object into something else.
        ///   The destination type must have a default constructor.
        /// </summary>
        /// <typeparam name = "T"></typeparam>
        /// <param name = "record"></param>
        /// <returns></returns>
        public static T ConvertTo <T>(this DbDataRecord record) where T : new()
        {
            var item = new T();

            for (int f = 0; f < record.FieldCount; f++)
            {
                var p = item.GetType().GetProperty(record.GetName(f));
                if (p != null && p.PropertyType == record.GetFieldType(f))
                {
                    p.SetValue(item, record.GetValue(f), null);
                }
            }

            return(item);
        }
Example #18
0
        static public void ComplexTypeWithEntityCommand()
        {
            //<snippetComplexTypeWithEntityCommand>
            using (EntityConnection conn =
                       new EntityConnection("name=AdventureWorksEntities"))
            {
                conn.Open();

                string esqlQuery = @"SELECT VALUE contacts FROM
                        AdventureWorksEntities.Contacts AS contacts 
                        WHERE contacts.ContactID == @id";

                // Create an EntityCommand.
                using (EntityCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = esqlQuery;
                    EntityParameter param = new EntityParameter();
                    param.ParameterName = "id";
                    param.Value         = 3;
                    cmd.Parameters.Add(param);

                    // Execute the command.
                    using (EntityDataReader rdr =
                               cmd.ExecuteReader(CommandBehavior.SequentialAccess))
                    {
                        // The result returned by this query contains
                        // Address complex Types.
                        while (rdr.Read())
                        {
                            // Display CustomerID
                            Console.WriteLine("Contact ID: {0}",
                                              rdr["ContactID"]);
                            // Display Address information.
                            DbDataRecord nestedRecord =
                                rdr["EmailPhoneComplexProperty"] as DbDataRecord;
                            Console.WriteLine("Email and Phone Info:");
                            for (int i = 0; i < nestedRecord.FieldCount; i++)
                            {
                                Console.WriteLine("  " + nestedRecord.GetName(i) +
                                                  ": " + nestedRecord.GetValue(i));
                            }
                        }
                    }
                }
                conn.Close();
            }
            //</snippetComplexTypeWithEntityCommand>
        }
    public static bool GetBoolean(this DbDataRecord rec, string fieldName)
    {
        var index = rec.GetOrdinal(fieldName);
        var value = rec.GetValue(index);

        if (value is bool || value is Boolean)
        {
            return((bool)value);
        }
        else if (value is SByte || value is sbyte)
        {
            return((sbyte)value == 1);
        }
        else
        {
            return(rec.GetInt64(index) == 1);
        }
    }
Example #20
0
        /// <summary>Audit entity deleted.</summary>
        /// <param name="entry">The entry.</param>
        /// <param name="record">The record.</param>
        /// <param name="prefix">The prefix.</param>
        public static void AuditEntityDeleted(AuditEntry entry, DbDataRecord record, string prefix = "")
        {
            for (var i = 0; i < record.FieldCount; i++)
            {
                var name  = record.GetName(i);
                var value = record.GetValue(i);

                var valueRecord = value as DbDataRecord;
                if (valueRecord != null)
                {
                    // Complex Type
                    AuditEntityDeleted(entry, valueRecord, string.Concat(prefix, name, "."));
                }
                else if (entry.Parent.CurrentOrDefaultConfiguration.IsAuditedProperty(entry.Entry, name))
                {
                    entry.Properties.Add(new AuditEntryProperty(entry, string.Concat(prefix, name), value, null));
                }
            }
        }
        public static void AuditEntityModified(Audit audit, AuditEntry entry, DbDataRecord orginalRecord, DbUpdatableDataRecord currentRecord, string prefix = "")
        {
            for (var i = 0; i < orginalRecord.FieldCount; i++)
            {
                var name          = orginalRecord.GetName(i);
                var originalValue = orginalRecord.GetValue(i);
                var currentValue  = currentRecord.GetValue(i);

                var valueRecord = originalValue as DbDataRecord;
                if (valueRecord != null)
                {
                    // Complex Type
                    AuditEntityModified(audit, entry, valueRecord, currentValue as DbUpdatableDataRecord, string.Concat(prefix, name, "."));
                }
                else
                {
                    if (audit.Configuration.IncludePropertyUnchanged || !Equals(currentValue, originalValue))
                    {
                        entry.Properties.Add(new AuditEntryProperty(string.Concat(prefix, name), originalValue, currentValue));
                    }
                }
            }
        }
Example #22
0
        public void GetEnumeratorTest()
        {
            this.fixture.ExecuteCommand(command => {
                command.CommandText = "SELECT * FROM ORDERS";
                using (var reader = command.ExecuteReader()) {
                    IEnumerator enumerator = reader.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        DbDataRecord record = (DbDataRecord)enumerator.Current;
                        Assert.Equal(reader.FieldCount, record.FieldCount);
                        Assert.Equal(reader.GetInt32(0), record.GetInt32(0));
                        Assert.Equal(reader.GetString(1), record.GetString(1));
                        Assert.Equal(reader.GetInt32(2), record.GetInt32(2));
                        Assert.Equal(reader.GetDateTime(3), record.GetDateTime(3));
                        Assert.Equal(reader.GetDateTime(4), record.GetDateTime(4));
                        Assert.Equal(reader.GetValue(5), record.GetValue(5));
                        Assert.Equal(reader.GetInt32(6), record.GetInt32(6));
                        Assert.Equal(reader.GetDecimal(7), record.GetDecimal(7));
                        reader.Read();
                    }
                }
            });
        }
        public override object GetValue(object item)
        {
            EntityUtil.CheckArgumentNull(item, "item");

            if (!_itemType.IsAssignableFrom(item.GetType()))
            {
                throw EntityUtil.IncompatibleArgument();
            }

            object propertyValue;

            DbDataRecord dbDataRecord = item as DbDataRecord;

            if (dbDataRecord != null)
            {
                propertyValue = (dbDataRecord.GetValue(dbDataRecord.GetOrdinal(_property.Name)));
            }
            else
            {
                propertyValue = LightweightCodeGenerator.GetValue(_property, item);
            }

            return(propertyValue);
        }
Example #24
0
        protected void GridViewRoleObjectAccess_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DbDataRecord sroa = e.Row.DataItem as DbDataRecord;

                e.Row.FindControl("CheckBoxCreate").Visible  = sroa.GetValue(8).ToString().IndexOf("C") >= 0;
                e.Row.FindControl("CheckBoxRead").Visible    = sroa.GetValue(8).ToString().IndexOf("R") >= 0;
                e.Row.FindControl("CheckBoxUpdate").Visible  = sroa.GetValue(8).ToString().IndexOf("U") >= 0;
                e.Row.FindControl("CheckBoxDelete").Visible  = sroa.GetValue(8).ToString().IndexOf("D") >= 0;
                e.Row.FindControl("CheckBoxExecute").Visible = sroa.GetValue(8).ToString().IndexOf("X") >= 0;

                /*
                 * (e.Row.FindControl("CheckBoxCreate") as CheckBox).Checked = Convert.ToBoolean(sroa.GetValue(3));
                 * (e.Row.FindControl("CheckBoxRead") as CheckBox).Checked  = Convert.ToBoolean( sroa.GetValue(4));
                 * (e.Row.FindControl("CheckBoxUpdate") as CheckBox).Checked  = Convert.ToBoolean(sroa.GetValue(5));
                 * (e.Row.FindControl("CheckBoxDelete") as CheckBox).Checked  = Convert.ToBoolean(sroa.GetValue(6));
                 * (e.Row.FindControl("CheckBoxExecute") as CheckBox).Checked = Convert.ToBoolean(sroa.GetValue(7));
                 * */

                LabelIDResultSet.Text = LabelIDResultSet.Text + sroa.GetValue(0).ToString() + ",";
            }
        }
Example #25
0
        private static object GetDisplayValue(AuditEntryState state, NavigationProperty navigationProperty, IMemberAccessor displayMember, DbDataRecord values)
        {
            if (values == null)
            {
                return(null);
            }

            var association = navigationProperty.RelationshipType as AssociationType;

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

            // only support first constraint
            var referentialConstraint = association.ReferentialConstraints.FirstOrDefault();

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

            var toProperties = referentialConstraint
                               .ToProperties
                               .Select(p => p.Name)
                               .ToList();

            var fromProperties = referentialConstraint
                                 .FromProperties
                                 .Select(p => p.Name)
                                 .ToList();

            // make sure key columns match
            if (fromProperties.Count != toProperties.Count)
            {
                return(null);
            }

            var edmType = referentialConstraint
                          .FromProperties
                          .Select(p => p.DeclaringType)
                          .FirstOrDefault();

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

            var entitySet = state.ObjectContext.GetEntitySet(edmType.FullName);

            var sql = new StringBuilder();

            sql.Append("SELECT VALUE t.")
            .Append(displayMember.Name)
            .Append(" FROM ")
            .Append(entitySet.Name)
            .Append(" as t")
            .Append(" WHERE ");

            var parameters = new List <ObjectParameter>();

            for (int index = 0; index < fromProperties.Count; index++)
            {
                if (parameters.Count > 1)
                {
                    sql.Append(" AND ");
                }

                string fromProperty = fromProperties[index];
                string toProperty   = toProperties[index];
                var    value        = values.GetValue(toProperty);
                var    name         = "@" + fromProperty;

                sql.Append(" t.")
                .Append(fromProperty)
                .Append(" == ")
                .Append(name);

                parameters.Add(new ObjectParameter(fromProperty, value));
            }

            var q = state.ObjectContext.CreateQuery <object>(
                sql.ToString(),
                parameters.ToArray());

            return(q.FirstOrDefault());
        }
 /// <summary>
 ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
 ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
 ///     any release. You should only use it directly in your code with extreme caution and knowing that
 ///     doing so can result in application failures when updating to a new Entity Framework Core release.
 /// </summary>
 public static T GetFieldValue <T>(this DbDataRecord record, string name)
 => (T)record.GetValue(record.GetOrdinal(name));
 public static T GetFieldValue <T>([JB.NotNull] this DbDataRecord record, [JB.NotNull] string name)
 => (T)record.GetValue(record.GetOrdinal(name));
        public void Write(object o)
        {
            if (o == null)
            {
                Write("null");
            }
            else if (o == _omittedValue)
            {
                Write("{...}");
            }
            else if (o is DateTime)
            {
                Write("{");
                Write(((DateTime)o).ToString());
                Write("}");
            }
            else if (o is ValueType)
            {
                Write(o.ToString());
            }
            else if (o is Type)
            {
                Write(((Type)o).Name);
            }
            else if (o is Exception)
            {
                Write("EXCEPTION: " + o.ToString());
            }
            else if (o is byte[])
            {
                byte[] arr    = (byte[])o;
                int    length = Math.Min(arr.Length, 32);
                string t      = "Byte[" + arr.Length + "] = " + BitConverter.ToString(arr, 0, length) + ((length != arr.Length) ? "..." : "");
                Write(t);
            }
            else if (o is string)
            {
                Write("\"");
                Write(o as string);
                Write("\"");
            }
            else
            {
                if (o is ObjectCollectionCache)
                {
                    Write(((ObjectCollectionCache)o).OriginalType);
                }
                else
                {
                    Write(o.GetType());
                }
                Write(" ");

                if (_ancestors.Contains(o) || (Level > _maximumDepth + 1))
                {
                    Write("{...}");
                }
                else
                {
                    _ancestors.Push(o);
                    if (o is IEnumerable)
                    {
                        var members = from object element in (o as IEnumerable)
                                      select new Member {
                            Name = null, Value = element
                        };

                        Write(members);
                    }
                    else if (o is DbDataRecord)
                    {
                        DbDataRecord rec = o as DbDataRecord;

                        var members = from element in Enumerable.Range(0, rec.FieldCount)
                                      select new Member {
                            Name = rec.GetName(element), Value = rec.IsDBNull(element) ? null : rec.GetValue(element)
                        };

                        Write(members);
                    }
                    else
                    {
                        var members = from element in o.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance)
                                      let p                 = element as PropertyInfo
                                                      let f = element as FieldInfo
                                                              where p != null || f != null
                                                              select new Member {
                            Name = element.Name, Value = p != null?p.GetValue(o, null) : f.GetValue(o)
                        };

                        // remove members which cause explosion of the tree
                        if (o is EntityReference)
                        {
                            members = members.Select(c => new Member {
                                Name = c.Name, Value = (c.Name == "RelationshipSet" ? _omittedValue : c.Value)
                            });
                        }

                        Write(members);
                    }
                }
            }
        }
Example #29
0
 /// <summary>
 /// Sets each <seealso cref="PropertyInfo"/> of the <paramref name="dbObject"/> to the value of
 /// the <paramref name="record"/>, so long as the <seealso cref="PropertyInfo"/> is not the
 /// primary key of the <paramref name="dbObject"/>.
 /// </summary>
 /// <typeparam name="T">Type of <seealso cref="DBObject"/></typeparam>
 /// <param name="dbObject"><seealso cref="DBObject"/> to set <seealso cref="PropertyInfo"/> values for.</param>
 /// <param name="record"><seealso cref="DbDataRecord"/> to read values from.</param>
 private static void SetPropertyValuesFromRecord <T>(ref T dbObject, DbDataRecord record) where T : DBObject
 {
     for (int i = 0; i < record.FieldCount; i++)
     {
         if (record.GetName(i) != dbObject.PrimaryKeyPropertyInfo.Name)
         {
             dbObject.GetType().GetProperty(record.GetName(i)).SetValue(dbObject, record.GetValue(i));
         }
     }
 }
Example #30
0
        private string GetEntryValueInString(ObjectStateEntry entry, bool isOrginal)
        {
            StringBuilder sb = new StringBuilder();

            foreach (string propertyName in entry.GetModifiedProperties())
            {
                DbDataRecord       original = entry.OriginalValues;
                CurrentValueRecord current  = entry.CurrentValues;
                //if (original.GetValue(original.GetOrdinal(propertyName)).ToString() != current.GetValue(current.GetOrdinal(propertyName)).ToString())
                //{
                if (isOrginal)
                {
                    sb.Append(String.Format("Property:{0} Value:{1} /", propertyName, original.GetValue(original.GetOrdinal(propertyName)).ToString()));
                }
                else
                {
                    sb.Append(String.Format("Property:{0} Value:{1} /", propertyName, current.GetValue(current.GetOrdinal(propertyName)).ToString()));
                }
                //}
            }
            return(sb.ToString());

            //if (entry.Entity is EntityObject)
            //{
            //    object target = CloneEntity((EntityObject)entry.Entity);
            //    foreach (string propName in entry.GetModifiedProperties())
            //    {
            //        object setterValue = null;
            //        if (isOrginal)
            //        {
            //            //Get orginal value
            //            setterValue = entry.OriginalValues[propName];
            //        }
            //        else
            //        {
            //            //Get orginal value
            //            setterValue = entry.CurrentValues[propName];
            //        }
            //        //Find property to update
            //        PropertyInfo propInfo = target.GetType().GetProperty(propName);
            //        //update property with orgibal value
            //        if (setterValue == DBNull.Value)
            //        {//
            //            setterValue = null;
            //        }
            //        propInfo.SetValue(target, setterValue, null);
            //    }//end foreach

            //    XmlSerializer formatter = new XmlSerializer(target.GetType());
            //    XDocument document = new XDocument();

            //    using (XmlWriter xmlWriter = document.CreateWriter())
            //    {
            //        formatter.Serialize(xmlWriter, target);
            //    }
            //    return document.Root.ToString();
            //}
            //return null;
        }