/// <summary>
        ///
        /// </summary>
        /// <param name="target"></param>
        /// <param name="accessorType"></param>
        /// <returns></returns>
        public static IClassAccessor GetClassAccessor(object target, AccessorType accessorType)
        {
            ArgumentAssertion.IsNotNull(target, "target");
            var type = target.GetType();

            return(GetClassAccessor(type, accessorType));
        }
Exemple #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        public CommandArguments(string[] args)
        {
            ArgumentAssertion.IsNotNull(args, "args");

            this.argumentMap = new Dictionary <string, string>(args.Length);
            foreach (var arg in args)
            {
                var argInfo = arg.Split(':');
                var argName = argInfo[0].ToLower();
                if (argName.StartsWith("-"))
                {
                    argName = argName.Substring(1);
                }
                string argValue = string.Empty;
                if (argInfo.Length > 1)
                {
                    argValue = argInfo[1];
                }
                this.argumentMap.Add(argName, argValue);
            }

            if (this.ContainsArgument("appId"))
            {
                this.SessionId = this.GetCommandArgument("appId");

                if (this.ContainsArgument("hostPID"))
                {
                    var hostPIDStr = this.GetCommandArgument("hostPID");
                    this.HostProcessId = int.Parse(hostPIDStr);
                }
            }
        }
Exemple #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sqlName"></param>
        /// <returns></returns>
        public static SqlWrap GetSqlWrap(string sqlName)
        {
            Initialize();

            ArgumentAssertion.IsNotNull(sqlName, "sqlName");

            SqlWrap sqlWrap = null;

            if (sqlName.Contains(SqlMapping.SqKeySeparator))
            {
                var keyParts = sqlName.ToLower().Split(SqlMapping.SqKeySeparator[0]);
                var sqlMap   = FindSqlModule(keyParts[0]);
                if (null != sqlMap)
                {
                    sqlWrap = FindSqlWrap(string.Join(SqlMapping.ModuleKeySeparator, keyParts, 1, keyParts.Length - 1), sqlMap);
                }
            }
            else if (sqlName.Contains(SqlMapping.ModuleKeySeparator)) //兼容老版本直接调用SqlHelper的逻辑
            {
                var keyParts = sqlName.ToLower().Split(SqlMapping.ModuleKeySeparator[0]);
                var sqlMap   = FindSqlModule(string.Join(SqlMapping.ModuleKeySeparator, keyParts, 0, keyParts.Length - 1));
                if (null != sqlMap)
                {
                    sqlWrap = FindSqlWrap(keyParts[keyParts.Length - 1], sqlMap);
                }
            }


            if (null == sqlWrap)
            {
                throw new ArgumentOutOfRangeException("sqlName", sqlName, string.Format("没有定义SqlWrap - {0}", sqlName));
            }

            return(sqlWrap);
        }
Exemple #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="argName"></param>
        /// <returns></returns>
        public bool ContainsArgument(string argName)
        {
            ArgumentAssertion.IsNotNull(argName, "argName");

            argName = argName.ToLower();
            return(this.argumentMap.ContainsKey(argName));
        }
Exemple #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cookie"></param>
        public HttpCookieInfo(HttpCookie cookie)
        {
            ArgumentAssertion.IsNotNull(cookie, "cookie");

            this.Name     = cookie.Name;
            this.Domain   = cookie.Domain;
            this.Expires  = cookie.Expires;
            this.Path     = cookie.Path;
            this.HttpOnly = cookie.HttpOnly;
            this.Secure   = cookie.Secure;
            if (cookie.HasKeys)
            {
                this.Values = new Dictionary <string, string>(cookie.Values.Count);
                foreach (var itemKey in cookie.Values.AllKeys)
                {
                    if (cookie.Values[itemKey] != null)
                    {
                        this.Values.Add(itemKey, cookie.Values[itemKey]);
                    }
                }
            }
            else
            {
                this.Value = cookie.Value;
            }
        }
        /// <summary>
        /// Creates a new property accessor.
        /// </summary>
        /// <param name="targetType">Target object type.</param>
        /// <param name="property">Property name.</param>
        public ReflectionPropertyAccessor(Type targetType, string property)
        {
            ArgumentAssertion.IsNotNull(targetType, "targetType");

            this.mTargetType = targetType;

            this.propertyInfo = targetType.GetProperty(property, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
            this.fieldInfo    = targetType.GetField(property, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
            //
            // Make sure the property exists
            //
            if (this.propertyInfo == null && this.fieldInfo == null)
            {
                throw new PropertyAccessorException(
                          string.Format("Property \"{0}\" does not exist for type "
                                        + "{1}.", property, targetType));
            }
            else if (this.propertyInfo != null)
            {
                this.mCanRead      = this.propertyInfo.CanRead;
                this.mCanWrite     = this.propertyInfo.CanWrite;
                this.mProperty     = this.propertyInfo.Name;
                this.mPropertyType = this.propertyInfo.PropertyType;
                this.nonSerialized = this.propertyInfo.GetCustomAttributes(typeof(NonSerializedPropertyAttribute), true).Length > 0;
            }
            else
            {
                this.mCanRead      = true;
                this.mCanWrite     = true;
                this.mProperty     = this.fieldInfo.Name;
                this.mPropertyType = this.fieldInfo.FieldType;
                this.nonSerialized = this.fieldInfo.GetCustomAttributes(typeof(NonSerializedAttribute), true).Length > 0;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            ArgumentAssertion.IsNotNull(obj, "obj");
            var json = JsonConvert.SerializeObject(obj, BuildSerializerSettings());

            return(json);
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parameterValues"></param>
        /// <returns></returns>
        public override T ExecuteIdentity <T>(SqlWrap sql, IDictionary <string, object> parameterValues)
        {
            ArgumentAssertion.IsNotNull(sql, "sql");
            var identityValue = this.ExecuteScalar(sql, parameterValues);

            return(identityValue.Convert <T>(default(T)));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToJson(this object value)
        {
            ArgumentAssertion.IsNotNull(value, "value");
            var json = JsonConvert.SerializeObject(value, BuildSerializerSettings());

            return(json);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameterValues"></param>
        /// <param name="pagination"></param>
        /// <returns></returns>
        public override DataTable ExecutePaginationTable(SqlWrap sql, IDictionary <string, object> parameterValues, Pagination pagination)
        {
            ArgumentAssertion.IsNotNull(sql, "sql");
            ArgumentAssertion.IsNotNull(pagination, "pagination");

            Stopwatch stopwatch    = null;
            var       sqlProcessor = ObjectIOCFactory.GetSingleton <DataSettings>().SqlProcessor;

            if (sqlProcessor.EnableTrace)
            {
                stopwatch = Stopwatch.StartNew();
            }

            var sqlText = GetPaginationSql(sql, pagination);

            sqlText = this.TransformSql(sqlText, parameterValues);

            var dataSet    = MySqlHelper.ExecuteDataSet(this.ConnectionString, sqlText, sql.CommandTimeout, ConvertToDbParams(parameterValues));
            var totalCount = dataSet.Tables[0].Rows[0][0].Convert <int>();

            pagination.TotalCount = totalCount;

            if (sqlProcessor.EnableTrace)
            {
                stopwatch.Stop();
                sqlProcessor.Log(LogLevel.Trace, string.Format("[{0}]ExecuteSql({1})\r\n\t{2}", stopwatch.Elapsed, sql.FullName, sqlText), null);
            }

            return(dataSet.Tables[1]);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameterValues"></param>
        /// <returns></returns>
        public override object ExecuteScalar(SqlWrap sql, IDictionary <string, object> parameterValues)
        {
            ArgumentAssertion.IsNotNull(sql, "sql");

            Stopwatch stopwatch    = null;
            var       sqlProcessor = ObjectIOCFactory.GetSingleton <DataSettings>().SqlProcessor;

            if (sqlProcessor.EnableTrace)
            {
                stopwatch = Stopwatch.StartNew();
            }

            var sqlText = this.TransformSql(sql.SqlText, parameterValues);

            var result = MySqlHelper.ExecuteScalar(this.ConnectionString, sqlText, sql.CommandTimeout, ConvertToDbParams(parameterValues));

            if (result == DBNull.Value)
            {
                result = null;
            }

            if (sqlProcessor.EnableTrace)
            {
                stopwatch.Stop();
                sqlProcessor.Log(LogLevel.Trace, string.Format("[{0}]ExecuteSql({1})\r\n\t{2}", stopwatch.Elapsed, sql.FullName, sqlText), null);
            }
            return(result);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="handlingInstanceId"></param>
        /// <param name="bizInfo"></param>
        /// <returns></returns>
        public Exception HandleException(Exception exception, Guid handlingInstanceId, IDictionary bizInfo)
        {
            ArgumentAssertion.IsNotNull(exception, "exception");

            var msg = this.WrapMessage;

            if (string.IsNullOrEmpty(msg))
            {
                msg = exception.Message;
            }
            else if (msg.Contains(MesssageKey))
            {
                msg = msg.Replace(MesssageKey, exception.Message);
            }

            if (string.IsNullOrEmpty(this.WrapType))
            {
                throw new ConfigException("node define the WrapType");
            }

            var targetExceptionType = TypeExtension.GetMapType(this.WrapType);

            if (null == targetExceptionType)
            {
                throw new ConfigException(string.Format("cannot find the ExceptionType :{0}", this.WrapType));
            }

            object[] extraParameters = new object[2] {
                msg, exception
            };
            return((Exception)Activator.CreateInstance(targetExceptionType, extraParameters));
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public static T ConvertEntity <T>(this string jsonData)
        {
            ArgumentAssertion.IsNotNull(jsonData, "jsonData");
            var entity = JsonConvert.DeserializeObject <T>(jsonData, BuildSerializerSettings());

            return(entity);
        }
Exemple #14
0
        internal static bool Transform(UserPassport passport, OrganizationProfile newProfile)
        {
            ArgumentAssertion.IsNotNull(passport, "passport");

            OrganizationProfile profile = null;

            if (passport.Profile is OrganizationProfile)
            {
                profile = (OrganizationProfile)passport.Profile;
            }
            else
            {
                profile = new OrganizationProfile();
                profile.FillProfile(passport.Profile);
                profile.PersistentState = PersistentState.Transient;
            }
            if (null != newProfile)
            {
                profile.CurrentProfileType    = ProfileType.OrganizationProfile;
                profile.CurrentOrganizationId = newProfile.CurrentOrganizationId;
            }

            var saved = profile.Save();

            if (saved)
            {
                passport.Profile          = profile;
                passport.ProfileType      = ProfileType.OrganizationProfile;
                passport.MultipleProfiles = passport.MultipleProfiles | ProfileType.OrganizationProfile;
                passport.Save();
            }

            return(saved);
        }
Exemple #15
0
        public static string Decrypt(string decryption, string privateKey)
        {
            ArgumentAssertion.IsNotNull(decryption, "original");
            ArgumentAssertion.IsNotNull(privateKey, "privateKey");

            var key = GenerateKey(privateKey);

            try
            {
                using (RijndaelManaged rijndaelProvider = new RijndaelManaged())
                {
                    rijndaelProvider.Key = Encoding.UTF8.GetBytes(key);
                    rijndaelProvider.IV  = IV;
                    ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();

                    byte[] inputData     = Convert.FromBase64String(decryption);
                    byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);

                    var original = Encoding.UTF8.GetString(decryptedData);

                    if (original.Length > KeyLength)
                    {
                        original = RemoveSalt(original, key);
                    }

                    return(original);
                }
            }
            catch
            {
                return(null);
            }
        }
        public static bool IsCrawlerRequest(HttpRequest request)
        {
            ArgumentAssertion.IsNotNull(request, "request");

            var isCrawler = false;

            try
            {
                var browserInfo = request.Browser;
                if (browserInfo != null && browserInfo.Type != null && browserInfo.Crawler == false)
                {
                    var httpUserAgent = string.Empty;
                    if (request.QueryString.AllKeys.Contains("HTTP_USER_AGENT"))
                    {
                        httpUserAgent = request.QueryString["HTTP_USER_AGENT"];
                    }
                    else if (request.ServerVariables.AllKeys.Contains("HTTP_USER_AGENT") && null != request.ServerVariables["HTTP_USER_AGENT"])
                    {
                        httpUserAgent = request.ServerVariables["HTTP_USER_AGENT"];
                    }

                    if (httpUserAgent.Length < 15)     //  "Mozilla/4.0 (co"
                    {
                        isCrawler = true;
                    }
                }
            }
            catch
            {
                isCrawler = false;
            }
            return(isCrawler);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="targetType"></param>
        /// <param name="accessorType"></param>
        /// <returns></returns>
        public static IClassAccessor GetClassAccessor(Type targetType, AccessorType accessorType)
        {
            ArgumentAssertion.IsNotNull(targetType, "targetType");

            IClassAccessor accessor = null;
            var            typeKey  = string.Format("{0}.{1}", accessorType, targetType.FullName);

            if (ClassAccessores.ContainsKey(typeKey))
            {
                accessor = ClassAccessores[typeKey];
            }
            else
            {
                lock (SyncObject)
                {
                    if (ClassAccessores.ContainsKey(typeKey))
                    {
                        accessor = ClassAccessores[typeKey];
                    }
                    else
                    {
                        accessor = ClassAccessorFactory.CreateClassAccessor(targetType, accessorType);
                        ClassAccessores.Add(typeKey, accessor);
                    }
                }
            }
            return(accessor);
        }
        public static bool ExceededMaximumRequestLength(HttpRequest request)
        {
            ArgumentAssertion.IsNotNull(request, "request");

            var exceeded = false;

            try
            {
                var httpContentLength = 0;
                if (request.ServerVariables.AllKeys.Contains("HTTP_CONTENT_LENGTH") && null != request.ServerVariables["HTTP_CONTENT_LENGTH"])
                {
                    httpContentLength = Convert.ToInt32(request.ServerVariables["HTTP_CONTENT_LENGTH"]);
                }

                var maxLengthLimit = GetMaxRequestLength();
                if (httpContentLength > 0 && maxLengthLimit > 0 && httpContentLength >= maxLengthLimit)
                {
                    exceeded = true;
                }
            }
            catch
            {
                exceeded = false;
            }

            return(exceeded);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="handlingInstanceId"></param>
        /// <param name="bizInfo"></param>
        /// <returns></returns>
        public Exception HandleException(Exception exception, Guid handlingInstanceId, IDictionary bizInfo)
        {
            ArgumentAssertion.IsNotNull(exception, "exception");

            var context = HttpContext.Current;

            if (context == null)
            {
                return(exception);
            }

            if (string.IsNullOrEmpty(this.Url))
            {
                throw new ConfigException("node define the Redirect Url");
            }

            var rawUrl = this.Url;

            if (rawUrl.Contains(MesssageKey))
            {
                rawUrl = rawUrl.Replace(MesssageKey, exception.Message);
            }

            context.Response.Redirect(rawUrl);

            return(exception);
        }
Exemple #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        public static string EncodeRequestData(IList <KeyValuePair <string, object> > requestData)
        {
            ArgumentAssertion.IsNotNull(requestData, "requestData");

            var buffer = new StringBuilder(1024);

            if (requestData.Count > 0)
            {
                var processFirst = false;
                foreach (var item in requestData)
                {
                    if (processFirst == false)
                    {
                        processFirst = true;
                    }
                    else
                    {
                        buffer.Append("&");
                    }
                    buffer.AppendFormat("{0}={1}", item.Key, item.Value);
                }
            }


            return(buffer.ToString());
        }
Exemple #21
0
        /// <summary>
        /// 获取子节点列表
        /// </summary>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        public IList <IConfigNode> GetNodeList(string nodeName)
        {
            ArgumentAssertion.IsNotNull(nodeName, "nodeName");
            var propValue = this.propertyMap[nodeName.ToLower()];

            return(propValue as IList <IConfigNode>);
        }
        static string GetPaginationSql(SqlWrap sql, Pagination pagination)
        {
            ArgumentAssertion.IsNotNull(sql, "sql");

            var paginationSql = PaginationSql.Parse(sql);

            var startIndex      = (pagination.PageIndex - 1) * pagination.PageSize;
            var endIndex        = pagination.PageIndex * pagination.PageSize;
            var whereExpression = string.IsNullOrEmpty(paginationSql.WhereExpression) ? "" : string.Concat("where ", paginationSql.WhereExpression);

            var sqlBuilder = new StringBuilder(1204);

            sqlBuilder.AppendFormat("select count(*) from {0} {1};\r\n", paginationSql.Tables, whereExpression);
            if (string.IsNullOrEmpty(sql.PrimaryKey))
            {
                sqlBuilder.AppendFormat("select {0} from (", paginationSql.Columns);
                sqlBuilder.AppendFormat("\r\n  select {0},row_number() over(order by {3}) _row_number from {1} {2}", paginationSql.Columns, paginationSql.Tables, whereExpression, paginationSql.OrderExpression);
                sqlBuilder.AppendFormat("\r\n ) _ZZZ where _row_number>{0} and _row_number<= {1} order by _row_number", startIndex, endIndex);
            }
            else
            {
                sqlBuilder.AppendFormat("select {0} from {1} _AAA, (", paginationSql.Columns, paginationSql.Tables);
                sqlBuilder.AppendFormat("\r\n  select {0} _zzzId,row_number() over(order by {3}) _row_number from {1} {2}", sql.PrimaryKey, paginationSql.Tables, whereExpression, paginationSql.OrderExpression);
                sqlBuilder.AppendFormat("\r\n ) _ZZZ where _row_number>{0} and _row_number<= {1} and _AAA.{2}=_ZZZ._zzzId order by _row_number", startIndex, endIndex, sql.PrimaryKey);
            }
            return(sqlBuilder.ToString());
        }
Exemple #23
0
        private static string GenerateKey(string privateKey)
        {
            ArgumentAssertion.IsNotNull(privateKey, "privateKey");

            var key = HashHelper.ComputeHash(string.Concat(privateKey, ModuleEnvironment.EncryptSalt), HashAlgorithmName.MD5);

            return(key);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="context"></param>
 public void Init(HttpApplication context)
 {
     ArgumentAssertion.IsNotNull(context, "context");
     this.httpApplication               = context;
     this.httpApplication.Error        += new EventHandler(context_Error);
     this.httpApplication.BeginRequest += new EventHandler(httpApplication_BeginRequest);
     this.httpApplication.EndRequest   += new EventHandler(httpApplication_EndRequest);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="iDCard"></param>
        /// <returns></returns>
        public static TargetEmploye FindByIDCard(string iDCard)
        {
            ArgumentAssertion.IsNotNull(iDCard, "iDCard");

            var repository = RepositoryManager.GetRepository <ITargetEmployeRepository>(ModuleEnvironment.ModuleName);
            var model      = repository.FindByIDCard(iDCard);

            return(model);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="originalException"></param>
        /// <param name="bizInfo"></param>
        /// <returns></returns>
        public bool Handle(Exception originalException, IDictionary bizInfo)
        {
            ArgumentAssertion.IsNotNull(originalException, "originalException");

            Guid      handlingInstanceID = Guid.NewGuid();
            Exception chainException     = ExecuteHandlerChain(originalException, handlingInstanceID, bizInfo);

            return(RethrowRecommended(chainException, originalException));
        }
Exemple #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static long FindIdByUserName(string userName)
        {
            ArgumentAssertion.IsNotNull(userName, "userName");

            var repository = RepositoryManager.GetRepository <IUserPassportRepository>(ModuleEnvironment.ModuleName);
            var userId     = repository.FindIdByUserName(userName);

            return(userId);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="password"></param>
        /// <param name="userPassport"></param>
        /// <returns></returns>
        internal static string HashPassword(string password, UserPassport userPassport)
        {
            ArgumentAssertion.IsNotNull(userPassport, "userPassport");
            ArgumentAssertion.IsNotNull(userPassport.UserSecurity, "userPassport.UserSecurity");

            var securityStrategy = LoadSecurityStrategy(userPassport.UserSecurity.HashAlgorithm);

            return(securityStrategy.HashPassword(password, userPassport));
        }
Exemple #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entName"></param>
        /// <returns></returns>
        public static OpenAccountRequest FindByEntName(string entName)
        {
            ArgumentAssertion.IsNotNull(entName, "entName");

            var repository = RepositoryManager.GetRepository <IOpenAccountRequestRepository>(ModuleEnvironment.ModuleName);
            var model      = repository.FindByEntName(entName);

            return(model);
        }
Exemple #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static long FindIdByEmail(string email)
        {
            ArgumentAssertion.IsNotNull(email, "email");

            var repository = RepositoryManager.GetRepository <IUserPassportRepository>(ModuleEnvironment.ModuleName);
            var userId     = repository.FindIdByEmail(email);

            return(userId);
        }