Example #1
0
        private void LoadSettings()
        {
            var cmd = _db.GetCommand("usp1_AppSetting_get_all");

            (cmd as SqlCommand).Parameters.AddWithValue("@AppId", _appid);

            var dbr = _db.ExecuteReader(cmd, (reader) =>
            {
                var x = new AppSettingModel
                {
                    AppSettingCategoryID = SafeClrConvert.ToInt32(reader["AppSettingCategoryID"]),
                    AppSettingID         = SafeClrConvert.ToInt32(reader["AppSettingID"]),
                    Title          = SafeClrConvert.ToString(reader["Title"]),
                    Description    = SafeClrConvert.ToString(reader["Description"]),
                    Key            = SafeClrConvert.ToString(reader["Key"]),
                    Value          = SafeClrConvert.ToString(reader["Value"]),
                    Encrypted      = SafeClrConvert.ToBoolean(reader["Encrypted"]),
                    DecryptedValue = SafeClrConvert.ToString(reader["DecryptedValue"])
                };

                x.Category = _categories[x.AppSettingCategoryID];

                _settings.TryAdd(x.Key, x);

                return(x);
            });
        }
        private static int GC_THRESHOLD      = 30;         // if 30% of ip addresses are candidate to be removed
        // (i.e. their sessions have been timed out), try garbage collection
        // on the ip addresses list ("entries" variable).
        #endregion
        static DosAttackModule()
        {
            REQUEST_THRESHOLD = SafeClrConvert.ToInt32(WebConfigurationManager.AppSettings["DOS_REQUEST_THRESHOLD"]);
            if (REQUEST_THRESHOLD <= 0)
            {
                REQUEST_THRESHOLD = 15;
            }

            RELEASE_INTERVAL = SafeClrConvert.ToInt32(WebConfigurationManager.AppSettings["DOS_RELEASE_INTERVAL"]);
            if (RELEASE_INTERVAL <= 0)
            {
                RELEASE_INTERVAL = 10 * 60;
            }

            GC_CHECK_INTERVAL = SafeClrConvert.ToInt32(WebConfigurationManager.AppSettings["DOS_GC_CHECK_INTERVAL"]);
            if (GC_CHECK_INTERVAL <= 0)
            {
                GC_CHECK_INTERVAL = 30 * 60;
            }

            SESSION_TIMEOUT = SafeClrConvert.ToInt32(WebConfigurationManager.AppSettings["DOS_SESSION_TIMEOUT"]);
            if (SESSION_TIMEOUT <= 0)
            {
                SESSION_TIMEOUT = 8 * 60;
            }

            GC_THRESHOLD = SafeClrConvert.ToInt32(WebConfigurationManager.AppSettings["DOS_GC_THRESHOLD"]);
            if (GC_THRESHOLD <= 0)
            {
                GC_THRESHOLD = 30;
            }

            moduleEnabled = SafeClrConvert.ToBoolean(WebConfigurationManager.AppSettings["DOS_DEFENDER_ENABLED"] ?? "true");
            excludeIPs    = SafeClrConvert.ToString(WebConfigurationManager.AppSettings["DOS_DEFENDER_EXCLUDE_IPS"]).Split(',');
        }
Example #3
0
        private bool IsCompressedResponseRequested()
        {
            if (CallContext != null && CallContext.HttpContext != null && CallContext.HttpContext.Request != null)
            {
                var Request = CallContext.HttpContext.Request;

                return(CallContext.Api?.CompressedResponse || SafeClrConvert.ToBoolean(Request.Headers["x-request-compressed-response"]));
            }

            return(false);
        }
Example #4
0
        public override void Test()
        {
            var connstr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
            var conn    = new SqlConnection(connstr);

            try
            {
                conn.Open();
                using (SqlCommand command = new SqlCommand("select * from dbo.FilmTbl where filmcode=42690", conn))
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var f = new Film();

                            f.FilmCode            = SafeClrConvert.ToInt32(reader["FilmCode"]);
                            f.FilmDesc            = SafeClrConvert.ToString(reader["FilmDesc"]);
                            f.Iranian             = SafeClrConvert.ToBoolean(reader["Iranian"]);
                            f.Director            = SafeClrConvert.ToString(reader["Director"]);
                            f.Summary             = SafeClrConvert.ToString(reader["Summary"]);
                            f.ReleaseDate         = SafeClrConvert.ToString(reader["ReleaseDate"]);
                            f.RunningTime         = SafeClrConvert.ToString(reader["RunningTime"]);
                            f.Genre               = SafeClrConvert.ToString(reader["Genre"]);
                            f.Trailer             = SafeClrConvert.ToString(reader["Trailer"]);
                            f.Year                = SafeClrConvert.ToString(reader["Year"]);
                            f.Producer            = SafeClrConvert.ToString(reader["Producer"]);
                            f.Casting             = SafeClrConvert.ToString(reader["Casting"]);
                            f.Credits             = SafeClrConvert.ToString(reader["Credits"]);
                            f.Filmimage           = SafeClrConvert.ToString(reader["Filmimage"]);
                            f.Film_id             = SafeClrConvert.ToInt32(reader["Film_id"]);
                            f.Category_Id         = SafeClrConvert.ToInt32(reader["Category_Id"]);
                            f.date                = SafeClrConvert.ToDateTime(reader["date"]);
                            f.FilmHorizontalImage = SafeClrConvert.ToString(reader["FilmHorizontalImage"]);
                            f.distribution        = SafeClrConvert.ToString(reader["distribution"]);
                            f.ShowSale            = SafeClrConvert.ToBoolean(reader["ShowSale"]);
                            f.Film_Field1         = SafeClrConvert.ToString(reader["Film_Field1"]);
                            f.Film_Field2         = SafeClrConvert.ToString(reader["Film_Field2"]);
                            f.Film_Order          = SafeClrConvert.ToInt32(reader["Film_Order"]);
                            f.Rating              = SafeClrConvert.ToInt32(reader["Rating"]);
                            f.Rating_Users        = SafeClrConvert.ToInt32(reader["Rating_Users"]);
                            f.Film_Field3         = SafeClrConvert.ToString(reader["Film_Field3"]);

                            System.Console.WriteLine(JsonConvert.SerializeObject(f));
                        }
                    }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
            }
        }
        public ActionResult Send(NotifyType notifyType)
        {
            var result  = new ServiceResponse <object>();
            var request = null as NotifyRequest;

            switch (notifyType)
            {
            case NotifyType.Email:
                request = new EmailNotifyRequest
                {
                    Body    = Request.Form["Body"],
                    Email   = Request.Form["To"],
                    Subject = Request.Form["Subject"],
                    IsHtml  = SafeClrConvert.ToBoolean(Request.Form["IsHtml"])
                };
                break;

            case NotifyType.SMS:
                request = new SmsNotifyRequest
                {
                    Message  = Request.Form["Message"],
                    MobileNo = Request.Form["targetNumber"]
                };
                break;

            default:
                result.Status  = "InvalidOrUnsupportedNotifyType";
                result.Message = "Specified notify type is not supported or valid";
                break;
            }

            if (request != null)
            {
                try
                {
                    result.Data    = notificationService.Notify(notifyType, request);
                    result.Success = true;
                }
                catch (Exception e)
                {
                    result.Exception = e;
                }
            }

            return(Content(JsonConvert.SerializeObject(result), "application/javascript"));
        }
Example #6
0
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            var skip = SafeClrConvert.ToBoolean(filterContext.HttpContext.Items["x_request_body_read"]);

            if (!skip)
            {
                var data = "";

                using (var reader = new StreamReader(filterContext.HttpContext.Request.InputStream))
                {
                    data = reader.ReadToEnd();
                }

                filterContext.HttpContext.Items.Add("x_request_body_read", true);
                filterContext.HttpContext.Items.Add("x_request_body", data);
            }
        }
Example #7
0
        public DbResult <bool> _RoleExists(string roleName)
        {
            var cmd  = db.GetCommand("usp1_Role_exists");
            var args = new
            {
                roleName,
                Result = CommandParameter.Output(SqlDbType.Bit)
            };
            var dbr    = db.ExecuteNonQuery(cmd, args);
            var result = dbr.Copy <bool>();

            if (dbr.Success)
            {
                result.Data = SafeClrConvert.ToBoolean(args.Result.Value);
            }

            return(result);
        }
        public virtual string AddActionJs(string dynamicResourceExtraArgs = "")
        {
            Logger?.LogCategory("AddActionJs()");

            var result = "";
            var js     = SafeClrConvert.ToString(ViewData[WebConstants.JS_KEY]);
            var staticResourceDefaultBasePath          = WebConstants.JsStaticResourceDefaultBasePath;
            var dynamicResourceResourceDefaultBasePath = WebConstants.JsDynamicResourceResourceDefaultBasePath;
            var dynamicResourceDefaultBasePath         = WebConstants.JsDynamicResourceDefaultBasePath;

            if (string.IsNullOrEmpty(staticResourceDefaultBasePath))
            {
                staticResourceDefaultBasePath = "/js";
            }
            if (string.IsNullOrEmpty(dynamicResourceResourceDefaultBasePath))
            {
                dynamicResourceResourceDefaultBasePath = "/js";
            }
            if (string.IsNullOrEmpty(dynamicResourceDefaultBasePath))
            {
                dynamicResourceDefaultBasePath = "/js/app";
            }

            if (SafeClrConvert.ToBoolean(js))
            {
                result = GetPath(processingAction: "/" + WebConstants.JS_PROCESSING_ACTION,
                                 staticResourcePathKey: WebConstants.JS_STATIC_RESOURCE_PATH_KEY,
                                 staticResourceDefaultBasePath: staticResourceDefaultBasePath,
                                 dynamicResourceResourceBasePathKey: WebConstants.JS_DYNAMIC_RESOURCE_RESOURCE_BASEPATH_KEY,
                                 dynamicResourceResourceDefaultBasePath: dynamicResourceResourceDefaultBasePath,
                                 dynamicResourcePathKey: WebConstants.JS_DYNAMIC_RESOURCE_PATH_KEY,
                                 dynamicResourceDefaultBasePath: dynamicResourceDefaultBasePath,
                                 typeKey: WebConstants.JS_TYPE_KEY,
                                 extension: ".js",
                                 staticResourceExtraArgsKey: WebConstants.JS_EXTRA_ARGS_KEY,
                                 dynamicResourceExtraArgs: dynamicResourceExtraArgs);

                result = $"<script type=\"text/javascript\" src=\"{result}\"></script>";
            }

            Logger?.Log($"   result: {result}");

            return(result);
        }
        public virtual string AddActionCss(string dynamicResourceExtraArgs = "")
        {
            Logger?.LogCategory("AddActionCss()");

            var result = "";
            var css    = SafeClrConvert.ToString(ViewData[WebConstants.CSS_KEY]);
            var staticResourceDefaultBasePath          = WebConstants.CssStaticResourceDefaultBasePath;
            var dynamicResourceResourceDefaultBasePath = WebConstants.CssDynamicResourceResourceDefaultBasePath;
            var dynamicResourceDefaultBasePath         = WebConstants.CssDynamicResourceDefaultBasePath;

            if (string.IsNullOrEmpty(staticResourceDefaultBasePath))
            {
                staticResourceDefaultBasePath = "/css";
            }
            if (string.IsNullOrEmpty(dynamicResourceResourceDefaultBasePath))
            {
                dynamicResourceResourceDefaultBasePath = "/css";
            }
            if (string.IsNullOrEmpty(dynamicResourceDefaultBasePath))
            {
                dynamicResourceDefaultBasePath = "/css/app";
            }

            if (SafeClrConvert.ToBoolean(css))
            {
                result = GetPath(processingAction: "/" + WebConstants.CSS_PROCESSING_ACTION,
                                 staticResourcePathKey: WebConstants.CSS_STATIC_RESOURCE_PATH_KEY,
                                 staticResourceDefaultBasePath: staticResourceDefaultBasePath,
                                 dynamicResourceResourceBasePathKey: WebConstants.CSS_DYNAMIC_RESOURCE_RESOURCE_BASEPATH_KEY,
                                 dynamicResourceResourceDefaultBasePath: dynamicResourceResourceDefaultBasePath,
                                 dynamicResourcePathKey: WebConstants.CSS_DYNAMIC_RESOURCE_PATH_KEY,
                                 dynamicResourceDefaultBasePath: dynamicResourceDefaultBasePath,
                                 typeKey: WebConstants.CSS_TYPE_KEY,
                                 extension: ".css",
                                 staticResourceExtraArgsKey: WebConstants.CSS_EXTRA_ARGS_KEY,
                                 dynamicResourceExtraArgs: dynamicResourceExtraArgs);
                result = $"<link rel=\"stylesheet\" type=\"text/css\" href=\"{result}\" />";
            }

            Logger?.Log($"   result: {result}");

            return(result);
        }
Example #10
0
        public DbResult <bool> _IsUserInRole(string username, string roleName)
        {
            var cmd  = db.GetCommand("usp1_User_is_in_role");
            var args = new
            {
                username,
                roleName,
                Result = CommandParameter.Output(SqlDbType.Bit)
            };
            var dbr    = db.ExecuteNonQuery(cmd, args);
            var result = dbr.Copy <bool>();

            if (dbr.Success)
            {
                result.Data = SafeClrConvert.ToBoolean(args.Result.Value);
            }

            return(result);
        }
Example #11
0
        public static HtmlString ActionJs(ViewContext context)
        {
            var useActionJs = SafeClrConvert.ToBoolean(context.ViewData["UseActionJs"], true);

            if (useActionJs)
            {
                var area       = context.RouteData.DataTokens["area"]?.ToString().ToLower();
                var controller = context.RouteData.Values["controller"]?.ToString().ToLower();
                var action     = context.RouteData.Values["action"]?.ToString().ToLower();

                if (string.IsNullOrEmpty(area))
                {
                    area = "app";
                }

                return(new HtmlString($"<script src=\"/js/{area}/{controller}/{action}.js?{hashNumber}\"></script>"));
            }

            return(new HtmlString(""));
        }
Example #12
0
        public static HtmlString ActionCss(ViewContext context)
        {
            var useActionCss = SafeClrConvert.ToBoolean(context.ViewData["UseActionCss"], true);

            if (useActionCss)
            {
                var area       = context.RouteData.DataTokens["area"]?.ToString().ToLower();
                var controller = context.RouteData.Values["controller"]?.ToString().ToLower();
                var action     = context.RouteData.Values["action"]?.ToString().ToLower();

                if (string.IsNullOrEmpty(area))
                {
                    area = "app";
                }

                return(new HtmlString($"<link href=\"/css/{area}/{controller}/{action}.css?{hashNumber}\" rel=\"stylesheet\" type=\"text/css\" />"));
            }

            return(new HtmlString(""));
        }
Example #13
0
        public static HtmlSelect GetSelect(this SqlBaseInfoProvider bip, string category, object options = null)
        {
            var data = bip.GetAllAsDictionary(category);

            var result = new HtmlSelect
            {
                Name  = category,
                ID    = category,
                Items = data
            };

            if (options != null)
            {
                result.Class        = SafeClrConvert.ToString(options.ReadProperty("class"));
                result.CurrentValue = SafeClrConvert.ToString(options.ReadProperty("currentvalue"));
                result.FirstText    = SafeClrConvert.ToString(options.ReadProperty("firsttext"));
                result.FirstValue   = SafeClrConvert.ToString(options.ReadProperty("firstvalue"));
                result.Style        = SafeClrConvert.ToString(options.ReadProperty("style"));
                result.Size         = SafeClrConvert.ToInt32(options.ReadProperty("size"));
                result.Multiple     = SafeClrConvert.ToBoolean(options.ReadProperty("multiple"));
            }

            return(result);
        }
Example #14
0
        public static string ToJson(this IBaseServiceResponse response, JsonSerializationOptions options = null)
        {
            var _options = new JsonSerializationOptions(options);
            var result   = new StringBuilder();

            if (response != null)
            {
                foreach (var prop in response.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (prop.CanRead)
                    {
                        var propType = prop.PropertyType;
                        var value    = prop.GetValue(response);

                        if (value != null)
                        {
                            var cmdParam = value as CommandParameter;
                            if (cmdParam != null)
                            {
                                result.AppendFormatWithCommaIfNotEmpty("\"{0}\": {1}", prop.Name, cmdParam.ToJson());
                                continue;
                            }
                            if (propType.IsEnum)
                            {
                                result.AppendFormatWithCommaIfNotEmpty("\"{0}\": \"{1}\"", prop.Name, value.ToString());
                                continue;
                            }
                            if (propType == TypeHelper.TypeOfBool)
                            {
                                result.AppendFormatWithCommaIfNotEmpty("\"{0}\": {1}", prop.Name,
                                                                       SafeClrConvert.ToBoolean(value) ? "true" : "false");
                                continue;
                            }
                            if (propType == TypeHelper.TypeOfString)
                            {
                                result.AppendFormatWithCommaIfNotEmpty("\"{0}\": \"{1}\"", prop.Name, value);
                                continue;
                            }
                            if (propType == TypeHelper.TypeOfChar)
                            {
                                result.AppendFormatWithCommaIfNotEmpty("\"{0}\": '{1}'", prop.Name, value);
                                continue;
                            }
                            if (propType.IsBasicType())
                            {
                                result.AppendFormatWithCommaIfNotEmpty("\"{0}\": {1}", prop.Name, value);
                                continue;
                            }
                            if (value is Guid)
                            {
                                if ((Guid)value != Guid.Empty)
                                {
                                    result.AppendFormatWithCommaIfNotEmpty("\"{0}\":'{1}'", prop.Name, value);
                                    continue;
                                }
                                else
                                {
                                    result.AppendFormatWithCommaIfNotEmpty("\"{0}\":null", prop.Name);
                                    continue;
                                }
                            }
                            var jm = value as IJsonSerializable;

                            if (jm != null)
                            {
                                result.AppendFormatWithCommaIfNotEmpty("\"{0}\":{1}", prop.Name, jm.ToJson(_options));
                                continue;
                            }

                            var e = value as IEnumerable;
                            if (e != null)
                            {
                                result.AppendFormatWithCommaIfNotEmpty("\"{0}\": ", prop.Name);
                                result.Append(e.ToJson(_options));
                                continue;
                            }
                            result.AppendFormatWithCommaIfNotEmpty("\"{0}\": \"{1}\"", prop.Name, value.ToString());
                        }
                        else
                        {
                            result.AppendFormatWithCommaIfNotEmpty("\"{0}\": null", prop.Name);
                        }
                    }
                }
            }

            return("{" + result + "}");
        }
Example #15
0
        public static void SafeApplyOutputs(this DbCommand cmd, object parameters, PropertyInfo[] properties = null)
        {
            cmd.ApplyOutputs(parameters, (obj, prop, value) =>
            {
                if (value == null || DBNull.Value.Equals(value))
                {
                    if (prop.PropertyType.IsNullable() && prop.CanWrite)
                    {
                        prop.SetValue(obj, null);
                    }
                }
                else
                {
                    if (prop.PropertyType == typeof(CommandParameter))
                    {
                        var cp = prop.GetValue(obj) as CommandParameter;

                        if (cp != null)
                        {
                            cp.Value = value;
                        }
                    }
                    else
                    {
                        do
                        {
                            if (prop.PropertyType == TypeHelper.TypeOfInt16 || prop.PropertyType == TypeHelper.TypeOfNullableInt16)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToInt16(value));
                                break;
                            }


                            if (prop.PropertyType == TypeHelper.TypeOfInt32 || prop.PropertyType == TypeHelper.TypeOfNullableInt32)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToInt32(value));
                                break;
                            }


                            if (prop.PropertyType == TypeHelper.TypeOfInt64 || prop.PropertyType == TypeHelper.TypeOfNullableInt64)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToInt64(value));
                                break;
                            }


                            if (prop.PropertyType == TypeHelper.TypeOfUInt16 || prop.PropertyType == TypeHelper.TypeOfNullableUInt16)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToUInt16(value));
                                break;
                            }


                            if (prop.PropertyType == TypeHelper.TypeOfUInt32 || prop.PropertyType == TypeHelper.TypeOfNullableUInt32)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToUInt32(value));
                                break;
                            }


                            if (prop.PropertyType == TypeHelper.TypeOfUInt64 || prop.PropertyType == TypeHelper.TypeOfNullableUInt64)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToUInt64(value));
                                break;
                            }


                            if (prop.PropertyType == TypeHelper.TypeOfSingle || prop.PropertyType == TypeHelper.TypeOfNullableSingle)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToSingle(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfFloat || prop.PropertyType == TypeHelper.TypeOfNullableFloat)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToFloat(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfDouble || prop.PropertyType == TypeHelper.TypeOfNullableDouble)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToDouble(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfDecimal || prop.PropertyType == TypeHelper.TypeOfNullableDecimal)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToDecimal(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfByte || prop.PropertyType == TypeHelper.TypeOfNullableByte)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToByte(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfSByte || prop.PropertyType == TypeHelper.TypeOfNullableSByte)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToSByte(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfChar || prop.PropertyType == TypeHelper.TypeOfNullableChar)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToChar(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfString)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToString(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfBool || prop.PropertyType == TypeHelper.TypeOfNullableBool)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToBoolean(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfDateTime || prop.PropertyType == TypeHelper.TypeOfNullableDateTime)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToDateTime(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfDateTimeOffset || prop.PropertyType == TypeHelper.TypeOfNullableDateTimeOffset)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToDateTime(value));
                                break;
                            }

                            if (prop.PropertyType == TypeHelper.TypeOfTimeSpan || prop.PropertyType == TypeHelper.TypeOfNullableTimeSpan)
                            {
                                prop.SetValue(obj, SafeClrConvert.ToTimeSpan(value));
                                break;
                            }

                            prop.SetValue(obj, value);
                        }while (false);
                    }
                }
            }, properties);
        }
Example #16
0
        public object Map(IDataReader reader, Type type)
        {
            var result = Activator.CreateInstance(type);

            ReflectionHelper.ForEachPublicInstanceReadableProperty(type, prop =>
            {
                if (reader.HasColumn(prop.Name))
                {
                    var value = reader[prop.Name];

                    if (value != null && !DBNull.Value.Equals(value))
                    {
                        var propType = prop.PropertyType;

                        if (propType == TypeHelper.TypeOfBool || propType == TypeHelper.TypeOfNullableBool)
                        {
                            prop.SetValue(result, SafeClrConvert.ToBoolean(value));
                        }
                        else if (propType == TypeHelper.TypeOfByte || propType == TypeHelper.TypeOfNullableByte)
                        {
                            prop.SetValue(result, SafeClrConvert.ToByte(value));
                        }
                        else if (propType == TypeHelper.TypeOfByteArray)
                        {
                            prop.SetValue(result, (byte[])value);
                        }
                        else if (propType == TypeHelper.TypeOfChar || propType == TypeHelper.TypeOfNullableChar)
                        {
                            prop.SetValue(result, SafeClrConvert.ToChar(value));
                        }
                        else if (propType == TypeHelper.TypeOfDateTime || propType == TypeHelper.TypeOfNullableDateTime)
                        {
                            prop.SetValue(result, SafeClrConvert.ToDateTime(value));
                        }
                        else if (propType == TypeHelper.TypeOfDateTimeOffset || propType == TypeHelper.TypeOfNullableDateTimeOffset)
                        {
                            prop.SetValue(result, SafeClrConvert.ToDateTime(value));
                        }
                        else if (propType == TypeHelper.TypeOfDecimal || propType == TypeHelper.TypeOfNullableDecimal)
                        {
                            prop.SetValue(result, SafeClrConvert.ToDecimal(value));
                        }
                        else if (propType == TypeHelper.TypeOfDouble || propType == TypeHelper.TypeOfNullableDouble)
                        {
                            prop.SetValue(result, SafeClrConvert.ToDouble(value));
                        }
                        else if (propType == TypeHelper.TypeOfFloat || propType == TypeHelper.TypeOfNullableFloat)
                        {
                            prop.SetValue(result, SafeClrConvert.ToSingle(value));
                        }
                        else if (propType == TypeHelper.TypeOfGuid)
                        {
                            prop.SetValue(result, new Guid(SafeClrConvert.ToString(value)));
                        }
                        else if (propType == TypeHelper.TypeOfInt16 || propType == TypeHelper.TypeOfNullableInt16)
                        {
                            prop.SetValue(result, SafeClrConvert.ToInt16(value));
                        }
                        else if (propType == TypeHelper.TypeOfInt32 || propType == TypeHelper.TypeOfNullableInt32)
                        {
                            prop.SetValue(result, SafeClrConvert.ToInt32(value));
                        }
                        else if (propType == TypeHelper.TypeOfInt64 || propType == TypeHelper.TypeOfNullableInt64)
                        {
                            prop.SetValue(result, SafeClrConvert.ToInt64(value));
                        }
                        else if (propType == TypeHelper.TypeOfSByte || propType == TypeHelper.TypeOfNullableSByte)
                        {
                            prop.SetValue(result, SafeClrConvert.ToSByte(value));
                        }
                        else if (propType == TypeHelper.TypeOfString)
                        {
                            prop.SetValue(result, SafeClrConvert.ToString(value));
                        }
                        else if (propType == TypeHelper.TypeOfTimeSpan || propType == TypeHelper.TypeOfNullableTimeSpan)
                        {
                            prop.SetValue(result, SafeClrConvert.ToDateTime(value));
                        }
                        else if (propType == TypeHelper.TypeOfUInt16 || propType == TypeHelper.TypeOfNullableUInt16)
                        {
                            prop.SetValue(result, SafeClrConvert.ToUInt16(value));
                        }
                        else if (propType == TypeHelper.TypeOfUInt32 || propType == TypeHelper.TypeOfNullableUInt32)
                        {
                            prop.SetValue(result, SafeClrConvert.ToUInt32(value));
                        }
                        else if (propType == TypeHelper.TypeOfUInt64 || propType == TypeHelper.TypeOfNullableUInt64)
                        {
                            prop.SetValue(result, SafeClrConvert.ToUInt64(value));
                        }
                    }
                }
            });

            return(result);
        }
 public virtual bool GetDebugMode()
 {
     return(SafeClrConvert.ToBoolean(context.Request.Headers["x-app-debug"]));
 }
        protected override void OnBasicPropertyDetected(string propertyName, string propertyValue, JsonValueType itemType)
        {
            var isNumeric = !string.IsNullOrEmpty(propertyValue) && propertyValue.GetType().IsNumeric();

            switch (propertyName[0])
            {
            case 's':
                if (propertyName.Length == 6)
                {
                    Source = propertyValue;
                }
                else
                {
                    if (isNumeric)
                    {
                        SourceComparison = SafeClrConvert.ToInt32(propertyValue).ToEnum <StringComparison>();
                    }
                    else
                    {
                        StringComparison x;

                        if (Enum.TryParse(propertyValue, out x))
                        {
                            SourceComparison = x;
                        }
                    }
                }
                break;

            case 't':
                if (propertyName.Length > 1)
                {
                    switch (propertyName[1])
                    {
                    case 'a':
                        if (propertyName.Length == 6)
                        {
                            Target = propertyValue;
                        }
                        else
                        {
                            TargetIgnoreCase = SafeClrConvert.ToBoolean(propertyValue);
                        }
                        break;

                    case 'h':
                        switch (propertyName.Length)
                        {
                        case 22:
                            ThrowOnMissingProperty = SafeClrConvert.ToBoolean(propertyValue);
                            break;

                        case 18:
                            ThrowIfNotBindable = SafeClrConvert.ToBoolean(propertyValue);
                            break;

                        case 19:
                            ThrowOnMissingValue = SafeClrConvert.ToBoolean(propertyValue);
                            break;
                        }
                        break;
                    }
                }
                else
                {
                    Target = propertyValue;
                }
                break;

            case 'd':
                DefaultValue = propertyValue;
                break;

            case 'c':
                if (isNumeric)
                {
                    Conversion = SafeClrConvert.ToInt32(propertyValue).ToEnum <ModelReadType>();
                }
                else
                {
                    ModelReadType x;
                    if (Enum.TryParse <ModelReadType>(propertyValue, out x))
                    {
                        Conversion = x;
                    }
                }
                break;

            case 'i':
                Ignore = SafeClrConvert.ToBoolean(propertyValue);
                break;

            case 'a':
                break;
            }
        }
 public virtual bool GetTraceMode()
 {
     return(SafeClrConvert.ToBoolean(context.Request.Headers["x-app-trace"]));
 }
Example #20
0
        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            if (controllerContext.HttpContext == null)
            {
                throw new ArgumentNullException("controllerContext.HttpContext");
            }

            var data = "";

            try
            {
                var skip = SafeClrConvert.ToBoolean(controllerContext.HttpContext.Items["x_request_body_read"]);

                if (!skip)
                {
                    using (var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream))
                    {
                        data = reader.ReadToEnd();
                    }

                    controllerContext.HttpContext.Items.Add("x_request_body_read", true);
                    controllerContext.HttpContext.Items.Add("x_request_body", data);
                }
                else
                {
                    data = controllerContext.HttpContext.Items["x_request_body"]?.ToString();
                }

                if (!string.IsNullOrEmpty(data) && controllerContext.HttpContext.Request.IsJson())
                {
                    data = data.Trim();

                    if (!string.IsNullOrEmpty(data))
                    {
                        Object JSONObject = null;

                        if (data[0] == '[')
                        {
                            JSONObject = JsonConvert.DeserializeObject <List <ExpandoObject> >(data,
                                                                                               new ExpandoObjectConverter());
                        }
                        else
                        {
                            JSONObject = JsonConvert.DeserializeObject <ExpandoObject>(data,
                                                                                       new ExpandoObjectConverter());
                        }

                        var backingStore =
                            new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

                        if (JSONObject != null)
                        {
                            // add all properties to this backing store
                            AddToBackingStore(backingStore, String.Empty, JSONObject);
                        }

                        // return the object in a dictionary value provider so the MVC understands it
                        return(new DictionaryValueProvider <object>(backingStore, CultureInfo.CurrentCulture));
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
            }

            return(null);
        }
Example #21
0
        public static T ReflectionSafeTransform <T>(IDataReader reader) where T : class, new()
        {
            var result = new T();

            if (!reader.IsClosed)
            {
                var props = GlobalReflectionPropertyCache.Cache.GetPublicInstanceReadableProperties <T>();

                for (var i = 0; i < reader.FieldCount; i++)
                {
                    if (!reader.IsDBNull(i))
                    {
                        var column = reader.GetName(i);
                        var value  = reader[i];

                        var prop = props.FirstOrDefault(p => string.Compare(p.Name, column, true) == 0);

                        if (prop != null)
                        {
                            try
                            {
                                if (prop.PropertyType.IsNullable())
                                {
                                    if (value != null)
                                    {
                                        object nullableValue  = null;
                                        object convertedValue = null;

                                        var nullableFinalType = prop.PropertyType.GenericTypeArguments[0];

                                        if (nullableFinalType == TypeHelper.TypeOfByte)
                                        {
                                            convertedValue = SafeClrConvert.ToByte(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfInt16)
                                        {
                                            convertedValue = SafeClrConvert.ToInt16(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfInt32)
                                        {
                                            convertedValue = SafeClrConvert.ToInt32(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfInt64)
                                        {
                                            convertedValue = SafeClrConvert.ToInt64(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfSByte)
                                        {
                                            convertedValue = SafeClrConvert.ToSByte(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfUInt16)
                                        {
                                            convertedValue = SafeClrConvert.ToUInt16(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfUInt32)
                                        {
                                            convertedValue = SafeClrConvert.ToUInt32(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfUInt64)
                                        {
                                            convertedValue = SafeClrConvert.ToUInt64(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfSingle)
                                        {
                                            convertedValue = SafeClrConvert.ToSingle(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfDouble)
                                        {
                                            convertedValue = SafeClrConvert.ToDouble(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfDecimal)
                                        {
                                            convertedValue = SafeClrConvert.ToDecimal(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfString)
                                        {
                                            convertedValue = SafeClrConvert.ToString(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfDateTime)
                                        {
                                            convertedValue = SafeClrConvert.ToDateTime(value);
                                        }
                                        else
                                        if (nullableFinalType == TypeHelper.TypeOfBool)
                                        {
                                            convertedValue = SafeClrConvert.ToBoolean(value);
                                        }

                                        nullableValue = Activator.CreateInstance(prop.PropertyType, new object[] { convertedValue });

                                        prop.SetValue(result, nullableValue);
                                    }
                                }
                                else
                                {
                                    object convertedValue = null;

                                    var propType = prop.PropertyType;

                                    if (propType == TypeHelper.TypeOfByte)
                                    {
                                        convertedValue = SafeClrConvert.ToByte(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfInt16)
                                    {
                                        convertedValue = SafeClrConvert.ToInt16(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfInt32)
                                    {
                                        convertedValue = SafeClrConvert.ToInt32(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfInt64)
                                    {
                                        convertedValue = SafeClrConvert.ToInt64(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfSByte)
                                    {
                                        convertedValue = SafeClrConvert.ToSByte(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfUInt16)
                                    {
                                        convertedValue = SafeClrConvert.ToUInt16(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfUInt32)
                                    {
                                        convertedValue = SafeClrConvert.ToUInt32(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfUInt64)
                                    {
                                        convertedValue = SafeClrConvert.ToUInt64(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfSingle)
                                    {
                                        convertedValue = SafeClrConvert.ToSingle(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfDouble)
                                    {
                                        convertedValue = SafeClrConvert.ToDouble(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfDecimal)
                                    {
                                        convertedValue = SafeClrConvert.ToDecimal(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfString)
                                    {
                                        convertedValue = SafeClrConvert.ToString(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfDateTime)
                                    {
                                        convertedValue = SafeClrConvert.ToDateTime(value);
                                    }
                                    else
                                    if (propType == TypeHelper.TypeOfBool)
                                    {
                                        convertedValue = SafeClrConvert.ToBoolean(value);
                                    }

                                    if (convertedValue != null)
                                    {
                                        prop.SetValue(result, convertedValue);
                                    }
                                    else
                                    {
                                        prop.SetValue(result, value);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                throw new Exception($"error reading column {column} into prop {prop.Name}", e);
                            }
                        }
                    }
                }
            }

            return(result);
        }
Example #22
0
 public override Task RunAsync(ApiClientCustomerGetByTokenContext context)
 {
     return(ExecuteSingleAsync(context, Service.CacheKeySpecifier, Service.CacheLifeSpecifier, (cc) => Task.FromResult(!SafeClrConvert.ToBoolean(context.OutputParameters["IsChanged"].Value) && hubService.IsValidHub(cc.ApiClientCustomerHubId, context.Request.AccessToken))));
 }
Example #23
0
 public static System.Boolean ToBoolean(this string s, System.Boolean @default = default(System.Boolean))
 {
     return(SafeClrConvert.ToBoolean(s, @default));
 }
Example #24
0
        public static string ToJson(this IBaseServiceRequest request)
        {
            //var result = "";
            //result = JsonConvert.SerializeObject(request);
            //return result;

            var result = new StringBuilder();

            result.Append("{");
            if (request != null)
            {
                var cnt = 0;
                foreach (var prop in request.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (prop.CanRead)
                    {
                        if (cnt++ > 0)
                        {
                            result.Append(", ");
                        }
                        var propType = prop.PropertyType;
                        var value    = prop.GetValue(request);

                        if (value != null)
                        {
                            var cmdParam = value as CommandParameter;
                            if (cmdParam != null)
                            {
                                var cmdOutput = cmdParam as CommandOutputParameter;

                                if (cmdOutput == null)
                                {
                                    result.AppendFormat("\"{0}\": {1}", prop.Name, cmdParam.ToJson());
                                    continue;
                                }
                            }
                            if (propType.IsEnum)
                            {
                                result.AppendFormat("\"{0}\": \"{1}\"", prop.Name, value.ToString());
                                continue;
                            }
                            if (propType == TypeHelper.TypeOfBool)
                            {
                                result.AppendFormat("\"{0}\": {1}", prop.Name,
                                                    SafeClrConvert.ToBoolean(value) ? "true" : "false");
                                continue;
                            }
                            if (propType == TypeHelper.TypeOfString)
                            {
                                result.AppendFormat("\"{0}\": \"{1}\"", prop.Name, HttpUtility.JavaScriptStringEncode(value.ToString()));
                                continue;
                            }
                            if (propType == TypeHelper.TypeOfChar)
                            {
                                result.AppendFormat("\"{0}\": '{1}'", prop.Name, value);
                                continue;
                            }
                            if (propType.IsBasicType())
                            {
                                result.AppendFormat("\"{0}\": {1}", prop.Name, value);
                                continue;
                            }
                            result.AppendFormat("\"{0}\": \"{1}\"", prop.Name, HttpUtility.JavaScriptStringEncode(value.ToString()));
                        }
                        else
                        {
                            result.AppendFormat("\"{0}\": null", prop.Name);
                        }
                    }
                }
            }

            result.Append("}");

            return(result.ToString());
        }
Example #25
0
 public override void Run(ApiClientCustomerGetByTokenContext context)
 {
     ExecuteSingle(context, Service.CacheKeySpecifier, Service.CacheLifeSpecifier, (cc) => !SafeClrConvert.ToBoolean(context.OutputParameters["IsChanged"].Value) && hubService.IsValidHub(cc.ApiClientCustomerHubId, context.Request.AccessToken));
 }
Example #26
0
        public static T AppSetting <T>(string key, T defaultValue = default(T)) where T : struct
        {
            var result = default(T);
            var type   = typeof(T);
            var value  = ConfigurationManager.AppSettings[key];

            if (type.IsEnum)
            {
                if (value.IsNumeric())
                {
                    result = SafeClrConvert.ToInt(value).ToEnum(defaultValue);
                }
                else
                {
                    if (!Enum.TryParse(value, out result))
                    {
                        result = defaultValue;
                    }
                }
            }
            else
            {
                if (type.IsBasicType())
                {
                    do
                    {
                        if (type == TypeHelper.TypeOfBool)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToBoolean(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfInt16)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToInt16(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfInt32)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToInt32(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfInt64)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToInt64(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfByte)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToByte(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfSByte)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToSByte(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfUInt16)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToUInt16(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfUInt32)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToUInt32(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfUInt64)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToUInt64(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfChar)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToChar(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfDateTime)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToDateTime(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfDecimal)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToDecimal(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfDouble)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToDouble(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfFloat)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToSingle(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfGuid)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToGuid(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfTimeSpan)
                        {
                            result = (T)System.Convert.ChangeType(SafeClrConvert.ToTimeSpan(value), type);
                            break;
                        }
                        if (type == TypeHelper.TypeOfString)
                        {
                            result = (T)((object)value);
                            break;
                        }
                    }while (false);
                }
            }

            return(result);
        }
Example #27
0
            protected override void SetProperty(SetPropertyArgs args)
            {
                switch (args.PropertyName)
                {
                case "FilmCode":
                    FilmCode = SafeClrConvert.ToInt32(args.GivenValue);
                    break;

                case "FilmDesc":
                    FilmDesc = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Iranian":
                    Iranian = SafeClrConvert.ToBoolean(args.GivenValue);
                    break;

                case "Director":
                    Director = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Summary":
                    Summary = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "ReleaseDate":
                    ReleaseDate = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "RunningTime":
                    RunningTime = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Genre":
                    Genre = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Trailer":
                    Trailer = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Year":
                    Year = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Producer":
                    Producer = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Casting":
                    Casting = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Credits":
                    Credits = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Filmimage":
                    Filmimage = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Film_id":
                    Film_id = SafeClrConvert.ToInt32(args.GivenValue);
                    break;

                case "Category_Id":
                    Category_Id = SafeClrConvert.ToInt32(args.GivenValue);
                    break;

                case "date":
                    date = SafeClrConvert.ToDateTime(args.GivenValue);
                    break;

                case "FilmHorizontalImage":
                    FilmHorizontalImage = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "distribution":
                    distribution = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "ShowSale":
                    ShowSale = SafeClrConvert.ToBoolean(args.GivenValue);
                    break;

                case "Film_Field1":
                    Film_Field1 = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Film_Field2":
                    Film_Field2 = SafeClrConvert.ToString(args.GivenValue);
                    break;

                case "Film_Order":
                    Film_Order = SafeClrConvert.ToInt32(args.GivenValue);
                    break;

                case "Rating":
                    Rating = SafeClrConvert.ToInt32(args.GivenValue);
                    break;

                case "Rating_Users":
                    Rating_Users = SafeClrConvert.ToInt32(args.GivenValue);
                    break;

                case "Film_Field3":
                    Film_Field3 = SafeClrConvert.ToString(args.GivenValue);
                    break;
                }
            }