예제 #1
0
        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
        {
            if (indexes.Length > 0)
            {
                var key = SafeClrConvert.ToString(indexes[0]);

                if (_keys != null)
                {
                    result = _keys[key];
                }
                else
                {
                    result = "";
                }
            }
            else
            {
                result = "";
            }

            if (result == null)
            {
                result = "";
            }

            return(true);
        }
예제 #2
0
        public ActionResult Add()
        {
            try
            {
                var wcm  = GetCache();
                var key  = SafeClrConvert.ToString(Request.Form["txtKey"]);
                var f    = JsonConvert.DeserializeObject <Foo>(SafeClrConvert.ToString(Request.Form["txtData"]));
                var life = SafeClrConvert.ToInt32(Request.Form["txtLifeLength"]);

                if (life < 0)
                {
                    life = 0;
                }

                if (f != null && !string.IsNullOrEmpty(key))
                {
                    wcm.Add(key, f, life);

                    TempData["Message"] = "Item added";
                }
                else
                {
                    TempData["Message"] = "Item is not Foo or has no key";
                }
            }
            catch (Exception e)
            {
                TempData["Message"] = e.Message;
            }

            return(Redirect("/cache"));
        }
예제 #3
0
        public IEnumerable <BasicData> GetAll()
        {
            var result = new BasicData[] {};

            var dt = Cache.Get <DataTable>(CACHE_KEY);

            if (dt == null)
            {
                Load();
            }

            dt = Cache.Get <DataTable>(CACHE_KEY);

            if (dt != null && dt.Rows.Count > 0)
            {
                result = new BasicData[dt.Rows.Count];
                var i = 0;
                foreach (DataRow row in dt.Rows)
                {
                    result[i++] = new BasicData
                    {
                        Category    = SafeClrConvert.ToString(row["Category"]),
                        Id          = SafeClrConvert.ToInt32(row["Id"]),
                        Name        = SafeClrConvert.ToString(row["Name"]),
                        Title       = SafeClrConvert.ToString(row["Title"]),
                        Description = SafeClrConvert.ToString(row["Description"]),
                        Code        = SafeClrConvert.ToString(row["Code"]),
                        Parent      = SafeClrConvert.ToInt32(row["Parent"])
                    };
                }
            }

            return(result);
        }
예제 #4
0
        private async Task <PaymentManagerReversalPaymentResponse> SaveReversalPaymentAsync(ReversalRequest request, PaymentProviderReversalPaymentResponse providerResponse, CancellationToken cancellation)
        {
            var result = new PaymentManagerReversalPaymentResponse();

            result.Request = request;

            var dbOk = false;

            Logger.LogCategory("SaveReversalPaymentAsync");

            if (providerResponse.Succeeded || !Config.SaveOnlySuccessfulOperations)
            {
                Logger.Log("Start saving in the database");

                var args = new
                {
                    Result        = CommandParameter.Output(SqlDbType.VarChar, 50),
                    PaymentCode   = request.PaymentCode,
                    BankType      = providerResponse.ProviderType,
                    StepStatus    = SafeClrConvert.ToString(providerResponse.Status),
                    StepDate      = providerResponse.Date,
                    StepSucceeded = providerResponse.Succeeded,
                    @StepData     = ""
                };
                var cmd = _db.GetCommand("usp1_Payment_save_reversal_step");

                result.DbResult = await _db.ExecuteNonQueryAsync(cmd, args, cancellation);

                if (result.DbResult.Success)
                {
                    result.Status = args.Result.Value.ToString();

                    Logger.Log("DbStatus = " + result.Status);

                    dbOk = result.Status == "Success";

                    if (!dbOk)
                    {
                        result.Status = "SaveError";
                    }
                }
                else
                {
                    Logger.Log("Failed: " + result.DbResult.Exception.ToString(","));

                    result.Failed(result.DbResult.Exception);
                }
            }
            else
            {
                dbOk = true;
            }

            if (providerResponse.Succeeded && dbOk)
            {
                result.Succeeded();
            }

            return(result);
        }
예제 #5
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);
            });
        }
예제 #6
0
        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(',');
        }
예제 #7
0
        public virtual LoggerPurgeResponse Purge(LoggerPurgeRequest request)
        {
            var response = new LoggerPurgeResponse();

            if (ConnectionStringProvider != null)
            {
                try
                {
                    var query = GetPurgeSql();

                    var constr = ConnectionStringProvider.GetConnectionString();

                    if (!string.IsNullOrEmpty(constr))
                    {
                        using (var con = new SqlConnection(constr))
                        {
                            using (var cmd = new SqlCommand(query, con))
                            {
                                cmd.CommandType = CommandType.StoredProcedure;

                                cmd.Parameters.AddOutput("@Result", SqlDbType.NVarChar, 100);
                                cmd.Parameters.AddOutput("@Info", SqlDbType.NVarChar);
                                cmd.Parameters.AddInput("@FromDate", request.FromDate);
                                cmd.Parameters.AddInput("@ToDate", request.ToDate);

                                FinalizePurgeCommand(cmd);

                                con.Open();
                                cmd.ExecuteNonQuery();

                                response.SetStatus(cmd.Parameters[0].Value);
                                response.Info = SafeClrConvert.ToString(cmd.Parameters[1].Value);
                            }
                        }
                    }
                    else
                    {
                        response.Message = "ConnectionStringProvider has no connection string";
                        response.Info    = $"Provider = {ConnectionStringProvider.GetType().Name}";
                        response.SetStatus("NoConStr");
                    }
                }
                catch (Exception e)
                {
                    response.Failed(e);
                }
            }
            else
            {
                response.Message = "No ConnectionStringProvider is specified";
                response.SetStatus("NoConStrProvider");
            }

            return(response);
        }
예제 #8
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);
            }
        }
예제 #9
0
        protected BasicData read(string category, DataRow row)
        {
            var result = new BasicData
            {
                Id          = SafeClrConvert.ToInt32(row["ID"]),
                Category    = category,
                Name        = SafeClrConvert.ToString(row["Name"]),
                Title       = SafeClrConvert.ToString(row["Title"]),
                Code        = SafeClrConvert.ToString(row["Code"]),
                Description = SafeClrConvert.ToString(row["Description"])
            };

            return(result);
        }
        protected internal virtual string GetResourceBasePath(string key, string defaultValue)
        {
            var basePath = SafeClrConvert.ToString(Settings[$"{key}"]);

            if (string.IsNullOrEmpty(basePath))
            {
                basePath = defaultValue;
            }

            Logger?.Log($"GetResourceBasePath: Args({nameof(key)}: \"{key}\", {nameof(defaultValue)}: \"{defaultValue}\")");
            Logger?.Log($"   result: \"{basePath}\"");

            return(basePath);
        }
        public override void Test()
        {
            var _args = new { a = "alireza", b = CommandParameter.Output(SqlDbType.NVarChar, -1) };
            var dbr   = DA.DefaultDb.ExecuteNonQuery("ust_test2", _args);

            if (dbr.Success)
            {
                var s = SafeClrConvert.ToString(_args.b.Value);
                System.Console.WriteLine("b: " + s);
            }
            else
            {
                System.Console.WriteLine(dbr.Exception.Message);
            }
        }
예제 #12
0
        public ActionResult Get()
        {
            var wcm = GetCache();
            var key = SafeClrConvert.ToString(Request.Form["txtKey"]);
            var x   = wcm.Get(key);

            TempData["Item"] = x;

            if (x == null)
            {
                TempData["Message"] = "Item not found";
            }

            return(Redirect("/cache"));
        }
예제 #13
0
        public override void Test()
        {
            var guid  = Guid.NewGuid();
            var _args = new { p1 = CommandParameter.Guid(guid), p2 = CommandParameter.Output(SqlDbType.UniqueIdentifier) };
            var dbr   = DA.DefaultDb.ExecuteNonQuery("ust_test1", _args);

            if (dbr.Success)
            {
                var s = SafeClrConvert.ToString(_args.p2.Value);
                System.Console.WriteLine("p2: " + s);
            }
            else
            {
                System.Console.WriteLine(dbr.Exception.Message);
            }
        }
예제 #14
0
        protected virtual LogItem Transform(IDataReader reader)
        {
            var result = new LogItem
            {
                Row      = SafeClrConvert.ToLong(reader["Row"]),
                Id       = SafeClrConvert.ToInt(reader["Id"]),
                Member   = SafeClrConvert.ToString(reader["Member"]),
                Category = SafeClrConvert.ToString(reader["Category"]),
                Message  = SafeClrConvert.ToString(reader["Message"]),
                FilePath = SafeClrConvert.ToString(reader["FilePath"]),
                LogDate  = SafeClrConvert.ToDateTime(reader["LogDate"]),
                Line     = SafeClrConvert.ToInt(reader["Line"]),
            };

            return(result);
        }
예제 #15
0
        public BasicData GetByName(string category, string name)
        {
            var result = new BasicData();
            var rows   = GetAll(category);

            foreach (var row in rows)
            {
                var _name = SafeClrConvert.ToString(row["Name"]);

                if (string.Compare(_name, name, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    result = read(category, row);
                }
            }

            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);
        }
예제 #17
0
        public DbResult <string[]> _GetAllRoles()
        {
            var cmd  = db.GetCommand("usp1_Role_get_all");
            var args = new
            {
                roles = CommandParameter.Output(SqlDbType.VarChar, 4000)
            };
            var dbr    = db.ExecuteNonQuery(cmd, args);
            var result = dbr.Copy <string[]>();

            if (dbr.Success)
            {
                var roles = SafeClrConvert.ToString(args.roles.Value);

                result.Data = roles.Split(new char[] { ',' });
            }

            return(result);
        }
예제 #18
0
        public SamanBankConfig()
        {
            this.GatewayUrl = ConfigurationManager.AppSettings["BankSamanGatewayUrl"];
            if (string.IsNullOrEmpty(this.GatewayUrl))
            {
                this.GatewayUrl = "https://sep.shaparak.ir/payment.aspx";
            }
            this.CallbackUrl           = ConfigurationManager.AppSettings["BankSamanCallbackUrl"];
            this.GatewayMethod         = HttpMethod.Post;
            this.MaxFinishPaymentRetry = SafeClrConvert.ToInt32(ConfigurationManager.AppSettings["BankSamanMaxFinishPaymentRetry"]);

            var c = new ShetabBankUserPassPinCredentials();

            c.Pin      = SafeClrConvert.ToString(ConfigurationManager.AppSettings["BankSamanMerchantID"]);
            c.Username = c.Pin;
            c.Password = SafeClrConvert.ToString(ConfigurationManager.AppSettings["BankSamanMerchantPass"]);

            this.Credentials = c;
        }
예제 #19
0
        public override string Render(object text)
        {
            var result = "";

            foreach (var ch in SafeClrConvert.ToString(text))
            {
                if (Char.IsDigit(ch) && ((int)ch - 48) < 10)
                {
                    //result += "&#" + (1632 + ((int)ch - 48)).ToString() + ";";
                    result += this.Digits[(int)ch - 48];
                }
                else
                {
                    result += ch;
                }
            }

            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);
        }
예제 #21
0
        private void LoadCategories()
        {
            var cmd = new SqlCommand("usp1_AppSettingCategory_get_all");
            var dbr = _db.ExecuteReader(cmd, (reader) =>
            {
                var cat = new AppSettingCategoryModel
                {
                    AppID = SafeClrConvert.ToInt32(reader["AppID"]),
                    AppSettingCategoryID = SafeClrConvert.ToInt32(reader["AppSettingCategoryID"]),
                    Title       = SafeClrConvert.ToString(reader["AppID"]),
                    Description = SafeClrConvert.ToString(reader["AppID"]),
                    Code        = SafeClrConvert.ToString(reader["AppID"])
                };

                _categories.TryAdd(cat.AppSettingCategoryID, cat);

                return(cat);
            });
        }
        public virtual DebugLevel GetDebugLevel()
        {
            var result = DebugLevel.Dialog;

            if (context != null)
            {
                var x = SafeClrConvert.ToString(context.Request.Headers["x-app-debug-level"]);

                if (x.IsNumeric())
                {
                    result = SafeClrConvert.ToInt32(x).ToEnum <DebugLevel>();
                }
                else
                {
                    Enum.TryParse(x, true, out result);
                }
            }

            return(result);
        }
        public virtual MessageViewerType GetViewerType()
        {
            var result = MessageViewerType.Guest;

            if (context != null)
            {
                var x = SafeClrConvert.ToString(context.Request.Headers["x-app-viewer-type"]);

                if (x.IsNumeric())
                {
                    result = SafeClrConvert.ToInt32(x).ToEnum <MessageViewerType>();
                }
                else
                {
                    Enum.TryParse(x, true, out result);
                }
            }

            return(result);
        }
예제 #24
0
        public virtual async Task <ServiceResponse <string> > AuditAsync(WebAuditData data)
        {
            var result = new ServiceResponse <string>();

            try
            {
                var cmd  = Db.GetCommand("usp0_Audit_web_direct");
                var args = GetArgs(data);

                await Db.ExecuteNonQueryAsync(cmd, args);

                result.Status  = SafeClrConvert.ToString(args.result.Value);
                result.Data    = SafeClrConvert.ToString(args.args.Value);
                result.Success = result.Status == "AuditSucceeded";
            }
            catch (Exception e)
            {
                result.Status    = "AuditError";
                result.Exception = e;
            }

            return(result);
        }
예제 #25
0
        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
        {
            KeyDataCollection keys = null;

            if (indexes.Length > 0)
            {
                var key = SafeClrConvert.ToString(indexes[0]);

                if (data != null)
                {
                    keys = data[key];
                }
            }

            if (keys == null)
            {
                keys = new KeyDataCollection(StringComparer.OrdinalIgnoreCase);
            }

            result = new IniSettingKeys(keys);

            return(true);
        }
예제 #26
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);
        }
예제 #27
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);
        }
        protected string GetPath(string processingAction,
                                 string staticResourcePathKey,
                                 string staticResourceDefaultBasePath,
                                 string dynamicResourceResourceBasePathKey,
                                 string dynamicResourceResourceDefaultBasePath,
                                 string dynamicResourcePathKey,
                                 string dynamicResourceDefaultBasePath,
                                 string typeKey,
                                 string extension,
                                 string staticResourceExtraArgsKey,
                                 string dynamicResourceExtraArgs)
        {
            var type = ViewData[typeKey]?.ToLowerCase();

            Logger?.LogCategory("GetPath(): ");
            Logger?.Log($@"Args(
        {nameof(type)}: ""{type}"",
        {nameof(extension)}: ""{extension}"",
        {nameof(staticResourcePathKey)}: ""{staticResourcePathKey}"",
        {nameof(staticResourceDefaultBasePath)}: ""{staticResourceDefaultBasePath}"",
        {nameof(dynamicResourceResourceBasePathKey)}: ""{dynamicResourceResourceBasePathKey}"",
        {nameof(dynamicResourceResourceDefaultBasePath)}: ""{dynamicResourceResourceDefaultBasePath}"",
        {nameof(dynamicResourcePathKey)}: ""{dynamicResourcePathKey}"",
        {nameof(dynamicResourceDefaultBasePath)}: ""{dynamicResourceDefaultBasePath})"",
        {nameof(staticResourceExtraArgsKey)}: ""{ staticResourceExtraArgsKey}"",
        {nameof(dynamicResourceExtraArgs)}: ""{ dynamicResourceExtraArgs})");

            if (!string.IsNullOrEmpty(type))
            {
                if (!ExternalClientSideItemType.Validate(type))
                {
                    throw new Exception($"invalid client side item type: {type}");
                }
            }

            var area = string.IsNullOrEmpty(Area) ? "" : Area + "/";
            var lang = "";
            var hash = GetHash(Action,
                               type,
                               extension,
                               staticResourcePathKey,
                               staticResourceDefaultBasePath,
                               dynamicResourceResourceBasePathKey,
                               dynamicResourceResourceDefaultBasePath,
                               dynamicResourcePathKey,
                               dynamicResourceDefaultBasePath);
            var args   = "";
            var result = "";

            if (!string.IsNullOrEmpty(type) && type != ExternalClientSideItemType.StaticFile)
            {
                Logger?.Log("Not a static file");

                args = GetArgs(hash, dynamicResourceExtraArgs);
                lang = (WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.Both || WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.OnlyLanguageBased) &&
                       !string.IsNullOrEmpty(Lang) ? Lang + "/" : "";

                if (!string.IsNullOrEmpty(type))
                {
                    type = "/" + type;
                }

                result = $"/{lang}{area}{Controller}{processingAction}/{Action}{type}{args}";
            }
            else
            {
                Logger?.Log("static file");

                var staticPath = SafeClrConvert.ToString(ViewData[staticResourcePathKey]).ToTrimmedLowerCase();

                if (string.IsNullOrEmpty(staticPath))
                {
                    staticPath = staticResourceDefaultBasePath;
                }

                if (WebConstants.SeparateClientSideStaticFilesByLanguage && (WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.Both || WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.OnlyLanguageBased) &&
                    !string.IsNullOrEmpty(Lang))
                {
                    lang = Lang + "/";
                }

                var staticResourceExtraArgs = SafeClrConvert.ToString(ViewData[staticResourceExtraArgsKey]);

                args = GetArgs(hash, staticResourceExtraArgs);

                result = $"{staticPath}/{lang}{area}{Controller}/{Action}{extension}{args}";
            }

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

            return(result);
        }
        internal virtual string GetHash(string action,
                                        string type,
                                        string extension,
                                        string staticResourcePathKey,
                                        string staticResourceDefaultBasePath,
                                        string dynamicResourceResourceBasePathKey,
                                        string dynamicResourceResourceDefaultBasePath,
                                        string dynamicResourcePathKey,
                                        string dynamicResourceDefaultBasePath)
        {
            var result = "";

            if (HashProvider != null)
            {
                var basePath = "";
                var content  = "";
                var path     = "";
                var area     = string.IsNullOrEmpty(Area) ? "" : Area + "/";
                var lang     = "";

                Logger?.LogCategory($"GetHash()");

                if (ExternalClientSideItemType.Resource.EqualsTrimmedIgnoreCase(type))
                {
                    basePath = GetResourceBasePath(dynamicResourceResourceBasePathKey, dynamicResourceResourceDefaultBasePath);
                    content  = GetResource(Page.ViewContext.Controller, basePath, action, extension);
                }
                else
                if (ExternalClientSideItemType.DynamicFile.EqualsTrimmedIgnoreCase(type))
                {
                    try
                    {
                        basePath = GetDynamicFileBasePath(extension, dynamicResourcePathKey, dynamicResourceDefaultBasePath);
                        content  = GetFile(basePath, action, extension);
                    }
                    catch (Exception e)
                    {
                        Logger?.Log($"ERROR: {e.Message}");

                        ExceptionLogger?.LogException(e, $@"GetHash();DynamicFile: Args({nameof(action)}: ""{action}"",			
{nameof(type)}: ""{type}"",
{nameof(extension)}: ""{extension}"",
{nameof(staticResourcePathKey)}: ""{staticResourcePathKey}"",
{nameof(staticResourceDefaultBasePath)}: ""{staticResourceDefaultBasePath}"",
{nameof(dynamicResourceResourceBasePathKey)}: ""{dynamicResourceResourceBasePathKey}"",
{nameof(dynamicResourceResourceDefaultBasePath)}: ""{dynamicResourceResourceDefaultBasePath}"",
{nameof(dynamicResourcePathKey)}: ""{dynamicResourcePathKey}"",
{nameof(dynamicResourceDefaultBasePath)}: ""{dynamicResourceDefaultBasePath})");


                        return(new Random().Next(99999).ToString());
                    }
                }
                else
                if (ExternalClientSideItemType.RazorView.EqualsTrimmedIgnoreCase(type))
                {
                    /*
                     * if (WebConstants.SeparateClientSideStaticFilesByLanguage && (WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.Both || WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.OnlyLanguageBased)
                     *      && !string.IsNullOrEmpty(Lang))
                     * {
                     *  lang = "." + Lang;
                     * }
                     *
                     * if (!string.IsNullOrEmpty(Area))
                     * {
                     *  path = "/Areas/" + Area + "/Views/" + Controller + "/" + action + lang + ".cshtml";
                     * }
                     * else
                     * {
                     *  path = "/Views/" + Controller + "/" + action + lang + ".cshtml";
                     * }
                     */
                    path = GetViewPath(Area, Controller, Lang, Action, extension);
                    path = path.Length > 1 ? path.Substr(2): "";
                    path = Path.Combine(HttpContext.Server.MapPath("\\"), path);

                    try
                    {
                        Logger?.Log($"Path = {path}");

                        content = File.ReadAllText(path);
                    }
                    catch (Exception e)
                    {
                        Logger?.Log($"ERROR: {e.Message}");

                        ExceptionLogger?.LogException(e, $@"GetHash();RazorView: Path = {path}"", Args({nameof(action)}: ""{action}"",			
{nameof(type)}: ""{type}"",
{nameof(extension)}: ""{extension}"",
{nameof(staticResourcePathKey)}: ""{staticResourcePathKey}"",
{nameof(staticResourceDefaultBasePath)}: ""{staticResourceDefaultBasePath}"",
{nameof(dynamicResourceResourceBasePathKey)}: ""{dynamicResourceResourceBasePathKey}"",
{nameof(dynamicResourceResourceDefaultBasePath)}: ""{dynamicResourceResourceDefaultBasePath}"",
{nameof(dynamicResourcePathKey)}: ""{dynamicResourcePathKey}"",
{nameof(dynamicResourceDefaultBasePath)}: ""{dynamicResourceDefaultBasePath})");

                        return(new Random().Next(99999).ToString());
                    }
                }
                else
                if (string.IsNullOrEmpty(type) || ExternalClientSideItemType.StaticFile.EqualsTrimmedIgnoreCase(type))
                {
                    var staticPath = SafeClrConvert.ToString(ViewData[staticResourcePathKey]).ToTrimmedLowerCase();

                    if (string.IsNullOrEmpty(staticPath))
                    {
                        staticPath = staticResourceDefaultBasePath;
                    }

                    if (WebConstants.SeparateClientSideStaticFilesByLanguage && (WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.Both || WebConstants.MultiLanguageClientAwareController == MultiLanguageRoutingOptions.OnlyLanguageBased) &&
                        !string.IsNullOrEmpty(Lang))
                    {
                        lang = Lang + "/";
                    }

                    path = Path.Combine(HttpContext.Server.MapPath("\\"), $"{staticPath}/{lang}{area}{Controller}/{Action}{extension}");

                    try
                    {
                        Logger?.Log($"Path = {path}");

                        content = File.ReadAllText(path);
                    }
                    catch (Exception e)
                    {
                        Logger?.Log($"ERROR: {e.Message}");

                        ExceptionLogger?.LogException(e, $@"GetHash();StaticFile: Path = {path}"", Args({nameof(action)}: ""{action}"",			
{nameof(type)}: ""{type}"",
{nameof(extension)}: ""{extension}"",
{nameof(staticResourcePathKey)}: ""{staticResourcePathKey}"",
{nameof(staticResourceDefaultBasePath)}: ""{staticResourceDefaultBasePath}"",
{nameof(dynamicResourceResourceBasePathKey)}: ""{dynamicResourceResourceBasePathKey}"",
{nameof(dynamicResourceResourceDefaultBasePath)}: ""{dynamicResourceResourceDefaultBasePath}"",
{nameof(dynamicResourcePathKey)}: ""{dynamicResourcePathKey}"",
{nameof(dynamicResourceDefaultBasePath)}: ""{dynamicResourceDefaultBasePath})");

                        return(new Random().Next(99999).ToString());
                    }
                }

                Logger?.Log($"content retrieved. Content Length = {content.Length}");

                result = HashProvider.GetHash(new HashContext {
                    Data = content, BasePath = basePath
                });
            }

            return(result);
        }
예제 #30
0
        private void LogInternal(LogItem log, string info)
        {
            var query =
                $@"  INSERT INTO {LogTableName}
	(
		 [Username]
		,[RoleName]
        ,[SessionId]
		,[Url]
		,[FormData]
		,[Headers]
		,[Message]
		,[StackTrace]
		,[IP]
		,[Cookies]
		,[HostName]
		,[Method]
		,[Referer]
		,[Info]
		,[Browser]
        ,[Member]
        ,[FilePath]
        ,[Line]
	 )
     VALUES
	 (
		@Username,
        @RoleName,
        @SessionId,
        @Url,
        @FormData,
        @Headers,
        @Message,
        @StackTrace,
        @IP,
        @Cookies,
        @HostName,
        @Method,
        @Referer,
        @Info,
        @Browser,
        @Member,
        @FilePath,
        @Line)
	)"    ;

            if (ConnectionStringProvider != null)
            {
                var constr = ConnectionStringProvider.GetConnectionString();

                if (!string.IsNullOrEmpty(constr))
                {
                    using (var con = new SqlConnection(constr))
                    {
                        using (var cmd = new SqlCommand(query, con))
                        {
                            cmd.CommandType = CommandType.Text;

                            cmd.Parameters.AddWithValue("@Username", SafeClrConvert.ToString(log.Username).Left(50));
                            cmd.Parameters.AddWithValue("@RoleName", SafeClrConvert.ToString(log.RoleNames).Left(50));
                            cmd.Parameters.AddWithValue("@SessionId", SafeClrConvert.ToString(log.SessionId).Left(100));
                            cmd.Parameters.AddWithValue("@Url", SafeClrConvert.ToString(log.Url).Left(500));
                            cmd.Parameters.AddWithValue("@FormData", SafeClrConvert.ToString(log.FormData).Left(4000));
                            cmd.Parameters.AddWithValue("@Headers", SafeClrConvert.ToString(log.Headers).Left(500));
                            cmd.Parameters.AddWithValue("@Message", SafeClrConvert.ToString(log.Message).Left(4000));
                            cmd.Parameters.AddWithValue("@StackTrace", SafeClrConvert.ToString(log.StackTrace));
                            cmd.Parameters.AddWithValue("@IP", SafeClrConvert.ToString(log.IP).Left(40));
                            cmd.Parameters.AddWithValue("@Cookies", SafeClrConvert.ToString(log.Cookies).Left(4000));
                            cmd.Parameters.AddWithValue("@HostName", SafeClrConvert.ToString(log.HostName).Left(30));
                            cmd.Parameters.AddWithValue("@Method", log.Method);
                            cmd.Parameters.AddWithValue("@Referer", log.Referer);
                            cmd.Parameters.AddWithValue("@Info", SafeClrConvert.ToString(info).Left(4000));
                            cmd.Parameters.AddWithValue("@Browser", log.Browser);
                            cmd.Parameters.AddWithValue("@Member", log.Member);
                            cmd.Parameters.AddWithValue("@FilePath", log.FilePath);
                            cmd.Parameters.AddWithValue("@Line", log.Line);

                            con.Open();
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
                else
                {
                    Throw($"No ConnectionString: Provider = {ConnectionStringProvider.GetType().Name}");
                }
            }
            else
            {
                Throw($"No ConnectionString Provider");
            }
        }