public override Task <PaymentProviderBeginPaymentResponse> BeginPaymentAsync(BeginPaymentRequest request, System.Threading.CancellationToken cancellation) { var tcs = new TaskCompletionSource <PaymentProviderBeginPaymentResponse>(); try { var pec = new ir.shaparak.pec.EShopService(); pec.PinPaymentRequestCompleted += new PinPaymentRequestCompletedEventHandler((sender, args) => { if (args.Error != null) { tcs.TrySetException(args.Error); } else if (!args.Cancelled) { try { var result = new PaymentProviderBeginPaymentResponse <AyandehBankTranStatus>(Now); result.ProviderType = this.ProviderType; result.Code = args.authority; result.SendData.Add(BankCodeArgName, args.authority.ToString()); result.Status = args.status; result.Succeeded = (args.status == 0 && args.authority != -1); result.GatewayUrl = Config.GatewayUrl + $"?{BankCodeArgName}={args.authority}"; result.SendMethod = Config.GatewayMethod; tcs.SetResult(result); } catch (Exception ex) { tcs.TrySetException(ex); } } else { tcs.SetCanceled(); } pec.Dispose(); }); var orderid = SafeClrConvert.ToInt32(request.PaymentCode); var pay = SafeClrConvert.ToInt32(request.Amount); byte pecStatus = 0; long auth = 0; cancellation.Register(() => pec.CancelAsync(request.PaymentCode)); pec.PinPaymentRequestAsync(Config.Credentials.Pin, pay, orderid, (string.IsNullOrEmpty(request.ReturnUrl) ? Config.CallbackUrl : request.ReturnUrl), auth, pecStatus, request.PaymentCode); } catch (Exception e) { tcs.SetException(e); } return(tcs.Task); }
protected override PaymentProviderEndPaymentResponse endPayment(IDictionary <string, string> request, string code, string status) { var result = new PaymentProviderEndPaymentResponse <ZarinPalBankTranStatus>(Now); var _status = SafeClrConvert.ToInt32(status); result.ProviderType = this.ProviderType; result.StrongStatus = _status.ToEnum <ZarinPalBankTranStatus>(); string authority = code; if (!EndPaymentSucceeded(status)) { result.Status = status; } else { var service = new com.zarinpal.www.PaymentGatewayImplementationService(); long refId = 0; var amount = SafeClrConvert.ToInt32(request["Amount"]); _status = service.PaymentVerification(Config.Credentials.MerchantId, authority, amount, out refId); result.Query = authority; result.Code = refId; result.StrongStatus = _status.ToEnum <ZarinPalBankTranStatus>(); result.Status = _status.ToString(); result.Succeeded = _status == 100; } return(result); }
protected override void OnBasicPropertyDetected(string propertyName, string propertyValue, JsonValueType propertyType) { if (string.Compare(propertyName, "count", StringComparison.OrdinalIgnoreCase) == 0) { Count = SafeClrConvert.ToInt32(propertyValue); } }
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); }); }
public ICircuitBreaker CreateBreaker(object arg) { ICircuitBreaker result; var maxFailures = SafeClrConvert.ToInt32(ConfigurationManager.AppSettings["CircuitBreakerMaxFailures"]); if (maxFailures <= 0) { maxFailures = 5; } var invocationTimeout = SafeClrConvert.ToInt32(ConfigurationManager.AppSettings["CircuitBreakerInvocationTimeout"]); if (invocationTimeout <= 0) { invocationTimeout = 500; } var circuitResetTimeout = SafeClrConvert.ToInt32(ConfigurationManager.AppSettings["CircuitBreakerResetTimeout"]); if (circuitResetTimeout <= 0) { circuitResetTimeout = 5000; } result = new CB( TaskScheduler.Current, maxFailures: maxFailures, invocationTimeout: TimeSpan.FromMilliseconds(invocationTimeout), circuitResetTimeout: TimeSpan.FromMilliseconds(circuitResetTimeout)); return(result); }
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")); }
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); }
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(','); }
public override Task <ShetabPaymentStep1> BeginPaymentAsync(string paymentcode, decimal amount, string returnUrl, System.Threading.CancellationToken cancellation) { var tcs = new TaskCompletionSource <ShetabPaymentStep1>(); try { var pec = new ir.shaparak.pec.EShopService(); pec.PinPaymentRequestCompleted += new PinPaymentRequestCompletedEventHandler((sender, args) => { if (args.Error != null) { tcs.TrySetException(args.Error); } else if (!args.Cancelled) { try { var result = new ShetabPaymentStep1 <ParsianBankTranStatus>(); result.BankType = this.BankType; result.Code = args.authority; result.SendData.Add("au", args.authority.ToString()); result.Status = args.status; result.Succeeded = (args.status == 0 && args.authority != -1); result.GatewayUrl = Config.GatewayUrl + "?au=" + args.authority.ToString(); result.SendMethod = Config.GatewayMethod; tcs.SetResult(result); } catch (Exception ex) { tcs.TrySetException(ex); } } else { tcs.SetCanceled(); } pec.Dispose(); }); var orderid = SafeClrConvert.ToInt32(paymentcode); var pay = SafeClrConvert.ToInt32(amount); byte pecStatus = 0; long auth = 0; cancellation.Register(() => pec.CancelAsync(paymentcode)); pec.PinPaymentRequestAsync(Config.Credentials.Pin, pay, orderid, returnUrl, auth, pecStatus, paymentcode); } catch (Exception e) { tcs.SetException(e); } return(tcs.Task); }
public override Task <PaymentProviderBeginPaymentResponse> BeginPaymentAsync(BeginPaymentRequest request, System.Threading.CancellationToken cancellation) { var tcs = new TaskCompletionSource <PaymentProviderBeginPaymentResponse>(); try { var service = new com.zarinpal.www.PaymentGatewayImplementationService(); service.PaymentRequestCompleted += new PaymentRequestCompletedEventHandler((object sender, PaymentRequestCompletedEventArgs args) => { if (args.Error != null) { tcs.TrySetException(args.Error); } else if (!args.Cancelled) { try { var result = new PaymentProviderBeginPaymentResponse <ZarinPalBankTranStatus>(Now); result.ProviderType = this.ProviderType; result.Code = SafeClrConvert.ToLong(args.Authority); result.Status = args.Result; result.Succeeded = (args.Result == 100); result.GatewayUrl = Config.GatewayUrl + $"/{result.Code}"; result.SendMethod = Config.GatewayMethod; result.StrongStatus = args.Result.ToEnum <ZarinPalBankTranStatus>(); tcs.SetResult(result); } catch (Exception ex) { tcs.TrySetException(ex); } } else { tcs.SetCanceled(); } service.Dispose(); }); var amount = SafeClrConvert.ToInt32(request.Amount); cancellation.Register(() => service.CancelAsync(request.PaymentCode)); service.PaymentRequestAsync(Config.Credentials.MerchantId, amount, request.Info, "", "", (string.IsNullOrEmpty(request.ReturnUrl) ? Config.CallbackUrl : request.ReturnUrl)); } catch (Exception e) { tcs.SetException(e); } return(tcs.Task); }
public static IEnumerable <SelectListItem> GetSelectList(this HtmlHelper helper, object value) { IEnumerable <SelectListItem> result = null; var enumType = helper.ViewData["EnumType"] as Type ?? helper.ViewData.ModelMetadata.ModelType; if (enumType != null && enumType.IsEnum) { var itemTexts = helper.ViewData["ItemTexts"] as IEnumerable <string>; if (itemTexts == null) { itemTexts = helper.ViewContext.HttpContext.Cache["EditorTemplate." + enumType.Name + ".ItemTexts"] as IEnumerable <string>; if (itemTexts == null) { itemTexts = new List <string>(); var arr = Enum.GetValues(enumType); foreach (var item in arr) { var name = null as string; var display = enumType .GetMember(item.ToString()).First() .GetCustomAttributes(false) .OfType <DisplayAttribute>() .LastOrDefault(); if (display != null) { name = display.GetName(); } else { name = item.ToString(); } (itemTexts as List <string>).Add(name); } helper.ViewContext.HttpContext.Cache["EditorTemplate." + enumType.Name + ".ItemTexts"] = itemTexts; } } result = WebHelper.CreateSelectList(enumType, SafeClrConvert.ToInt32(value), itemTexts); } if (result == null) { result = helper.ViewData["Items"] as IEnumerable <SelectListItem> ?? new List <SelectListItem>(); } return(result); }
private double Harness(ICacheManager cm, int TaskCount, int MaxItems, int GetCount) { var srg = new SimpleRandomGenerator(); for (var i = 0; i < MaxItems; i++) { var f = new Foo(); f.Name = srg.Generate(new RandomGeneratorSetting(RandomCodeType.Alpha, 300)); f.Size = SafeClrConvert.ToInt32(new RandomGeneratorSetting(RandomCodeType.Num, 3)); f.Price = SafeClrConvert.ToInt32(new RandomGeneratorSetting(RandomCodeType.Num, 5)); f.Exists = SafeClrConvert.ToInt32(new RandomGeneratorSetting(RandomCodeType.Num, 2)) % 2 == 0; cm.Add("item" + i, f); } var tasks = new Task[TaskCount]; var rnd = new Random(); for (var i = 0; i < TaskCount; i++) { tasks[i] = new Task((c) => { var _c = c as ICacheManager; if (_c != null) { for (var j = 0; j < GetCount; j++) { var x = _c.Get("item" + rnd.Next(0, MaxItems)); consume(x); Thread.Yield(); } } }, cm); } var sw = new Stopwatch(); sw.Start(); for (var i = 0; i < TaskCount; i++) { tasks[i].Start(); } Task.WaitAll(tasks); sw.Stop(); return(sw.ElapsedMilliseconds); }
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); } }
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); }
public BasicData GetById(string category, int id) { var result = new BasicData(); var rows = GetAll(category); foreach (var row in rows) { var _id = SafeClrConvert.ToInt32(row["ID"]); if (id == _id) { result = read(category, row); } } return(result); }
protected override PaymentProviderEndPaymentResponse endPayment(IDictionary <string, string> request, string code, string status) { var result = new PaymentProviderEndPaymentResponse <SamanBankTranStatus>(Now); var refnum = code; result.ProviderType = this.ProviderType; if (string.IsNullOrEmpty(refnum) || !EndPaymentSucceeded(status)) { result.Status = status; SamanBankTranStatus strongStatus; if (Enum.TryParse <SamanBankTranStatus>(status.Replace(" ", ""), out strongStatus)) { result.StrongStatus = strongStatus; } } else { ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; var eservice = new ir.shaparak.sep.PaymentIFBinding(); var config = Config as SamanBankConfig; var r = 0.0; for (var i = 0; i < config.MaxFinishPaymentRetry; i++) { r = eservice.verifyTransaction(refnum, Config.Credentials.Pin); var ri = SafeClrConvert.ToInt32(r); if (ri != 0) { result.Succeeded = EndPaymentSucceeded(ri); break; } } result.Query = code; result.Code = ""; result.Status = r; } return(result); }
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; }
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 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); }
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 override PaymentProviderBeginPaymentResponse BeginPayment(BeginPaymentRequest request) { var result = new PaymentProviderBeginPaymentResponse <ZarinPalBankTranStatus>(Now); result.ProviderType = this.ProviderType; var service = new com.zarinpal.www.PaymentGatewayImplementationService(); var amount = SafeClrConvert.ToInt32(request.Amount); string auth = ""; var status = service.PaymentRequest(Config.Credentials.MerchantId, amount, request.Info, "", "", (string.IsNullOrEmpty(request.ReturnUrl) ? Config.CallbackUrl : request.ReturnUrl), out auth); result.Code = SafeClrConvert.ToLong(auth); result.Status = status; result.Succeeded = status == 100; result.GatewayUrl = Config.GatewayUrl + $"/{result.Code}"; result.SendMethod = Config.GatewayMethod; result.StrongStatus = ((int)status).ToEnum <ZarinPalBankTranStatus>(); return(result); }
protected override void OnBasicPropertyDetected(string propertyName, string propertyValue, JsonValueType itemType) { var isNumeric = !string.IsNullOrEmpty(propertyValue) && propertyValue.GetType().IsNumeric(); switch (propertyName[9]) { case 'm': if (isNumeric) { DefaultComparison = SafeClrConvert.ToInt32(propertyValue).ToEnum <StringComparison>(); } else { StringComparison x; if (Enum.TryParse(propertyValue, out x)) { DefaultComparison = x; } } break; case 'n': if (isNumeric) { DefaultConversion = SafeClrConvert.ToInt32(propertyValue).ToEnum <ModelReadType>(); } else { ModelReadType x; if (Enum.TryParse(propertyValue, out x)) { DefaultConversion = x; } } break; } }
public override PaymentProviderBeginPaymentResponse BeginPayment(BeginPaymentRequest request) { var result = new PaymentProviderBeginPaymentResponse <AyandehBankTranStatus>(Now); result.ProviderType = this.ProviderType; var pec = new ir.shaparak.pec.EShopService(); var orderid = SafeClrConvert.ToInt32(request.PaymentCode); var pay = SafeClrConvert.ToInt32(request.Amount); byte pecStatus = 0; long auth = 0; pec.PinPaymentRequest(Config.Credentials.Pin, pay, orderid, (string.IsNullOrEmpty(request.ReturnUrl) ? Config.CallbackUrl : request.ReturnUrl), ref auth, ref pecStatus); result.Code = auth; result.SendData.Add(BankCodeArgName, auth.ToString()); result.Status = pecStatus; result.Succeeded = (pecStatus == 0 && auth != -1); result.GatewayUrl = Config.GatewayUrl + $"?{BankCodeArgName}={auth}"; result.SendMethod = Config.GatewayMethod; return(result); }
public override ShetabPaymentStep1 BeginPayment(string paymentcode, decimal amount, string returnUrl) { var result = new ShetabPaymentStep1 <ParsianBankTranStatus>(); result.BankType = this.BankType; var pec = new ir.shaparak.pec.EShopService(); var orderid = SafeClrConvert.ToInt32(paymentcode); var pay = SafeClrConvert.ToInt32(amount); byte pecStatus = 0; long auth = 0; pec.PinPaymentRequest(Config.Credentials.Pin, pay, orderid, returnUrl, ref auth, ref pecStatus); result.Code = auth; result.SendData.Add("au", auth.ToString()); result.Status = pecStatus; result.Succeeded = (pecStatus == 0 && auth != -1); result.GatewayUrl = Config.GatewayUrl + "?au=" + auth.ToString(); result.SendMethod = Config.GatewayMethod; return(result); }
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); }
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); }
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); }
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); }
protected override Task <PaymentProviderEndPaymentResponse> endPaymentAsync(IDictionary <string, string> request, string code, string status, CancellationToken cancellation) { var tcs = new TaskCompletionSource <PaymentProviderEndPaymentResponse>(); var refnum = code; try { ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; var eservice = new ir.shaparak.sep.PaymentIFBinding(); eservice.verifyTransactionCompleted += new verifyTransactionCompletedEventHandler((sender, args) => { if (args.Error != null) { tcs.TrySetException(args.Error); } else if (!args.Cancelled) { try { var result = new PaymentProviderEndPaymentResponse <SamanBankTranStatus>(Now); var config = Config as SamanBankConfig; var r = 0.0; for (var i = 0; i < config.MaxFinishPaymentRetry; i++) { r = eservice.verifyTransaction(refnum, Config.Credentials.Pin); var ri = SafeClrConvert.ToInt32(r); if (ri != 0) { result.Succeeded = EndPaymentSucceeded(ri); break; } } result.Query = code; result.Code = ""; result.Status = r; result.ProviderType = this.ProviderType; tcs.SetResult(result); } catch (Exception ex) { tcs.TrySetException(ex); } } else { tcs.SetCanceled(); } eservice.Dispose(); }); if (string.IsNullOrEmpty(refnum) || !EndPaymentSucceeded(status)) { var result = new PaymentProviderEndPaymentResponse <SamanBankTranStatus>(); result.ProviderType = this.ProviderType; result.Status = status; SamanBankTranStatus strongStatus; if (Enum.TryParse <SamanBankTranStatus>(status.Replace(" ", ""), out strongStatus)) { result.StrongStatus = strongStatus; } tcs.SetResult(result); } else { cancellation.Register(() => eservice.CancelAsync(refnum)); eservice.verifyTransactionAsync(refnum, Config.Credentials.Pin, refnum); } } catch (Exception e) { tcs.SetException(e); } return(tcs.Task); }
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; } }