示例#1
0
        //Assuming at least one CreditCard PaymentMethod has been created using the Orders UI
        public Guid GetPaymentMethodID()
        {
            Guid    creditCardPaymentMethodId = Guid.Empty;
            Boolean ccPmtMethodFound          = false;

            //Get all PaymentMethods
            DataSet         pmtMethods = orderCtx.GetPaymentMethods();
            DataTableReader reader     = pmtMethods.CreateDataReader();

            IEnumerator readerEnum = reader.GetEnumerator();

            while (readerEnum.MoveNext() && !ccPmtMethodFound)
            {
                DbDataRecord rec = (DbDataRecord)readerEnum.Current;
                switch (rec.GetInt32(rec.GetOrdinal("PaymentType")))
                {
                case (int)PaymentMethodTypes.CreditCard:
                    creditCardPaymentMethodId = rec.GetGuid(rec.GetOrdinal("PaymentMethodId"));
                    ccPmtMethodFound          = true;
                    break;
                }
            }

            if (Guid.Empty == creditCardPaymentMethodId)
            {
                throw new ApplicationException("This demo requires at least one CreditCard type of PaymentMethod to be defined!");
            }

            return(creditCardPaymentMethodId);
        }
示例#2
0
        public static String GetTimeZoneAdjustedDateTimeString(
            DbDataRecord dataRecord,
            String fieldName,
            double timeZoneOffset,
            String formatPattern)
        {
            String result = String.Empty;

            log.Debug("GetTimeZoneAdjustedDateTimeString fieldname was " + fieldName);


            if (
                (dataRecord != null) &&
                (fieldName != null)
                )
            {
                try
                {
                    if (dataRecord.GetOrdinal(fieldName) > -1)
                    {
                        if (dataRecord[fieldName] != DBNull.Value)
                        {
                            result = Convert.ToDateTime(dataRecord[fieldName]).AddHours(timeZoneOffset).ToString(formatPattern);
                        }
                    }
                }
                catch (InvalidCastException)
                { }
            }

            return(result);
        }
示例#3
0
        //Assuming at least one ShippingMethod has been created using the Orders UI
        public Guid GetShippingMethodID()
        {
            Guid    shippingMethodId = Guid.Empty;
            Boolean shipMethodFound  = false;

            //Get all PaymentMethods in default language - Hopefully there is one of each type
            DataSet         shipMethods = orderCtx.GetShippingMethods();
            DataTableReader reader      = shipMethods.CreateDataReader();

            IEnumerator readerEnum = reader.GetEnumerator();

            while (readerEnum.MoveNext() && !shipMethodFound)
            {
                DbDataRecord rec = (DbDataRecord)readerEnum.Current;
                shippingMethodId = rec.GetGuid(rec.GetOrdinal("ShippingMethodId"));
                shipMethodFound  = true;
            }

            if (Guid.Empty == shippingMethodId)
            {
                throw new ApplicationException("This demo requires at least one ShippingMethod to be defined!");
            }

            return(shippingMethodId);
        }
        public static Type GetFieldType(this DbDataRecord dr, string columnName)
        {
            Check.ArgNotNull(dr, nameof(dr));
            int ordinal = dr.GetOrdinal(columnName);

            return(dr.GetFieldType(ordinal));
        }
        public static bool GetBoolean(this DbDataRecord dr, string columnName)
        {
            Check.ArgNotNull(dr, nameof(dr));
            int ordinal = dr.GetOrdinal(columnName);

            return(dr.GetBoolean(ordinal));
        }
示例#6
0
        public static String GetTimeZoneAdjustedDateTimeString(
            DbDataRecord dataRecord,
            String fieldName,
            double timeZoneOffset)
        {
            String result = String.Empty;


            if (
                (dataRecord != null) &&
                (fieldName != null) &&
                (dataRecord.GetOrdinal(fieldName) > -1) &&
                (dataRecord[fieldName] != DBNull.Value)
                )
            {
                try
                {
                    result = Convert.ToDateTime(dataRecord[fieldName]).AddHours(timeZoneOffset).ToString();
                    //if (CultureInfo.CurrentCulture.Name == "fa-IR")
                    //{
                    //    PersianDateHelper dc = new PersianDateHelper();
                    //    result = dc.MtoSh(Convert.ToDateTime(result));
                    //}
                }
                catch (InvalidCastException) { }
                catch (ArgumentOutOfRangeException)
                {
                    result = DateTime.MinValue.ToString();
                }
            }

            return(result);
        }
        public static long GetInt64(this DbDataRecord dr, string columnName)
        {
            Check.ArgNotNull(dr, nameof(dr));
            int ordinal = dr.GetOrdinal(columnName);

            return(dr.GetInt64(ordinal));
        }
        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));
        }
        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 object IsDBNull(this DbDataRecord dr, string columnName)
        {
            Check.ArgNotNull(dr, nameof(dr));

            int ordinal = dr.GetOrdinal(columnName);

            return(dr.IsDBNull(ordinal));
        }
        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);
            }
        }
示例#12
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);
        }
示例#13
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 static long GetChars(
            this DbDataRecord dr,
            string columnName,
            long offset,
            char[] buffer,
            int bufferIndex,
            int length)
        {
            Check.ArgNotNull(dr, nameof(dr));

            int ordinal = dr.GetOrdinal(columnName);

            return(dr.GetChars(ordinal, offset, buffer, bufferIndex, length));
        }
    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);
        }
    }
        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);
        }
示例#17
0
        /// <summary>
        /// The event that triggers when
        /// the context savechanges method is called
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CurrentObjectContext_SavingChanges(object sender, EventArgs e)
        {
            try
            {
                ChangeTracker.DetectChanges(); // Important!
                System.Data.Entity.Core.Objects.ObjectContext           ctx = ((IObjectContextAdapter)this).ObjectContext;
                List <System.Data.Entity.Core.Objects.ObjectStateEntry> objectStateEntryList =
                    ctx.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Added
                                                                 | System.Data.Entity.EntityState.Modified
                                                                 | System.Data.Entity.EntityState.Deleted)
                    .ToList();

                foreach (System.Data.Entity.Core.Objects.ObjectStateEntry entry in objectStateEntryList)
                {
                    object[] list = entry.Entity.GetType().GetCustomAttributes(false);
                    // Only the models that marked with 'Auditable' attribute will be tracked
                    // Inside the model the properties that need to tracked needed to be marked with
                    // Auditable attribute
                    if (list.Count() == 0 || !((Nido.Common.Utilities.Attributes.AuditableAttribute)(list[0])).DoAudit)
                    {
                        continue;
                    }

                    TypeAttributes te    = entry.Entity.GetType().Attributes;
                    AuditTrail     audit = new AuditTrail();
                    audit.RevisionStamp = DateTime.Now;
                    audit.TableName     = entry.EntitySet.Name + entry.EntityKey;
                    audit.UserName      = UserName;
                    audit.SystemName    = SystemName;
                    if (!entry.IsRelationship)
                    {
                        switch (entry.State)
                        {
                        case System.Data.Entity.EntityState.Added:
                            // write log...
                        {
                            audit.NewData = GetEntryValueInString(entry);
                            audit.Actions = AuditActions.I.ToString();
                        }
                        break;

                        case System.Data.Entity.EntityState.Deleted:
                            // write log...
                        {
                            audit.TablePrimaryId = GetKeyValue(entry);
                            audit.OldData        = GetEntryValueInString(entry);
                            audit.Actions        = AuditActions.D.ToString();
                        }
                        break;

                        case System.Data.Entity.EntityState.Modified:
                        {
                            string xmlOld = "<?xml version='1.0' encoding='utf-16'?>  <" + (entry.EntitySet).Name
                                            + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>";
                            string xmlNew = "<?xml version='1.0' encoding='utf-16'?>  <" + (entry.EntitySet).Name
                                            + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>";

                            PropertyInfo[] propList = entry.Entity.GetType().GetProperties();
                            Dictionary <string, object> attrList = new Dictionary <string, object>();
                            foreach (PropertyInfo pInfo in propList)
                            {
                                object[] atts = pInfo.GetCustomAttributes(typeof(AuditableAttribute), false);
                                if (atts.Length > 0)
                                {
                                    attrList.Add(pInfo.Name, atts[0]);
                                }
                            }
                            int      i      = 0;
                            object[] listte = entry.GetUpdatableOriginalValues()[0].GetType().GetCustomAttributes(false);
                            foreach (string propertyName in
                                     entry.GetModifiedProperties())
                            {
                                if (attrList.Keys.Contains(propertyName))
                                {
                                    DbDataRecord original = entry.OriginalValues;

                                    string oldValue = original.GetValue(
                                        original.GetOrdinal(propertyName))
                                                      .ToString();

                                    System.Data.Entity.Core.Objects.CurrentValueRecord current = entry.CurrentValues;
                                    string newValue = current.GetValue(
                                        current.GetOrdinal(propertyName))
                                                      .ToString();

                                    xmlOld += "<" + propertyName + " type='" + original.GetFieldType(i) + "'>" + oldValue + "</" + propertyName + ">";
                                    xmlNew += "<" + propertyName + " type='" + original.GetFieldType(i) + "'>" + newValue + "</" + propertyName + ">";
                                }
                                i++;
                            }

                            xmlOld += "</" + (entry.EntitySet).Name + ">";
                            xmlNew += "</" + (entry.EntitySet).Name + ">";

                            audit.OldData = xmlOld;
                            audit.NewData = xmlNew;

                            audit.TablePrimaryId = GetKeyValue(entry);
                            audit.Actions        = AuditActions.U.ToString();
                            break;
                        }
                        }
                    }
                    AuditTrails.Add(audit);
                }
            }
            catch
            {
                // Keep quite...
            }
        }
 /// <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));
示例#20
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;
        }
        public override object GetValue(object item)
        {
            Check.NotNull <object>(item, nameof(item));
            if (!this._itemType.IsAssignableFrom(item.GetType()))
            {
                throw new ArgumentException(Strings.ObjectView_IncompatibleArgument);
            }
            DbDataRecord dbDataRecord = item as DbDataRecord;

            return(dbDataRecord == null?DelegateFactory.GetValue(this._property, item) : dbDataRecord.GetValue(dbDataRecord.GetOrdinal(this._property.Name)));
        }
示例#22
0
 public static bool GetBoolean(this DbDataRecord rec, string fieldName)
 {
     return(rec.GetBoolean(rec.GetOrdinal(fieldName)));
 }
 public static bool GetBoolean(this DbDataRecord rec, string fieldName)
 {
     return(rec.GetBoolean(rec.GetOrdinal(fieldName)));
     // Or this one....
     //return !(rec.GetValue(rec.GetOrdinal(fieldName)) == (object)0);
 }
示例#24
0
        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges(); // Important!

            ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;

            List <ObjectStateEntry> objectStateEntryList =
                ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added
                                                             | EntityState.Modified
                                                             | EntityState.Deleted)
                .ToList();

            foreach (ObjectStateEntry entry in objectStateEntryList)
            {
                if (!entry.IsRelationship)
                {
                    switch (entry.State)
                    {
                    case EntityState.Added:
                        // write log...
                        break;

                    case EntityState.Deleted:
                        // write log...
                        break;

                    case EntityState.Modified:
                    {
                        if (ObjectContext.GetObjectType(entry.Entity.GetType()) == typeof(DeviceParameter))
                        {
                            DbDataRecord original = entry.OriginalValues;
                            string       oldValue = original.GetValue(
                                original.GetOrdinal("Value"))
                                                    .ToString();

                            CurrentValueRecord current  = entry.CurrentValues;
                            string             newValue = current.GetValue(
                                current.GetOrdinal("Value"))
                                                          .ToString();

                            if (oldValue != newValue)     // probably not necessary
                            {
                                ParameterChangeHistory hist = new ParameterChangeHistory();
                                hist.Date     = DateTime.Now;
                                hist.Property = (DeviceParameter)(object)entry.Entity;
                                hist.Value    = newValue;
                                this.ParameterChanges.Add(hist);
                            }

                            if (this.ParamUpdateEvent != null)
                            {
                                Task.Factory.StartNew(() => this.ParamUpdateEvent((DeviceParameter)entry.Entity));
                            }
                        }
                        else if (ObjectContext.GetObjectType(entry.Entity.GetType()) == typeof(DeviceActionResult))
                        {
                            DbDataRecord original = entry.OriginalValues;
                            string       oldValue = original.GetValue(
                                original.GetOrdinal("Value"))
                                                    .ToString();

                            CurrentValueRecord current  = entry.CurrentValues;
                            string             newValue = current.GetValue(
                                current.GetOrdinal("Value"))
                                                          .ToString();

                            if (oldValue != newValue)     // probably not necessary
                            {
                                ActionChangeHistory hist = new ActionChangeHistory();
                                hist.Date     = DateTime.Now;
                                hist.Property = (DeviceActionResult)(object)entry.Entity;
                                hist.Value    = newValue;
                                this.ActionChangeHistory.Add(hist);
                            }

                            if (this.ActionUpdateEvent != null)
                            {
                                Task.Factory.StartNew(() => this.ActionUpdateEvent((DeviceActionResult)entry.Entity));
                            }
                        }
                        else if (ObjectContext.GetObjectType(entry.Entity.GetType()) == typeof(Device))
                        {
                            Task.Factory.StartNew(() => this.DeviceUpdateEvent((Device)entry.Entity));
                        }
                        break;
                    }
                    }
                }
            }
            return(base.SaveChanges());
        }