コード例 #1
0
        public JsonResult Save(ClientModel client)
        {
            Sys_User user = client.GetEntity <Sys_User>("user");

            switch (CheckExists(user))
            {
            case 1:
                return(Json(new { status = 1, msg = "用户账号已经存在" }));

            case 2:
                return(Json(new { status = 1, msg = "用户名称已经存在" }));

            default:
                if (!user.ID.HasValue)
                {
                    user.dCreatedDate = DateTime.Now;
                    user.cNonceStr    = Guid.NewGuid().ToString("N");
                    user.cPassword    = DataCipher.MD5Encrypt(user.UserId + user.cNonceStr + "123456");
                    user.TenantId     = Auth.TenantId;
                    user.iStatus      = 1;
                }
                user.InsertOrUpdate();
                return(Json(new { status = 0 }));
            }
        }
コード例 #2
0
        public User LogIn(string email, string imageUrl, string password)
        {
            var regexp = new Regex(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*" + "@" +
                                   @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");

            if (!regexp.IsMatch(email))
            {
                throw new Exception("Error: Email is not Valid");
            }
            var cypher = new DataCipher();

            using (var db = new DbRepository())
            {
                var pss  = !cypher.IsEncrypt(password) ? new DataCipher().Encrypt(password) : password;
                var user = db.Get <User>().Where(x => x.Email.Contains(email) && pss == x.Password).ExecuteFirstOrDefault();
                if (user == null && password == "google.com")
                {
                    user = new User
                    {
                        Email    = email,
                        Password = cypher.Encrypt(Guid.NewGuid().ToString("N")),
                        Picture  = imageUrl
                    };

                    db.Save(user).SaveChanges();
                    new DirectoryManager(Actions.ImageRootPath, Actions.GenerateUserFolderName(user.Email)).Create();
                }
                return(user);
            }
        }
コード例 #3
0
        public string Index()
        {
            string licence = DataCipher.RSAEncrypt(MachineData.MachineCode() + "|" + DateTime.Now.AddDays(20).ToString("yyyy-MM-dd"), "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmlx+ouP4MJehomQOn+8YqjBUnX3oUVXDR2R3I4HdC0QUG9Qq0565n1fPl3TZLdS3njamNtUMu9Ovjl2bI0/oRyv536J4px4QDKGrB78PRbLC/jIq+Nuk2V3ObEPXJA8EAnSrdGGqn3rb4fejZgCAKashTp96VD+SKbhaCk3kTbVL9TMIyCDTv9/QjK3xKSFxlq2x3bnt/hqTUMHveTcE93qFDpEV2jtNbUz1oT43//J/wvIFIHFU+Xd5CjEYqeo0gaX0uzt2oAODljHP7ce1R+d1Gt6ab2kYfKE2t5beXQhEETsWcAm3U1nmq4d/YNXoE2RwXNfQzFr01LsFmFks4QIDAQAB");

            var a = MachineData.AppPeriod(licence);

            return(a.ValidityDate.ToString());
        }
コード例 #4
0
        public void DecifradoDatos([FromForm] DataCipher _DataDeCipher, string decifrado)
        {
            MetodosNecesariosC _MetodosDecipher = new MetodosNecesariosC();
            ZigZag             _Zigzag          = new ZigZag();

            switch (decifrado.ToUpper())
            {
            case "CEASER":
                if (!Directory.Exists(_environment.WebRootPath + "\\ArchivoDecifradoCeaser\\"))
                {
                    Directory.CreateDirectory(_environment.WebRootPath + "\\ArchivoDecifradoCeaser\\");
                }
                _MetodosDecipher.DecifradoCeaser(_DataDeCipher.ArchivoCargado, _DataDeCipher.Llave, _DataDeCipher.NuevoNombre, _environment.WebRootPath + "\\ArchivoDecifradoCeaser\\");
                break;

            case "ZIGZAG":
                if (!Directory.Exists(_environment.WebRootPath + "\\ArchivoDecifradoZigZag\\"))
                {
                    Directory.CreateDirectory(_environment.WebRootPath + "\\ArchivoDecifradoZigZag\\");
                }
                _Zigzag.DescifradoZigZag(_DataDeCipher.ArchivoCargado, _DataDeCipher.TamanoCarriles, _DataDeCipher.NuevoNombre, _environment.WebRootPath + "\\ArchivoDecifradoZigZag\\");
                break;

            case "ESPIRAL":
                if (!Directory.Exists(_environment.WebRootPath + "\\ArchivoDecifradoEspiral\\"))
                {
                    Directory.CreateDirectory(_environment.WebRootPath + "\\ArchivoDecifradoEspiral\\");
                }
                _MetodosDecipher.DecifradoEspiral(_DataDeCipher.ArchivoCargado, _DataDeCipher.n, _DataDeCipher.m, _DataDeCipher.NuevoNombre, _environment.WebRootPath + "\\ArchivoDecifradoEspiral\\");
                break;

            case "VERTICAL":
                if (!Directory.Exists(_environment.WebRootPath + "\\ArchivoDecifradoVertical\\"))
                {
                    Directory.CreateDirectory(_environment.WebRootPath + "\\ArchivoDecifradoVertical\\");
                }
                _MetodosDecipher.DecifradoVertical(_DataDeCipher.ArchivoCargado, _DataDeCipher.n, _DataDeCipher.m, _DataDeCipher.NuevoNombre, _environment.WebRootPath + "\\ArchivoDecifradoVertical\\");
                break;

            default:
                break;
            }
        }
コード例 #5
0
        /// <summary>
        /// 通过配置文件中的ProviderName来自动生成Connection对象
        /// </summary>
        /// <param name="databaseName">在appsetting中配置的数据库连接对象名称</param>
        /// <returns></returns>
        public IDbConnection CreateConnection(string databaseName)
        {
            bool encrypt = TwinkleContext.Config.GetValue <bool>($"ConnectionStrings:{databaseName}:Encrypt");

            string connectString = TwinkleContext.Config.GetValue <string>($"ConnectionStrings:{databaseName}:ConnectString");

            //如果连接字符串被加密了 需要解密
            if (encrypt)
            {
                connectString = DataCipher.RSADecrypt(connectString);
            }

            string providerName = TwinkleContext.Config.GetValue <string>($"ConnectionStrings:{databaseName}:ProviderName");

            IDbConnection connection = null;

            switch (providerName)
            {
            case "System.Data.SqlClient":
                connection = SqlClientFactory.Instance.CreateConnection();
                break;

            case "Oracle.ManagedDataAccess.Client":
                connection = new OracleClientFactory().CreateConnection();
                break;

            case "MySql.Data.MySqlClient":
                connection = new MySqlClientFactory().CreateConnection();
                break;

            default:
                throw new DataException("There is no suitable Provider for creating IDbConnection");
            }

            connection.ConnectionString = connectString;

            this.Connection = connection;
            return(connection);
        }
コード例 #6
0
 internal void CleanDecoder(string replaceWith)
 {
     if (!EndWithDecoder())
     {
         sb.Append(replaceWith);
     }
     else
     {
         MatchCollection matches = null;
         var             result  = new string[0];
         while ((matches = DataEncodeExp.Matches(sb.ToString())).Count > 0)
         {
             var m = matches[0];
             result = m.Value.Replace("</DataEncode>", "").TrimEnd(']').Substring(@"<DataEncode>\[".Length - 1).Split('|'); // get the key
             sb     = sb.Remove(m.Index, m.Value.Length);
             if (replaceWith.Contains("String["))
             {
                 var spt     = replaceWith.Split(new string[] { "]," }, StringSplitOptions.None).Where(x => !string.IsNullOrEmpty(x));
                 var isFirst = true;
                 foreach (var str in spt)
                 {
                     var xValue     = str.Trim().Replace("String[", "").TrimEnd("]");
                     var rValue     = xValue.TrimStart('%').TrimEnd("%");
                     var codedValue = new DataCipher(result.First(), result.Last().ConvertValue <int>().ConvertValue <DataCipherKeySize>()).Encrypt(rValue);
                     if (xValue.StartsWith("%"))
                     {
                         codedValue = "%" + codedValue;
                     }
                     if (xValue.EndsWith("%"))
                     {
                         codedValue += "%";
                     }
                     sb.Insert(m.Index, (!isFirst ? "," : "") + "String[" + codedValue + "]");
                     isFirst = false;
                 }
             }
             else if (replaceWith.Contains("Date["))
             {
                 var spt     = replaceWith.Split(new string[] { "]," }, StringSplitOptions.None).Where(x => !string.IsNullOrEmpty(x));
                 var isFirst = true;
                 foreach (var str in spt)
                 {
                     var xValue     = str.Trim().Replace("Date[", "").TrimEnd("]");
                     var rValue     = xValue.TrimStart('%').TrimEnd("%");
                     var codedValue = new DataCipher(result.First(), result.Last().ConvertValue <int>().ConvertValue <DataCipherKeySize>()).Encrypt(rValue);
                     if (xValue.StartsWith("%"))
                     {
                         codedValue = "%" + codedValue;
                     }
                     if (xValue.EndsWith("%"))
                     {
                         codedValue += "%";
                     }
                     sb.Insert(m.Index, (!isFirst ? "," : "") + "Date[" + codedValue + "]");
                     isFirst = false;
                 }
             }
             else
             {
                 sb = sb.Insert(m.Index, new DataCipher(result.First(), result.Last().ConvertValue <int>().ConvertValue <DataCipherKeySize>()).Encrypt(replaceWith));
             }
         }
     }
 }
コード例 #7
0
        /// <summary>
        /// generic Json to object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        internal static T FromJson <T>(this string json, IRepository repository)
        {
            var o = JSON.ToObject <T>(json);


            void LoadJsonIgnoreProperties(object item)
            {
                if (item is IList)
                {
                    foreach (var t in (IList)item)
                    {
                        LoadJsonIgnoreProperties(t);
                    }
                    return;
                }

                var type = item?.GetType().GetActualType();

                if (type == null)
                {
                    return;
                }
                if (!(item?.GetPrimaryKeyValue().ObjectIsNew() ?? true))
                {
                    var primaryId = item.GetPrimaryKeyValue();
                    foreach (var prop in DeepCloner.GetFastDeepClonerProperties(item.GetType()).Where(x => (x.ContainAttribute <JsonIgnore>() || !x.IsInternalType) && !x.ContainAttribute <ExcludeFromAbstract>() && x.CanRead))
                    {
                        var value = prop.GetValue(item);
                        if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty(value?.ToString()))
                        {
                            value = string.Empty;
                        }
                        if (prop.IsInternalType && value == LightDataTableShared.ValueByType(prop.PropertyType)) // Value is default
                        {
                            var cmd  = repository.GetSqlCommand($"SELECT [{prop.GetPropertyName()}] FROM [{type.TableName()}] WHERE [{item.GetPrimaryKey().GetPropertyName()}] = {Querys.GetValueByType(item.GetPrimaryKeyValue(), repository.DataBaseTypes)}");
                            var data = repository.ExecuteScalar(cmd);
                            if (data == null)
                            {
                                continue;
                            }
                            if (prop.ContainAttribute <DataEncode>())
                            {
                                data = new DataCipher(prop.GetCustomAttribute <DataEncode>().Key, prop.GetCustomAttribute <DataEncode>().KeySize).Decrypt(data.ToString());
                            }
                            else if (prop.ContainAttribute <ToBase64String>() && data.ToString().IsBase64String())
                            {
                                data = MethodHelper.DecodeStringFromBase64(data.ToString());
                            }
                            else if (prop.ContainAttribute <JsonDocument>())
                            {
                                data = data?.ToString().FromJson(prop.PropertyType);
                            }
                            prop.SetValue(item, data.ConvertValue(prop.PropertyType));
                        }
                        else if (value != null)
                        {
                            LoadJsonIgnoreProperties(value);
                        }
                    }
                }
            }

            LoadJsonIgnoreProperties(o);
            return(o);
        }
コード例 #8
0
        internal static IList DataReaderConverter(Transaction.Transaction repository, IDataReader reader, DbCommandExtended command, Type type)
        {
            var tType        = type.GetActualType();
            var baseListType = typeof(List <>);
            var listType     = baseListType.MakeGenericType(tType);
            var iList        = DeepCloner.CreateInstance(listType) as IList;
            //#if (NETSTANDARD2_0 || NETSTANDARD1_3 || NETSTANDARD1_5)
            var props = DeepCloner.GetFastDeepClonerProperties(tType);

            //#endif
            try
            {
                while (reader.Read())
                {
                    object item   = null;
                    object clItem = null;
                    //#if (NETSTANDARD2_0 || NETSTANDARD1_3 || NETSTANDARD1_5)

                    item   = DeepCloner.CreateInstance(tType);
                    clItem = DeepCloner.CreateInstance(tType);
                    var col = 0;

                    while (col < reader.FieldCount)
                    {
                        var columnName = reader.GetName(col);
                        var value      = reader[columnName];

                        var prop = DeepCloner.GetProperty(tType, columnName);

                        if (prop == null)
                        {
                            prop = props.FirstOrDefault(x => string.Equals(x.GetPropertyName(), columnName, StringComparison.CurrentCultureIgnoreCase) || x.GetPropertyName().ToLower() == columnName);
                        }

                        if (value != DBNull.Value && value != null && prop != null && prop.CanRead)
                        {
                            if (value as byte[] != null && prop.PropertyType.FullName.Contains("Guid"))
                            {
                                value = new Guid(value as byte[]);
                            }

                            var dataEncode     = prop.GetCustomAttribute <DataEncode>();
                            var toBase64String = prop.GetCustomAttribute <ToBase64String>();

                            if (toBase64String != null)
                            {
                                if (value.ConvertValue <string>().IsBase64String())
                                {
                                    value = MethodHelper.DecodeStringFromBase64(value.ConvertValue <string>());
                                }
                                else
                                {
                                    value = MethodHelper.ConvertValue(value, prop.PropertyType);
                                }
                            }
                            else if (dataEncode != null)
                            {
                                value = new DataCipher(dataEncode.Key, dataEncode.KeySize).Decrypt(value.ConvertValue <string>());
                            }
                            else if (prop.ContainAttribute <JsonDocument>())
                            {
                                value = value?.ToString().FromJson(prop.PropertyType);
                            }
                            else
                            {
                                value = MethodHelper.ConvertValue(value, prop.PropertyType);
                            }

                            prop.SetValue(item, value);
                            prop.SetValue(clItem, value);
                        }
                        col++;
                    }
                    //#else
                    //                    var cmReader = new DataRecordExtended(reader);
                    //                    if (!CachedDataRecord.ContainsKey(tType))
                    //                        CachedDataRecord.GetOrAdd(tType, DynamicBuilder.CreateBuilder(cmReader, tType));
                    //                    var x = CachedDataRecord[tType];
                    //                    item = x.Build(cmReader);
                    //                    clItem = !(repository?.IsAttached(item) ?? true) ? x.Build(cmReader) : null;
                    //#endif

                    if (clItem != null && !(repository?.IsAttached(clItem) ?? true))
                    {
                        repository?.AttachNew(clItem);
                    }
                    iList.Add(item);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                reader.Close();
                reader.Dispose();
                if (repository.OpenedDataReaders.ContainsKey(reader))
                {
                    repository.OpenedDataReaders.Remove(reader);
                }
            }

            return(iList);
        }
コード例 #9
0
        private object Save(object o, bool isIndependentData, bool updateOnly = false, List <string> ignoredProperties = null, string lastProperty = null)
        {
            try
            {
                if (ignoredProperties == null)
                {
                    ignoredProperties = new List <string>();
                }
                if (lastProperty == null)
                {
                    lastProperty = string.Empty; // not valid name
                }
                GlobalConfiguration.Log?.Info("Save", o);
                _repository.CreateTransaction();
                var props      = DeepCloner.GetFastDeepClonerProperties(o.GetType());
                var primaryKey = o.GetPrimaryKey();

                if (primaryKey == null)
                {
                    throw new EntityException("Object must have a PrimaryKey");
                }

                var primaryKeyId        = !Extension.ObjectIsNew(o.GetPrimaryKeyValue()) ? o.GetPrimaryKeyValue() : null;
                var availableColumns    = _repository.GetColumnSchema(o.GetType());
                var objectRules         = o.GetType().GetCustomAttribute <Rule>();
                var tableName           = o.GetType().TableName().GetName(_repository.DataBaseTypes);
                var primaryKeySubstitut = !primaryKey.GetCustomAttribute <PrimaryKey>().AutoGenerate ? primaryKeyId : null;

                object dbTrigger = null;
                if (objectRules != null && !CachedIDbRuleTrigger.ContainsKey(o.GetType()))
                {
                    dbTrigger = objectRules.RuleType.CreateInstance();
                    CachedIDbRuleTrigger.Add(o.GetType(), dbTrigger);
                }
                else if (objectRules != null || CachedIDbRuleTrigger.ContainsKey(o.GetType()))
                {
                    dbTrigger = CachedIDbRuleTrigger[o.GetType()];
                }

                if (primaryKeyId != null && !updateOnly) // lets attach the object
                {
                    var data = GetById(primaryKeyId, o.GetType());
                    if (data == null)
                    {
                        primaryKeyId = null;
                        o.SetPrimaryKeyValue();
                    }
                    else
                    {
                        if (!_repository.IsAttached(o))
                        {
                            _repository.Attach(data);
                        }

                        var changes = _repository.GetObjectChanges(o);
                        foreach (var item in props.Where(x => x.CanRead && !changes.Any(a => a.PropertyName == x.Name) && (x.IsInternalType || x.ContainAttribute <JsonDocument>())))
                        {
                            item.SetValue(o, item.GetValue(data));
                        }
                    }
                }

                if (!updateOnly)
                {
                    dbTrigger?.GetType().GetMethod("BeforeSave").Invoke(dbTrigger, new List <object>()
                    {
                        _repository, o
                    }.ToArray());                                                                                                    // Check the Rule before save
                }
                object tempPrimaryKey = null;
                var    sql            = "UPDATE " + (o.GetType().TableName().GetName(_repository.DataBaseTypes)) + " SET ";
                var    cols           = props.FindAll(x => x.CanRead && (availableColumns.ContainsKey(x.GetPropertyName()) || availableColumns.ContainsKey(x.GetPropertyName().ToLower())) && (x.IsInternalType || x.ContainAttribute <JsonDocument>() || x.ContainAttribute <XmlDocument>()) && !x.ContainAttribute <ExcludeFromAbstract>() && x.GetCustomAttribute <PrimaryKey>() == null);

                // Clean out all unwanted properties
                if (ignoredProperties.Any())
                {
                    cols = cols.FindAll(x => !ignoredProperties.Any(a => a == x.Name || a == (o.GetType().Name + "." + x.Name) || a == (lastProperty + "." + x.Name)));
                }

                if (primaryKeyId == null)
                {
                    if (primaryKey.PropertyType.IsNumeric() && primaryKey.GetCustomAttribute <PrimaryKey>().AutoGenerate)
                    {
                        sql  = "INSERT INTO " + tableName + "(" + string.Join(",", cols.Select(x => "[" + x.GetPropertyName() + "]")) + ") Values(";
                        sql += string.Join(",", cols.Select(x => "@" + x.GetPropertyName())) + ");";
                        sql += _repository.DataBaseTypes == DataBaseTypes.Sqllight ? " select last_insert_rowid();" : (_repository.DataBaseTypes != DataBaseTypes.PostgreSql ? " SELECT IDENT_CURRENT('" + tableName + "');" : " SELECT currval('" + string.Format("{0}_{1}_seq", tableName, primaryKey.GetPropertyName()) + "');");
                    }
                    else
                    {
                        var colList = new List <IFastDeepClonerProperty>();
                        tempPrimaryKey = primaryKeySubstitut == null?Guid.NewGuid() : primaryKeySubstitut;

                        if (primaryKeySubstitut == null && primaryKey.PropertyType.IsNumeric())
                        {
                            tempPrimaryKey = _repository.ExecuteScalar(_repository.GetSqlCommand(String.Format("SELECT MAX([{0}]) FROM {1}", primaryKey.GetPropertyName(), tableName))).ConvertValue <long>() + 1;
                        }
                        else if (primaryKey.PropertyType == typeof(string))
                        {
                            tempPrimaryKey = tempPrimaryKey.ToString();
                        }
                        colList.Insert(0, primaryKey);
                        colList.AddRange(cols);
                        sql  = "INSERT INTO " + tableName + "(" + string.Join(",", colList.Select(x => "[" + x.GetPropertyName() + "]")) + ") Values(";
                        sql += string.Join(",", colList.Select(x => "@" + x.GetPropertyName())) + "); select '" + tempPrimaryKey + "'";
                    }
                }
                else
                {
                    sql += string.Join(",", cols.Select(x => "[" + x.GetPropertyName() + "]" + " = @" + x.GetPropertyName()));
                    sql += Querys.Where(_repository.DataBaseTypes).Column(o.GetType().GetActualType().GetPrimaryKey().GetPropertyName()).Equal(primaryKeyId).Execute();
                }

                var cmd = _repository.GetSqlCommand(sql);
                if ((!primaryKey.PropertyType.IsNumeric() || !primaryKey.GetCustomAttribute <PrimaryKey>().AutoGenerate) && primaryKeyId == null)
                {
                    _repository.AddInnerParameter(cmd, primaryKey.GetPropertyName(), tempPrimaryKey);
                }


                foreach (var col in cols)
                {
                    var v = col.GetValue(o);
                    var defaultOnEmpty = col.GetCustomAttribute <DefaultOnEmpty>();
                    if (col.ContainAttribute <ForeignKey>() && (v?.ObjectIsNew() ?? true))
                    {
                        var ob              = props.FirstOrDefault(x => (x.PropertyType == col.GetCustomAttribute <ForeignKey>().Type) && (string.IsNullOrEmpty(col.GetCustomAttribute <ForeignKey>().PropertyName) || col.GetCustomAttribute <ForeignKey>().PropertyName == x.Name));
                        var obValue         = ob?.GetValue(o);
                        var independentData = ob?.GetCustomAttribute <IndependentData>() != null;
                        if (obValue != null)
                        {
                            v = obValue.GetType().GetPrimaryKey().GetValue(obValue)?.ObjectIsNew() ?? true?
                                Save(obValue, independentData, false, ignoredProperties, ob.Name) :
                                    obValue.GetType().GetPrimaryKey().GetValue(obValue);

                            col.SetValue(o, v);
                        }
                    }

                    if (col.ContainAttribute <ToBase64String>())
                    {
                        if (!v?.ConvertValue <string>().IsBase64String() ?? false)
                        {
                            v = MethodHelper.EncodeStringToBase64(v.ConvertValue <string>());
                        }
                    }

                    if (col.ContainAttribute <JsonDocument>())
                    {
                        v = v?.ToJson();
                    }

                    if (col.ContainAttribute <XmlDocument>())
                    {
                        v = v?.ToXml();
                    }

                    if (col.ContainAttribute <Stringify>() || col.ContainAttribute <DataEncode>())
                    {
                        v = v?.ConvertValue <string>();
                    }

                    if (col.ContainAttribute <DataEncode>())
                    {
                        if (col.PropertyType != typeof(string))
                        {
                            throw new EntityException(string.Format("Property {0} Contain DataEncode. PropertyType must be of type String .", col.FullName));
                        }
                        v = new DataCipher(col.GetCustomAttribute <DataEncode>().Key, col.GetCustomAttribute <DataEncode>().KeySize).Encrypt(v.ToString());
                    }

                    if (col.ContainAttribute <NotNullable>() && v == null && defaultOnEmpty == null)
                    {
                        throw new EntityException(string.Format("Property {0} dose not allow null.", col.FullName));
                    }


                    if (v == null && defaultOnEmpty != null)
                    {
                        v = defaultOnEmpty.Value.ConvertValue(col.PropertyType);
                    }

                    _repository.AddInnerParameter(cmd, col.GetPropertyName(), v);
                }

                if (primaryKeyId == null)
                {
                    primaryKeyId = _repository.ExecuteScalar(cmd).ConvertValue(primaryKey.PropertyType);
                }
                else
                {
                    _repository.ExecuteNonQuery(cmd);
                }
                var oState = dbTrigger != null?DeepCloner.Clone(o) : null;

                if (updateOnly)
                {
                    return(primaryKeyId);
                }
                dbTrigger?.GetType().GetMethod("AfterSave").Invoke(dbTrigger, new List <object>()
                {
                    _repository, o, primaryKeyId
                }.ToArray());                                                                                                                 // Check the Rule before save

                foreach (var prop in props.Where(x => !x.IsInternalType && !x.ContainAttribute <JsonDocument>() && !x.ContainAttribute <XmlDocument>() && !x.ContainAttribute <ExcludeFromAbstract>()))
                {
                    var independentData = prop.GetCustomAttribute <IndependentData>() != null;
                    var type            = prop.PropertyType.GetActualType();
                    var oValue          = prop.GetValue(o);
                    if (oValue == null)
                    {
                        continue;
                    }
                    var vList = oValue is IList ? (IList)oValue : new List <object>()
                    {
                        oValue
                    };

                    foreach (var item in vList)
                    {
                        var foreignKey = DeepCloner.GetFastDeepClonerProperties(item.GetType()).FirstOrDefault(x => x.GetCustomAttribute <ForeignKey>()?.Type == o.GetType() && string.IsNullOrEmpty(x.GetCustomAttribute <ForeignKey>().PropertyName));
                        foreignKey?.SetValue(item, primaryKeyId);
                        var res = Save(item, independentData, false, ignoredProperties, prop.Name);
                        foreignKey = props.FirstOrDefault(x => x.GetCustomAttribute <ForeignKey>()?.Type == type && (x.GetCustomAttribute <ForeignKey>().PropertyName == prop.Name || string.IsNullOrEmpty(x.GetCustomAttribute <ForeignKey>().PropertyName)));
                        if (foreignKey == null || !foreignKey.GetValue(o).ObjectIsNew())
                        {
                            continue;
                        }
                        if (o.GetType() == foreignKey.GetCustomAttribute <ForeignKey>().Type)
                        {
                            continue;
                        }
                        foreignKey.SetValue(o, res);
                    }
                }


                if (oState != null && _repository.GetObjectChanges(o, oState).Count > 0) // a change has been made outside the function Save then resave
                {
                    o.SetPrimaryKeyValue(primaryKeyId);
                    Save(o, false, true, ignoredProperties);
                }
                o.SetPrimaryKeyValue(primaryKeyId);
                _repository.Attach(o, true);
                return(primaryKeyId);
            }
            catch (Exception e)
            {
                GlobalConfiguration.Log?.Error(e);
                _repository.Rollback();
                throw;
            }
        }
コード例 #10
0
        internal static IList DataReaderConverter(Transaction.Transaction repository, IDataReader reader, DbCommandExtended command, Type type)
        {
            var tType        = type.GetActualType();
            var attachable   = tType.GetPrimaryKey() != null;
            var baseListType = typeof(List <>);
            var listType     = baseListType.MakeGenericType(tType);
            var iList        = DeepCloner.CreateInstance(listType) as IList;
            var props        = DeepCloner.GetFastDeepClonerProperties(tType);

            try
            {
                var colNames = new Custom_ValueType <int, string>();
                var pp       = new Custom_ValueType <int, FastDeepCloner.IFastDeepClonerProperty>();
                while (reader.Read())
                {
                    object item   = null;
                    object clItem = null;

                    item   = DeepCloner.CreateInstance(tType);
                    clItem = attachable ? DeepCloner.CreateInstance(tType) : null;
                    var col = 0;

                    while (col < reader.FieldCount)
                    {
                        string columnName;
                        if (colNames.ContainsKey(col))
                        {
                            columnName = colNames[col];
                        }
                        else
                        {
                            columnName = reader.GetName(col);
                            colNames.TryAdd(col, columnName);
                        }

                        var value = reader[columnName];

                        IFastDeepClonerProperty prop;
                        if (!pp.ContainsKey(col))
                        {
                            prop = DeepCloner.GetProperty(tType, columnName);
                            if (prop == null)
                            {
                                prop = props.FirstOrDefault(x => string.Equals(x.GetPropertyName(), columnName, StringComparison.CurrentCultureIgnoreCase) || x.GetPropertyName().ToLower() == columnName);
                            }
                            pp.TryAdd(col, prop);
                        }
                        else
                        {
                            prop = pp[col];
                        }
                        if (prop != null && value != DBNull.Value && value != null && prop.CanRead)
                        {
                            if (value as byte[] != null && prop.PropertyType.FullName.Contains("Guid"))
                            {
                                value = new Guid(value as byte[]);
                            }

                            var dataEncode = prop.GetCustomAttribute <DataEncode>();
                            if (prop.ContainAttribute <ToBase64String>())
                            {
                                if (value.ConvertValue <string>().IsBase64String())
                                {
                                    value = MethodHelper.DecodeStringFromBase64(value.ConvertValue <string>());
                                }
                                else
                                {
                                    value = MethodHelper.ConvertValue(value, prop.PropertyType);
                                }
                            }
                            else if (dataEncode != null)
                            {
                                value = new DataCipher(dataEncode.Key, dataEncode.KeySize).Decrypt(value.ConvertValue <string>());
                            }
                            else if (prop.ContainAttribute <JsonDocument>())
                            {
                                value = value?.ToString().FromJson(prop.PropertyType);
                            }
                            else if (prop.ContainAttribute <XmlDocument>())
                            {
                                value = value?.ToString().FromXml();
                            }
                            else
                            {
                                value = MethodHelper.ConvertValue(value, prop.PropertyType);
                            }

                            prop.SetValue(item, value);
                            if (attachable)
                            {
                                prop.SetValue(clItem, value);
                            }
                        }
                        col++;
                    }

                    if (clItem != null && !(repository?.IsAttached(clItem) ?? true))
                    {
                        repository?.AttachNew(clItem);
                    }
                    iList.Add(item);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                reader.Close();
                reader.Dispose();
                if (repository.OpenedDataReaders.ContainsKey(reader))
                {
                    repository.OpenedDataReaders.Remove(reader);
                }
            }

            return(iList);
        }
コード例 #11
0
        /// <summary>
        /// DeSerilize Xml to object, this is supposed to handle all unknow object types but there has not been to many tests.
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public static object FromXml(this string xml, IRepository transaction = null)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return(null);
            }
            var doc = new System.Xml.XmlDocument();

            doc.LoadXml(xml);
            var o = FromXml(doc.DocumentElement);

            void LoadXmlIgnoreProperties(object item)
            {
                if (item is IList)
                {
                    foreach (var t in (IList)item)
                    {
                        LoadXmlIgnoreProperties(t);
                    }
                    return;
                }

                var type = item?.GetType().GetActualType();

                if (type == null)
                {
                    return;
                }
                if (!(item?.GetPrimaryKeyValue().ObjectIsNew() ?? true))
                {
                    var primaryId = item.GetPrimaryKeyValue();
                    foreach (var prop in DeepCloner.GetFastDeepClonerProperties(item.GetType()).Where(x => (x.ContainAttribute <XmlIgnore>() || !x.IsInternalType) && !x.ContainAttribute <ExcludeFromAbstract>() && x.CanRead))
                    {
                        var value = prop.GetValue(item);
                        if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty(value?.ToString()))
                        {
                            value = string.Empty;
                        }
                        if (prop.IsInternalType && value == LightDataTableShared.ValueByType(prop.PropertyType)) // Value is default
                        {
                            var cmd  = transaction.GetSqlCommand($"SELECT [{prop.GetPropertyName()}] FROM {type.TableName().GetName(transaction.DataBaseTypes)} WHERE [{item.GetPrimaryKey().GetPropertyName()}] = {Querys.GetValueByType(item.GetPrimaryKeyValue(), transaction.DataBaseTypes)}");
                            var data = transaction.ExecuteScalar(cmd);
                            if (data == null)
                            {
                                continue;
                            }
                            if (prop.ContainAttribute <DataEncode>())
                            {
                                data = new DataCipher(prop.GetCustomAttribute <DataEncode>().Key, prop.GetCustomAttribute <DataEncode>().KeySize).Decrypt(data.ToString());
                            }
                            else if (prop.ContainAttribute <ToBase64String>() && data.ToString().IsBase64String())
                            {
                                data = MethodHelper.DecodeStringFromBase64(data.ToString());
                            }

                            prop.SetValue(item, data.ConvertValue(prop.PropertyType));
                        }
                        else if (value != null)
                        {
                            LoadXmlIgnoreProperties(value);
                        }
                    }
                }
            }

            if (transaction != null)
            {
                LoadXmlIgnoreProperties(o);
            }
            return(o);
        }
コード例 #12
0
        public JsonResult Login(ClientModel client)
        {
            string UserId   = client.GetString("UserId");
            string Password = client.GetString("Password");

            string tenantId = this.Auth.TenantId;// 后期 tenantId 一般会是从登陆界面带过来

            Sys_User user = Db.ExecuteEntity <Sys_User>("SELECT * FROM Sys_User WHERE UserId=@UserId and TenantId=@TenantId", new { UserId, TenantId = tenantId });

            if (user == null)
            {
                return(Json(new
                {
                    status = 1,
                    msg = "账号不存在."
                }));
            }

            user.cLoginIP = this.Request.HttpContext.Connection.RemoteIpAddress.ToString().Replace("::1", "127.0.0.1");


            if (user.cPassword != DataCipher.MD5Encrypt(user.UserId + user.cNonceStr + Password))
            {
                if (user.dUnlockDate > DateTime.Now)
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = "账户已经被锁定,请稍后再试或联系管理员."
                    }));
                }

                if ((DateTime.Now - (user.dLoginDate ?? DateTime.MinValue)).TotalMinutes > 30)
                {
                    user.nFailedCount = 0;
                }

                user.nFailedCount = (user.nFailedCount ?? 0) + 1;

                if (user.nFailedCount == 5)
                {
                    user.dUnlockDate = DateTime.Now.AddMinutes(20);
                }
                else
                {
                    user.dUnlockDate = null;
                }

                Db.ExecuteNonQuery("UPDATE Sys_User SET cLoginIP = @cLoginIP,dLoginDate = GETDATE(),nFailedCount =@nFailedCount,dUnlockDate=@dUnlockDate WHERE UserId=@UserId AND TenantId=@TenantId", user);

                if (user.nFailedCount == 5)
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = "由于多次密码错误,账号已经被锁定,请20分钟后重试."
                    }));
                }
                else
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = $"账号或密码错误,无法登陆,还可尝试 {5 - user.nFailedCount} 次."
                    }));
                }
            }
            else
            {
                if (user.dUnlockDate > DateTime.Now)
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = "账户已经被锁定,请稍后再试或联系管理员."
                    }));
                }

                if (user.iStatus == 0)
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = "账户已经被停用,请联系管理员."
                    }));
                }

                user.nFailedCount = 0;
                user.dUnlockDate  = null;

                Db.ExecuteNonQuery("UPDATE Sys_User SET cLoginIP = @cLoginIP,dLoginDate = GETDATE(),nFailedCount =@nFailedCount WHERE UserId=@UserId AND TenantId=@TenantId", user);

                TwinkleContext.Login(new AuthUser {
                    UserId = UserId, TenantId = tenantId
                });
                return(Json(new
                {
                    status = 0,
                    userId = UserId,
                    tenantId,
                }));
            }
        }
コード例 #13
0
        private object Save(object o, bool isIndependentData, bool updateOnly = false)
        {
            try
            {
                _repository.CreateTransaction();
                var props      = DeepCloner.GetFastDeepClonerProperties(o.GetType());
                var primaryKey = o.GetPrimaryKey();

                if (primaryKey == null)
                {
                    throw new NullReferenceException("Object must have a PrimaryKey");
                }

                var primaryKeyId     = !Extension.ObjectIsNew(o.GetPrimaryKeyValue()) ? o.GetPrimaryKeyValue() : null;
                var availableColumns = ObjectColumns(o.GetType());
                var objectRules      = o.GetType().GetCustomAttribute <Rule>();
                var tableName        = o.GetType().GetCustomAttribute <Table>()?.Name ?? o.GetType().Name;


                object dbTrigger = null;
                if (objectRules != null && !CachedIDbRuleTrigger.ContainsKey(o.GetType()))
                {
                    dbTrigger = objectRules.RuleType.CreateInstance(true);
                    CachedIDbRuleTrigger.Add(o.GetType(), dbTrigger);
                }
                else if (objectRules != null)
                {
                    dbTrigger = CachedIDbRuleTrigger[o.GetType()];
                }

                if (primaryKeyId != null && !updateOnly) // lets attach the object
                {
                    var data = GetById(primaryKeyId, o.GetType());
                    if (data == null)
                    {
                        primaryKeyId = null;
                        o.SetPrimaryKeyValue();
                    }
                    else
                    {
                        if (!_repository.IsAttached(o))
                        {
                            _repository.Attach(data);
                        }

                        var changes = _repository.GetObjectChanges(o);
                        foreach (var item in props.Where(x => x.CanRead && !changes.Any(a => a.PropertyName == x.Name) && x.IsInternalType))
                        {
                            item.SetValue(o, item.GetValue(data));
                        }
                    }
                }

                if (!updateOnly)
                {
                    dbTrigger?.GetType().GetMethod("BeforeSave").Invoke(dbTrigger, new List <object>()
                    {
                        _repository, o
                    }.ToArray());                                                                                                    // Check the Rule before save
                }
                object tempPrimaryKey = null;
                var    sql            = "UPDATE [" + (o.GetType().GetCustomAttribute <Table>()?.Name ?? o.GetType().Name) + "] SET ";
                var    cols           = props.FindAll(x => availableColumns.FindByPrimaryKey <bool>(x.GetPropertyName()) && x.IsInternalType && !x.ContainAttribute <ExcludeFromAbstract>() && x.GetCustomAttribute <PrimaryKey>() == null);
                if (primaryKeyId == null)
                {
                    if (primaryKey.PropertyType.IsNumeric())
                    {
                        sql  = "INSERT INTO [" + tableName + "](" + string.Join(",", cols.Select(x => "[" + x.GetPropertyName() + "]")) + ") Values(";
                        sql += string.Join(",", cols.Select(x => "@" + x.GetPropertyName())) + ");";
                        sql += _repository.DataBaseTypes == DataBaseTypes.Sqllight ? " select last_insert_rowid();" : " SELECT IDENT_CURRENT('" + tableName + "');";
                    }
                    else
                    {
                        var colList = new List <IFastDeepClonerProperty>();
                        tempPrimaryKey = Guid.NewGuid();
                        colList.Insert(0, primaryKey);
                        colList.AddRange(cols);
                        sql  = "INSERT INTO [" + tableName + "](" + string.Join(",", colList.Select(x => "[" + x.GetPropertyName() + "]")) + ") Values(";
                        sql += string.Join(",", colList.Select(x => "@" + x.GetPropertyName())) + "); select '" + tempPrimaryKey + "'";
                    }
                }
                else
                {
                    sql += string.Join(",", cols.Select(x => "[" + x.GetPropertyName() + "]" + " = @" + x.GetPropertyName()));
                    sql += Querys.Where(_repository.DataBaseTypes).Column(o.GetType().GetActualType().GetPrimaryKey().GetPropertyName()).Equal(string.Format("Guid[{0}]", primaryKeyId), true).Execute();
                }

                var cmd = _repository.GetSqlCommand(sql);
                if (!primaryKey.PropertyType.IsNumeric() && primaryKeyId == null)
                {
                    _repository.AddInnerParameter(cmd, primaryKey.GetPropertyName(), tempPrimaryKey, _repository.GetSqlType(primaryKey.PropertyType));
                }


                foreach (var col in cols)
                {
                    var v = col.GetValue(o);
                    var defaultOnEmpty = col.GetCustomAttribute <DefaultOnEmpty>();
                    if (col.ContainAttribute <ForeignKey>() && (v?.ObjectIsNew() ?? true))
                    {
                        var ob              = props.FirstOrDefault(x => x.PropertyType == col.GetCustomAttribute <ForeignKey>().Type&& (string.IsNullOrEmpty(col.GetCustomAttribute <ForeignKey>().PropertyName) || col.GetCustomAttribute <ForeignKey>().PropertyName == x.Name));
                        var obValue         = ob?.GetValue(o);
                        var independentData = ob?.GetCustomAttribute <IndependentData>() != null;
                        if (obValue != null)
                        {
                            v = obValue.GetType().GetPrimaryKey().GetValue(obValue)?.ObjectIsNew() ?? true?
                                Save(obValue, independentData) :
                                    obValue.GetType().GetPrimaryKey().GetValue(obValue);

                            col.SetValue(o, v);
                        }
                    }

                    if (col.ContainAttribute <ToBase64String>())
                    {
                        if (!v?.ConvertValue <string>().IsBase64String() ?? false)
                        {
                            v = MethodHelper.EncodeStringToBase64(v.ConvertValue <string>());
                        }
                    }

                    if (col.ContainAttribute <StringFy>() || col.ContainAttribute <DataEncode>())
                    {
                        v = v?.ConvertValue <string>();
                    }

                    if (col.ContainAttribute <DataEncode>())
                    {
                        if (col.PropertyType != typeof(string))
                        {
                            throw new NoNullAllowedException(string.Format("Property {0} Contain DataEncode. PropertyType must be of type String .", col.FullName));
                        }
                        v = new DataCipher(col.GetCustomAttribute <DataEncode>().Key, col.GetCustomAttribute <DataEncode>().KeySize).Encrypt(v.ToString());
                    }

                    if (col.ContainAttribute <NotNullable>() && v == null && defaultOnEmpty == null)
                    {
                        throw new NoNullAllowedException(string.Format("Property {0} dose not allow null.", col.FullName));
                    }


                    if (v == null && defaultOnEmpty != null)
                    {
                        v = defaultOnEmpty.Value.ConvertValue(col.PropertyType);
                    }

                    _repository.AddInnerParameter(cmd, col.GetPropertyName(), v, (col.ContainAttribute <StringFy>() || col.ContainAttribute <DataEncode>() || col.ContainAttribute <ToBase64String>() ? _repository.GetSqlType(typeof(string)) : _repository.GetSqlType(col.PropertyType)));
                }

                if (primaryKeyId == null)
                {
                    primaryKeyId = _repository.ExecuteScalar(cmd).ConvertValue(primaryKey.PropertyType);
                }
                else
                {
                    _repository.ExecuteNonQuery(cmd);
                }
                var oState = dbTrigger != null?DeepCloner.Clone(o) : null;

                if (updateOnly)
                {
                    return(primaryKeyId);
                }
                dbTrigger?.GetType().GetMethod("AfterSave").Invoke(dbTrigger, new List <object>()
                {
                    _repository, o, primaryKeyId
                }.ToArray());                                                                                                                 // Check the Rule before save

                foreach (var prop in props.Where(x => !x.IsInternalType && !x.ContainAttribute <ExcludeFromAbstract>()))
                {
                    var independentData = prop.GetCustomAttribute <IndependentData>() != null;
                    var type            = prop.PropertyType.GetActualType();
                    var oValue          = prop.GetValue(o);
                    if (oValue == null)
                    {
                        continue;
                    }
                    var vList = oValue is IList ? (IList)oValue : new List <object>()
                    {
                        oValue
                    };

                    foreach (var item in vList)
                    {
                        var foreignKey = DeepCloner.GetFastDeepClonerProperties(item.GetType()).FirstOrDefault(x => x.GetCustomAttribute <ForeignKey>()?.Type == o.GetType() && string.IsNullOrEmpty(x.GetCustomAttribute <ForeignKey>().PropertyName));
                        foreignKey?.SetValue(item, primaryKeyId);
                        var res = Save(item, independentData);
                        foreignKey = props.FirstOrDefault(x => x.GetCustomAttribute <ForeignKey>()?.Type == type && (x.GetCustomAttribute <ForeignKey>().PropertyName == prop.Name || string.IsNullOrEmpty(x.GetCustomAttribute <ForeignKey>().PropertyName)));
                        if (foreignKey == null || !foreignKey.GetValue(o).ObjectIsNew())
                        {
                            continue;
                        }
                        if (o.GetType() == foreignKey.GetCustomAttribute <ForeignKey>().Type)
                        {
                            continue;
                        }
                        foreignKey.SetValue(o, res);
                    }
                }

                if (oState != null && _repository.GetObjectChanges(o, oState).Count > 0) // a change has been made outside the function Save then resave
                {
                    Save(o, false);
                }

                o.GetType().GetPrimaryKey().SetValue(o, primaryKeyId.ConvertValue(primaryKey.PropertyType));
                _repository.Attach(o, true);
                return(primaryKeyId);
            }
            catch
            {
                _repository.Rollback();
                throw;
            }
        }