|
|
using Common.Model; using Common.Model.Config; using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions;
namespace Common.Helper { public static class Utilities { private static readonly Random Random = new Random(); private static readonly string MsisdnPrefix = ApplicationConfig.ReadWebConfig("MsisdnPrefix"); private static readonly string MsisdnLengthSetting = ApplicationConfig.ReadWebConfig("MsisdnLength"); private static EncryptionParameters _encryptionParams;
private static JsonResponse response = new JsonResponse(); private static List<string> lstSupportType { get; set; } private static List<string> lstTransferType { get; set; } private static List<string> lstActionType { get; set; }
//private static List<string> lstScheduleType { get; set; }
/// <summary>
/// Private method to initialize encryption parameters
/// </summary>
private static void InitializeEncryptionParameters() { _encryptionParams = new EncryptionParameters() { PassPhrase = ApplicationConfig.ReadWebConfig("symmetricKey"), HashAlgorithm = "SHA1", SaltValue = "sw!ftT3ch", PasswordIterations = 2, InitVector = "@1B2c3D4e5F6g7H8", KeySize = 256 }; }
/// <summary>
/// Encrypt string
/// </summary>
/// <returns></returns>
private static string Encrypt(EncryptionParameters encrypt) { byte[] initVectorBytes = Encoding.ASCII.GetBytes(encrypt.InitVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(encrypt.SaltValue);
// Convert our plaintext into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(encrypt.PlainText); PasswordDeriveBytes password = new PasswordDeriveBytes ( encrypt.PassPhrase, saltValueBytes, encrypt.HashAlgorithm, encrypt.PasswordIterations );
byte[] keyBytes = password.GetBytes(encrypt.KeySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor ( keyBytes, initVectorBytes );
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cryptoStream = new CryptoStream ( memoryStream, encryptor, CryptoStreamMode.Write );
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close(); cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
string cipherText = Convert.ToBase64String(cipherTextBytes);
// Return encrypted string.
return cipherText; }
/// <summary>
/// Generate random 5 digit OTP
/// </summary>
/// <returns></returns>
public static string GenerateOTP() { string[] strChar = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
string otpChar = strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)];
return otpChar; } /// <summary>
/// Decrypt string
/// </summary>
/// <returns></returns>
private static string Decrypt(EncryptionParameters decrypt) { byte[] initVectorBytes = Encoding.ASCII.GetBytes(decrypt.InitVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(decrypt.SaltValue);
// Convert our ciphertext into a byte array.
byte[] cipherTextBytes = Convert.FromBase64String(decrypt.CipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes ( decrypt.PassPhrase, saltValueBytes, decrypt.HashAlgorithm, decrypt.PasswordIterations );
// Use the password to generate pseudo-random bytes for the encryption key. Specify the
// size of the key in bytes (instead of bits).
byte[] keyBytes = password.GetBytes(decrypt.KeySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor ( keyBytes, initVectorBytes );
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
// Define cryptographic stream (always use Read mode for encryption).
CryptoStream cryptoStream = new CryptoStream ( memoryStream, decryptor, CryptoStreamMode.Read );
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
// Start decrypting.
int decryptedByteCount = cryptoStream.Read ( plainTextBytes, 0, plainTextBytes.Length );
// Close both streams.
memoryStream.Close(); cryptoStream.Close();
// Convert decrypted data into a string.
string plainText = Encoding.UTF8.GetString ( plainTextBytes, 0, decryptedByteCount );
// Return decrypted string.
return plainText; }
public static string DecryptData(string key, string encrypedData) { if (string.IsNullOrEmpty(encrypedData)) { return ""; }
string decData = null; byte[][] keys = GetHashKeys(key);
try { decData = DecryptStringFromBytes_Aes(encrypedData, keys[0], keys[1]); } catch (CryptographicException) { } catch (ArgumentNullException) { }
return decData; }
private static byte[][] GetHashKeys(string key) { byte[][] result = new byte[2][]; Encoding enc = Encoding.UTF8;
SHA256 sha2 = new SHA256CryptoServiceProvider();
byte[] rawKey = enc.GetBytes(key); byte[] rawIV = enc.GetBytes(key);
byte[] hashKey = sha2.ComputeHash(rawKey); byte[] hashIV = sha2.ComputeHash(rawIV);
Array.Resize(ref hashIV, 16);
result[0] = hashKey; result[1] = hashIV;
return result; }
private static string DecryptStringFromBytes_Aes(string cipherTextString, byte[] Key, byte[] IV) { byte[] cipherText = Convert.FromBase64String(cipherTextString); //final byte[] plainTextBytes = (orignalText)
if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV");
string plaintext = null;
using (Aes aesAlg = Aes.Create()) { aesAlg.Mode = CipherMode.CBC; aesAlg.KeySize = 256; aesAlg.BlockSize = 128; aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Key = Key; aesAlg.IV = new byte[16];
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { plaintext = srDecrypt.ReadToEnd(); } } } } return plaintext; }
/// <summary>
/// Generate Random 4 digit Pin
/// </summary>
/// <returns></returns>
public static string GenerateRandomPin() { string[] strChar = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
string otpChar = strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)];
return otpChar; }
/// <summary>
/// Encrypt plain text to cipher text.
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string EncryptString(string plainText) { InitializeEncryptionParameters();
EncryptionParameters _encrypt = new EncryptionParameters() { PlainText = plainText, PassPhrase = _encryptionParams.PassPhrase, HashAlgorithm = _encryptionParams.HashAlgorithm, SaltValue = _encryptionParams.SaltValue, PasswordIterations = _encryptionParams.PasswordIterations, InitVector = _encryptionParams.InitVector, KeySize = _encryptionParams.KeySize };
var s = Utilities.Encrypt(_encrypt); return s; }
/// <summary>
/// Decrypt encrypted/cipher text to plain text.
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string DecryptString(string cipherText) { try { InitializeEncryptionParameters();
EncryptionParameters _decrypt = new EncryptionParameters() { CipherText = cipherText, PassPhrase = _encryptionParams.PassPhrase, HashAlgorithm = _encryptionParams.HashAlgorithm, SaltValue = _encryptionParams.SaltValue, PasswordIterations = _encryptionParams.PasswordIterations, InitVector = _encryptionParams.InitVector, KeySize = _encryptionParams.KeySize };
return Utilities.Decrypt(_decrypt); } catch (Exception ex) { return ""; } }
/// <summary>
/// Check for email validity
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
public static bool IsValidEmail(this string email) { return Regex.IsMatch(email ?? "", ApplicationConfig.ReadWebConfig("regex"), RegexOptions.IgnoreCase); }
/// <summary>
/// Check for residence card number
/// </summary>
/// <param name="residenceCardNo"></param>
/// <returns></returns>
public static bool IsValidNumber(this string residenceCardNo) { return Regex.IsMatch(residenceCardNo ?? "", ApplicationConfig.ReadWebConfig("regexResidenceCard"), RegexOptions.IgnoreCase); }
public static bool IsValidMobileNumber(this string mobile) { return Regex.IsMatch(mobile ?? "", ApplicationConfig.ReadWebConfig("regexMobile"), RegexOptions.IgnoreCase); }
public static bool IsValidDrivingNumber(this string drivingNo) { return Regex.IsMatch(drivingNo ?? "", ApplicationConfig.ReadWebConfig("regexDrivingLiscence"), RegexOptions.IgnoreCase); } public static bool IsCheckAdditionalId() { var additionalid = ApplicationConfig.ReadWebConfig("CheckAdditinalID");
if (additionalid != null && additionalid.Equals("Y")) return true; else return false; }
/// <summary>
/// Check for 4 digit pin number
/// </summary>
/// <param name="pin"></param>
/// <returns></returns>
public static bool IsValidPin(this string pin) { if (!string.IsNullOrEmpty(pin)) { int iPin;
if (pin.Length != 4) { return false; }
return int.TryParse(pin, out iPin); } else { return false; } }
/// <summary>
/// Check Wether the Mobile Number is Valid or not
/// </summary>
/// <param name="msisdn"></param>
/// <returns></returns>
public static bool IsValidMsisdn(this string msisdn) { int minPrefix = 2; int maxPrefix = 4; int chkFlag = 0; if (!string.IsNullOrEmpty(msisdn)) { long iMsisdn; var splitMsisdnLength = MsisdnLengthSetting.Split('|').ToList();
if (splitMsisdnLength.Contains(msisdn.Length.ToString())) { var splitPrefix = MsisdnPrefix.Split('|').ToList(); for (int i = minPrefix; i <= maxPrefix; i++) { if (splitPrefix.Contains(msisdn.Substring(0, i))) //checking prefix
{ chkFlag = 1; break; } else { continue; } } if (chkFlag == 0) { return false; } } else { return false; }
return long.TryParse(msisdn, out iMsisdn); } else { return false; } }
public static bool IsValidARCFormat(string idType, string vin) { if (idType == ApplicationConfig.ReadWebConfig("kycVerificationIdType") || idType == ApplicationConfig.ReadWebConfig("kycNationalIdType")) { var number = vin.Split('-'); if (number.Length != 2) { return false; } else if (number[0].Length != 6 || number[1].Length != 7) { return false; } else { return true; } } else { return true; } }
/// <summary>
/// Generate Random Password
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static string GenerateRandomPassword(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[Random.Next(s.Length)]).ToArray()); }
public static string GetTimestamp(DateTime value) { return value.ToString("yyyyMMddHHmmssffff"); }
/// <summary>
/// Used to send email
/// </summary>
/// <param name="emailParameters"></param>
/// <returns></returns>
public static JsonResponse SendEmail(SendEmailParameters emailParameters) { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(); try { SmtpServer.Host = ApplicationConfig.ReadWebConfig("smtp"); SmtpServer.Port = Convert.ToInt16(ApplicationConfig.ReadWebConfig("port")); SmtpServer.Credentials = new System.Net.NetworkCredential(ApplicationConfig.ReadWebConfig("mailFrom"), ApplicationConfig.ReadWebConfig("emailPwd")); SmtpServer.EnableSsl = Convert.ToBoolean(ApplicationConfig.ReadWebConfig("enableSSL"));
mail.From = new MailAddress(ApplicationConfig.ReadWebConfig("mailFrom"), ApplicationConfig.ReadWebConfig("mailSender")); mail.To.Add(emailParameters.ToEmails); if (!string.IsNullOrEmpty(emailParameters.CcEmails)) mail.CC.Add(emailParameters.CcEmails); if (!string.IsNullOrEmpty(emailParameters.BccEmails)) mail.Bcc.Add(emailParameters.BccEmails); mail.Subject = emailParameters.MsgSubject; mail.IsBodyHtml = true; mail.Body = emailParameters.MsgBody; SmtpServer.Send(mail);
response.SetResponseMessage(HttpStatusCode.OK, "Message sent successfully"); } catch (SmtpFailedRecipientsException ex) { for (int i = 0; i < ex.InnerExceptions.Length; i++) { SmtpStatusCode status = ex.InnerExceptions[i].StatusCode; if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable) { // Console.WriteLine("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000); SmtpServer.Send(mail); response.SetResponseMessage(HttpStatusCode.OK, "Message sent successfully"); } else { response.SetResponseMessage(HttpStatusCode.BadRequest, ex.InnerExceptions[i].FailedRecipient);
// Console.WriteLine("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient);
//throw ex;
//smtpMail.Status = "N";
//GetStatic.EmailNotificationLog(smtpMail);
} } } catch (Exception ex) { response.SetResponseMessage(HttpStatusCode.BadRequest, ex.Message); } return response; }
/// <summary>
/// To check the properties of a class for Null/Empty values
/// </summary>
/// <param name="obj">The instance of the class</param>
/// <returns>Result of the evaluation</returns>
public static bool IsAnyNullOrEmpty(object obj) { //Step 1: Set the count variable to check for the count of 2.
int count = 0; try { //Step 2: Check if the incoming object has values or not.
if (obj != null) { //Step 3: Iterate over the properties and check for null values based on the type.
foreach (PropertyInfo pi in obj.GetType().GetProperties()) { if (count >= 2) { return true; } dynamic value; if (pi.PropertyType == typeof(string)) { value = (string)pi.GetValue(obj); if (!string.IsNullOrEmpty(value)) { count++; } } else if (pi.PropertyType == typeof(int)) { value = (int)pi.GetValue(obj); if (value > 0) { count++; } } else if (pi.PropertyType == typeof(List<string>)) { value = (List<string>)pi.GetValue(obj); if (value != null) { if (value.Count > 0) { count++; } } } else if (pi.PropertyType == typeof(bool)) { value = pi.GetValue(obj); if (value != null) { count++; } } } //Step 4: Check if the count variable is >2 that means there is atleast one parameter passed in the body
if (count >= 2) { return true; } } } catch (Exception ex) { throw ex; } return false; }
public static string ConvertToUnixTimestamp(string str) { try { DateTime date = Convert.ToDateTime(str); DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); TimeSpan diff = date - origin; return Math.Floor(diff.TotalSeconds).ToString(); } catch (Exception) { return ""; } }
public static bool ConvertToGlobalFormat(string param) { try { if (string.IsNullOrEmpty(param)) { return true; }
DateTime dt; string[] formats = { "yyyy-MM-dd", "yyyy/MM/dd", "MM/dd/yyyy", "MM-dd-yyyy", "dd/MM/yyyy" }; if (DateTime.TryParseExact(param, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt)) { return true; } else { return false; } } catch (Exception ex) { return false; } }
public static String ShowDecimal(String strVal) { if (strVal != "") return String.Format("{0:0,0.00}", double.Parse(strVal)); else return strVal; }
public static bool IsSupportTypeValid(string str) { var lstSupportType = LoadSupportType(); return lstSupportType.Contains(str) ? true : false; }
private static List<string> LoadSupportType() { if (lstSupportType == null) { lstSupportType = new List<string>(); lstSupportType.Add("feedback"); lstSupportType.Add("enquiry"); } return lstSupportType; }
public static bool IsTransferTypeValid(string type) { var lstTransferType = LoadTransferType(); return lstTransferType.Contains(type) ? true : false; }
private static List<string> LoadTransferType() { if (lstTransferType == null) { lstTransferType = new List<string>(); lstTransferType.Add("offer"); lstTransferType.Add("request"); } return lstTransferType; }
public static bool IsActionTypeValid(string type) { var lstActionType = LoadActionType(); return lstActionType.Contains(type) ? true : false; }
private static List<string> LoadActionType() { if (lstActionType == null) { lstActionType = new List<string>(); lstActionType.Add("accept"); lstActionType.Add("reject"); } return lstActionType; }
//public static bool IsScheduleTypeValid(string type)
//{
// var lstScheduleType = LoadScheduleType();
// return lstScheduleType.Contains(type) ? true : false;
//}
//private static List<string> LoadScheduleType()
//{
// if (lstScheduleType == null)
// {
// lstScheduleType = new List<string>();
// lstScheduleType.Add("0");
// lstScheduleType.Add("1");
// }
// return lstScheduleType;
//}
public static int GetOriginalLengthInBytes(string base64string) { if (string.IsNullOrEmpty(base64string)) { return 0; }
var characterCount = base64string.Length; var paddingCount = base64string.Substring(characterCount - 2, 2) .Count(c => c == '='); return (3 * (characterCount / 4)) - paddingCount; }
public static string[] SelectDistinct(this string[] array) { return array.Distinct().ToArray(); }
public static string ReadWebConfig(string key, string defValue) { var Key = ConfigurationManager.AppSettings[key] ?? defValue; return Key; }
public static bool CheckDateType(string date) { DateTime dt; string[] formats = { "yyyy-MM-dd" }; if (!DateTime.TryParseExact(date, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { return false; } else { return true; } }
public static KYCConfigDto GetKYCSettings(KycRequest obj) { KYCConfigDto dt = new KYCConfigDto() { Config = new TrustDocConfig(), Options = new List<KYCOption>() }; KYCConfig referenceMaps = new KYCConfig();
//string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, obj.DeviceType.ToLower().Equals("android") ? "config\\KycConfig-uat.json" : ConfigurationManager.AppSettings["KycConfigFilePath"].ToString());
string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["KycConfigFilePath"].ToString()); using (StreamReader reader = File.OpenText(mappingPath)) { var jsonS = reader.ReadToEnd(); referenceMaps = Newtonsoft.Json.JsonConvert.DeserializeObject<KYCConfig>(jsonS); }
if (!string.IsNullOrEmpty(obj.DeviceType)) { dt.Config = referenceMaps.Config.Where(x => x.DeviceType.ToLower().Equals(obj.DeviceType.ToLower())).SingleOrDefault();
}
dt.Options = referenceMaps.Options;
return dt; }
public static List<Option> GetPaymetMethods() { List<Option> options = new List<Option>();
string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["PaymentConfigFilePath"].ToString()); using (StreamReader reader = File.OpenText(mappingPath)) { var jsonS = reader.ReadToEnd(); options = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Option>>(jsonS); }
return options; }
public static List<ReferenceMap> GetReferenceMaps() { List<ReferenceMap> referenceMaps = new List<ReferenceMap>();
string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["MappingFilePath"].ToString());
using (StreamReader reader = File.OpenText(mappingPath)) { var jsonS = reader.ReadToEnd(); referenceMaps = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model.Config.ReferenceMap>>(jsonS); }
return referenceMaps; }
public static List<ReferenceMap> GetReferenceMaps(MappingType type) { var lstReferences = GetReferenceMaps().Where(x => x.Type.Equals(type.ToString()));
return lstReferences.ToList(); }
public static Mapping GetMapping(MappingType type, string keyValue = "") { Mapping map = new Mapping(); try { if (string.IsNullOrEmpty(keyValue)) { return new Mapping(); }
var lstReferences = GetReferenceMaps().Where(x => x.Type.Equals(type.ToString())).SingleOrDefault();
map = lstReferences.Mappings.FirstOrDefault(x => (!String.IsNullOrEmpty(x.field) ? x.field.Trim().ToUpper() : "").Equals(keyValue.ToUpper().Trim()));
} catch (Exception e) { throw e; } return map != null ? map : new Mapping(); }
#region LANGUAGE MAPPING
public static List<LanguageMap> GetReferenceLangMaps() {
List<LanguageMap> referenceMaps = new List<LanguageMap>();
string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["LangFilePath"].ToString());
using (StreamReader reader = File.OpenText(mappingPath)) { var jsonS = reader.ReadToEnd(); referenceMaps = Newtonsoft.Json.JsonConvert.DeserializeObject<List<LanguageMap>>(jsonS); }
return referenceMaps; } #endregion
public static LanguageMap GetLanguageMapping(string keyValue, string lang = "en") { LanguageMap map = new LanguageMap(); try { if (string.IsNullOrEmpty(keyValue)) { return new LanguageMap(); }
if (lang.Equals("np")) { lang = "ne"; } else if (lang.Equals("bd")) { lang = "bn"; } else if (lang.Equals("vn")) { lang = "vi"; }
map = GetReferenceLangMaps().FirstOrDefault(x => x.Key.ToUpper().Equals(keyValue.ToUpper()) && (!String.IsNullOrEmpty(x.Lang) ? x.Lang.Trim().ToUpper() : "EN").Equals(lang.ToUpper().Trim()));
if (map != null && string.IsNullOrEmpty(map.Message)) { map = GetReferenceLangMaps().FirstOrDefault(x => x.Key.ToUpper().Equals(keyValue.ToUpper()) && x.Lang.Trim().ToUpper().Equals("EN")); } else if (map == null) { map = GetReferenceLangMaps().FirstOrDefault(x => x.Key.ToUpper().Equals(keyValue.ToUpper()) && x.Lang.Trim().ToUpper().Equals("EN")); } } catch (Exception e) { throw e; } return map != null ? map : new LanguageMap(); }
// Reflection
public static List<KeyValuePair> GetPropertiesNameOfClass(this object atype) { if (atype == null) return new List<KeyValuePair>(); Type t = atype.GetType(); PropertyInfo[] props = t.GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); List<KeyValuePair> dict = new List<KeyValuePair>(); foreach (PropertyInfo prp in props) { object propValue = prp.GetValue(atype, new object[] { });
dict.Add(new KeyValuePair { Key = prp.Name, Value = propValue != null ? propValue.ToString() : "" }); }
var bankId = GetPropertyValue(atype, "agent.id"); dict.Add(new KeyValuePair { Key = "agent.id", Value = bankId != null ? bankId.ToString() : "" });
var bankname = GetPropertyValue(atype, "agent.name"); dict.Add(new KeyValuePair { Key = "agent.name", Value = bankname != null ? bankname.ToString() : "" });
var branch = GetPropertyValue(atype, "agent.branch.id"); dict.Add(new KeyValuePair { Key = "agent.branch.id", Value = branch != null ? branch.ToString() : "" });
var accountno = GetPropertyValue(atype, "agent.accountNo"); dict.Add(new KeyValuePair { Key = "agent.accountNo", Value = accountno != null ? accountno.ToString() : "" }); return dict; }
public static object GetPropertyValue(object src, string propName) { if (src == null) return null; if (propName == null) throw new ArgumentException("Value cannot be null.", "propName");
if (propName.Contains("."))//complex type nested
{ var temp = propName.Split(new char[] { '.' }, 2); return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]); } else { var prop = src.GetType().GetProperty(propName); return prop != null ? prop.GetValue(src, null) : null; } }
public static string GetFullName(string fname, string mname, string lname) { string fullName = string.Empty; fullName = string.Format("{0} {1}", (!string.IsNullOrEmpty(mname)) ? fname + " " + mname : fname, lname); return fullName; }
public static string getUKFormattedNumber(this string number) { string finalNo = number; if (!number.Contains("+44")) { string mobileFirst = number.Substring(0, 1); if (mobileFirst == "0") { if (number.Length == 11) { finalNo = "+44" + number.Substring(1, number.Length - 1); return finalNo; } else if (number.Length < 11) { finalNo = $"+44{number}"; } } else if (number.Substring(0, 1) != "0" && number.Length == 10) { finalNo = $"+44{number}"; } } else if (number.Contains("+44")) { string MobN = number.Substring(4, 1); if (MobN == "0" && number.Length > 14) { finalNo = number.Remove(4, 1); } } if (!finalNo.Substring(0, 1).Contains("+")) {
finalNo = $"+{finalNo}"; } return finalNo; } } }
|