public void Can_set_and_get_object_from_cache() { var cacheManager = new MemoryCacheManager(); cacheManager.Set("key", 3, int.MaxValue); cacheManager.Get <int>("key").ShouldEqual(3); }
public virtual Dictionary <string, KeyValuePair <int, string> > GetAllResourceValues() { var cacheManager = new MemoryCacheManager(); var db = new DbEntities(); var key = string.Format(LOCALSTRINGRESOURCES_ALL_KEY); return(cacheManager.Get(key, () => { var query = from l in db.CodeMessage orderby l.Code select l; var locales = query.ToList(); var dictionary = new Dictionary <string, KeyValuePair <int, string> >(); foreach (var locale in locales) { var code = locale.Code.ToLowerInvariant(); if (!dictionary.ContainsKey(code)) { dictionary.Add(code, new KeyValuePair <int, string>(locale.CmId, locale.Message)); } } return dictionary; })); }
public void Test() { MemoryCacheManager cache = new MemoryCacheManager(); cache.Set("name", "123456"); Assert.AreEqual("123456", cache.Get <string>("name")); }
public ActionResult ClearCache() { var cacheManager = new MemoryCacheManager(); cacheManager.Clear(); return RedirectToAction("Index", "Home"); }
public void RemoveByPatternTest() { /* * In this test I provide: * 1. pattern that consists of "key100\d" which matchs to: key1009, but not to key1010 * 2. ICacheManager object with several keys * 3. List<string> with several keys */ ICacheManager icacheManager = new MemoryCacheManager(); icacheManager.Set("key1001", 33, int.MaxValue); icacheManager.Set("key1202", 1244, int.MaxValue); icacheManager.Set("key1003", 512, int.MaxValue); icacheManager.Set("key1204", 55, int.MaxValue); icacheManager.Set("key1005", 32, int.MaxValue); string pattern = @"key100\d"; //"key100" and one digit List <string> keys = new List <string>(); keys.Add("key1001"); keys.Add("key1202"); keys.Add("key1003"); keys.Add("key1204"); keys.Add("key1005"); icacheManager.RemoveByPattern(pattern, keys); Assert.IsNotNull(icacheManager.Get <int>("key1202")); Assert.IsNotNull(icacheManager.Get <int>("key1204")); }
public ActionResult GetErrorImage(string key) { var dir = Server.MapPath("/Content/Images"); var path = System.IO.Path.Combine(dir, MemoryCacheManager.GetAppSettings(key ?? "jamuro:DefaultErrorImage")); return(base.File(path, "image/jpeg")); }
/// <summary> /// /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <param name="db"></param> /// <param name="sql"></param> /// <param name="map"></param> /// <param name="parameters"></param> /// <param name="splitOn"></param> /// <param name="getFromCache"></param> /// <returns></returns> public static IEnumerable <T1> Get <T1, T2, T3, T4>(this CRMDb db, string sql, Func <T1, T2, T3, T4, T1> map, object parameters = null, string splitOn = "Id", bool getFromCache = false, TimeSpan cacheInterval = default(TimeSpan), CommandType commandType = CommandType.Text, int timeoutSeconds = 30) { try { var cache = new MemoryCacheManager(); var key = GetHashedKey(sql + parameters); if (getFromCache && cache.IsExists(key)) { return(cache.Get <IEnumerable <T1> >(key)); } var cs = getConnectionString(db); using (var _con = GetSqlConnection(cs)) { _con.Open(); var result = _con.Query <T1, T2, T3, T4, T1>(sql, map, parameters, splitOn: splitOn, commandType: commandType, commandTimeout: timeoutSeconds); return(AddToCache(key, result, cache, getFromCache, cacheInterval)); } } catch (Exception ex) { parameters = (parameters == null) ? new object() : parameters; ex.Data.Clear(); ex.Data.Add("parameters", new JavaScriptSerializer().Serialize(parameters)); ex.Data.Add("sql", sql); Logger.Current.Error("Error while querying using dapper", ex); throw ex; } }
public void TestInitialize() { var eventPublisher = new Mock <IMediator>(); var cacheManager = new MemoryCacheManager(new Mock <IMemoryCache>().Object, eventPublisher.Object); config = new ConfigFileSettingService(cacheManager, null, null); }
public static string Get(string key) { try { string info = string.Empty; string decodedInfo = string.Empty; SecurityAgentClient client = new SecurityAgentClient(); ICacheManager cacheManager = new MemoryCacheManager(); decodedInfo = cacheManager.Get <string>(key); if (string.IsNullOrWhiteSpace(decodedInfo)) { info = client.Get(key); decodedInfo = Crypto.Decode(Keys.EncryptionKey, info); cacheManager.Set(key, decodedInfo, 1080); } return(decodedInfo); } catch (Exception ex) { throw new Exception(string.Format("Error > \"{0}\" {1} Error Type > \"{2}\" {3} Method > \"Get(key, input)\"{4} Class > {5}", ex.Message, Environment.NewLine, ex.GetType().ToString(), Environment.NewLine, Environment.NewLine, typeof(SecurityClient)), ex); } }
private static void AddCache(this IServiceCollection services) { services.AddMemoryCache(); var databaseHelper = services.BuildServiceProvider() .GetService <IDatabaseHelper>(); services.AddStackExchangeRedisCache(options => { options.Configuration = databaseHelper.Redis; options.InstanceName = "NewHouse"; }); var serviceProvider = services.BuildServiceProvider(); var defaultCacheTime = TimeSpan.FromMinutes(30); var memoryCache = serviceProvider.GetService <IMemoryCache>(); var memoryCacheManager = new MemoryCacheManager(memoryCache, defaultCacheTime); services.AddSingleton <ICacheManager>(memoryCacheManager); var distributeCache = serviceProvider.GetService <IDistributedCache>(); var distributeCacheManager = new DistributeCacheManger(distributeCache, defaultCacheTime); services.AddSingleton <ICacheManager>(distributeCacheManager); services.AddSingleton <ICacheManagerProvider>(x => new CacheManagerProvider(memoryCacheManager, distributeCacheManager) ); }
public Application(IFileManager googleFileManager, IFileManager localFileManager, FileCacheManager fileCacheManager, MemoryCacheManager memoryCacheManager) { GoogleManager = googleFileManager; LocalManager = localFileManager; FileCacheManager = fileCacheManager; MemoryCacheManager = memoryCacheManager; }
/// <summary> /// 获取对象的属性对象 /// 本方法提供缓存功能, 提高性能 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="propertyName"></param> /// <returns></returns> public static PropertyInfo GetProperty <TEntity>(string propertyName) { MemoryCacheManager memoryCacheManager = new MemoryCacheManager(); Dictionary <string, PropertyInfo> propertyDictionary = null; string cachingKey = PropertyCollectionPreKey + typeof(TEntity).Name; if (!memoryCacheManager.IsSet(cachingKey)) { propertyDictionary = new Dictionary <string, PropertyInfo>(); Type type = typeof(TEntity); PropertyInfo[] propertyInfos = type.GetProperties(); foreach (PropertyInfo property in propertyInfos) { propertyDictionary.Add(property.Name, property); } memoryCacheManager.Set(cachingKey, propertyDictionary, 60); } propertyDictionary = memoryCacheManager.Get <Dictionary <string, PropertyInfo> >(cachingKey); if (propertyDictionary.ContainsKey(propertyName)) { return(propertyDictionary[propertyName]); } return(null); }
public void Can_set_and_get_object_from_cache() { var cacheManager = new MemoryCacheManager(); cacheManager.Set("some_key_1", 3, int.MaxValue); cacheManager.Get<int>("some_key_1").ShouldEqual(3); }
protected override void Load(ContainerBuilder builder) { // NOTE: Do not register entire settings in container, pass necessary settings to services which requires them // ex: // builder.RegisterType<QuotesPublisher>() // .As<IQuotesPublisher>() // .WithParameter(TypedParameter.From(_settings.Rabbit.ConnectionString)) builder.RegisterInstance(_settings) .SingleInstance(); builder.RegisterInstance(_log) .As <ILog>() .SingleInstance(); builder.RegisterType <HealthService>() .As <IHealthService>() .SingleInstance(); builder.RegisterType <StartupManager>() .As <IStartupManager>(); builder.RegisterType <ShutdownManager>() .As <IShutdownManager>(); var cacheManager = new MemoryCacheManager(); builder.RegisterInstance(cacheManager).As <ICacheManager>(); RegisterAzureRepositories(builder); }
public static IEnumerable <dynamic> Get(this CRMDb db, string sql, object parameters = null, bool getFromCache = false, TimeSpan cacheInterval = default(TimeSpan)) { try { var cache = new MemoryCacheManager(); var key = GetHashedKey(sql + parameters); if (getFromCache && cache.IsExists(key)) { return(cache.Get <IEnumerable <dynamic> >(key)); } var cs = getConnectionString(db); using (var _con = GetSqlConnection(cs)) { _con.Open(); var result = _con.Query(sql, parameters); return(AddToCache(key, result, cache, getFromCache, cacheInterval)); } } catch (Exception ex) { parameters = (parameters == null) ? new object() : parameters; ex.Data.Clear(); ex.Data.Add("parameters", new JavaScriptSerializer().Serialize(parameters)); ex.Data.Add("sql", sql); Logger.Current.Error("Error while querying using dapper", ex); throw ex; } }
public PeopleController(ApplicationDbContext context, DbSetCachingService <Person> cachingService, MemoryCacheManager cacheManager, ISimple simple) { _context = context; _dbCs = cachingService; _cacheManager = cacheManager; _simple = simple; }
public async Task Invoke(HttpContext context) { RequestResponseLog _logInfo = new RequestResponseLog(); var token = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", ""); var users = MemoryCacheManager.GetCache <UserDto>(token); HttpRequest request = context.Request; _logInfo.Url = request.Path.ToString(); IDictionary <string, string> Headers = request.Headers.ToDictionary(k => k.Key, v => string.Join(";", v.Value.ToList())); _logInfo.Headers = $"[" + string.Join(",", Headers.Select(i => "{" + $"\"{i.Key}\":\"{i.Value}\"" + "}")) + "]"; _logInfo.Method = request.Method; _logInfo.ExcuteStartTime = DateTime.Now; _logInfo.UserName = users?.UserName; _logInfo.IPAddress = request.HttpContext.Connection.RemoteIpAddress.ToString(); _logInfo.Port = request.HttpContext.Connection.RemotePort; //获取request.Body内容 if (request.Method.ToLower().Equals("post")) { request.EnableRewind(); //启用倒带功能,就可以让 Request.Body 可以再次读取 Stream stream = request.Body; byte[] buffer = new byte[request.ContentLength.Value]; stream.Read(buffer, 0, buffer.Length); _logInfo.RequestBody = Encoding.UTF8.GetString(buffer); request.Body.Position = 0; } else if (request.Method.ToLower().Equals("get")) { _logInfo.RequestBody = request.QueryString.Value; } using (var responseBody = new MemoryStream()) { //获取Response.Body内容 var originalBodyStream = context.Response.Body; context.Response.Body = responseBody; await _next(context); _logInfo.ResponseBody = await FormatResponse(context.Response); //Log4Net.LogInfo($"VisitLog: {_logInfo.ToString()}"); await responseBody.CopyToAsync(originalBodyStream); } context.Response.OnCompleted(async o => { _logInfo.ExcuteEndTime = DateTime.Now; _appSystemServices.Create <RequestResponseLog>(_logInfo); }, context); }
//获取js_api_ticket public static string GetJsApiTicket() { string ticket; ICacheManager cache = new MemoryCacheManager(); var contains = cache.Contains("js_api_ticket"); if (contains) { ticket = cache.GetCache <string>("js_api_ticket"); } else { var httpGet = HttpHelper.HttpGet(GetTicketUrl(), ""); var jsApiTicketModel = JsonConvert.DeserializeObject <JsApiTicketModel>(httpGet); if (jsApiTicketModel.errcode == 0) { ticket = jsApiTicketModel.ticket; long expiresIn = jsApiTicketModel.expires_in; cache.SetCache("js_api_ticket", ticket, TimeSpan.FromSeconds(expiresIn - 60)); } else { ticket = null; } } // var httpGet = HttpHelper.HttpGet(GetTicketUrl(), ""); // var jsApiTicketModel = JsonConvert.DeserializeObject<JsApiTicketModel>(httpGet); // ticket = jsApiTicketModel.errcode == 0 ? jsApiTicketModel.ticket : null; return(ticket); }
public override void OnInvoke(MethodInterceptionArgs args) { //cache manager türetiliyor var cacheManager = new MemoryCacheManager(); //metod ismi alınıyor var methodName = string.Format("{0}.{1}.{2}", args.Method.ReflectedType.Namespace, args.Method.ReflectedType.Name, args.Method.Name); //metod parametreleri alınıyor var arguments = args.Arguments.ToList(); //cache key oluşturuluyor {MetodAdı.Parametreler} var key = string.Format("{0}({1})", methodName, string.Join(",", arguments.Select(x => x != null ? x.ToString() : "<Null>"))); //metod cache de var ise oradan çağrılıyor if (cacheManager.IsAdd(key)) { args.ReturnValue = cacheManager.Get <object>(key); return; } //metod çalıştırılıyor base.OnInvoke(args); //metod cache ekleniyor cacheManager.Add(key, args.ReturnValue, _dakika); }
public static void Main(string[] args) { Console.OutputEncoding = Encoding.Unicode; try { Console.WriteLine("========== START =========="); var container = new Initializer().RegisterComponents(); var localManager = new LocalFileManager(); var googleManager = new GoogleFileManager(container.Resolve <IGoogleDriveService>()); // TODO: both cache managers should be singletons. I'm a bit worried about possible issues with race conditions when reading/writing, but I don't think this is something serious here var fileCacheManager = new FileCacheManager("filecache.txt"); var memoryCacheManager = new MemoryCacheManager(); var app = new Application(googleManager, localManager, fileCacheManager, memoryCacheManager); app.Start(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } }
public void Can_lock_cache() { var cacheManager = new MemoryCacheManager(new MemoryCache(new MemoryCacheOptions())); var key = ".Task"; var expiration = TimeSpan.FromMinutes(2); var actionCount = 0; var action = new Action(() => { cacheManager.IsSet(key).ShouldBeTrue(); cacheManager.PerformActionWithLock(key, expiration, () => Assert.Fail("Action in progress")).ShouldBeFalse(); if (++actionCount % 2 == 0) { throw new ApplicationException("Alternating actions fail"); } }); cacheManager.PerformActionWithLock(key, expiration, action).ShouldBeTrue(); actionCount.ShouldEqual(1); Assert.Throws <ApplicationException>(() => cacheManager.PerformActionWithLock(key, expiration, action)); actionCount.ShouldEqual(2); cacheManager.PerformActionWithLock(key, expiration, action).ShouldBeTrue(); actionCount.ShouldEqual(3); }
private Mock <IServiceProvider> GetServiceProvider(string testname) { var serviceProvider = new Mock <IServiceProvider>(); serviceProvider .Setup(x => x.GetService(typeof(IdentityService))) .Returns(new IdentityService() { Token = "Token", Username = "******" }); serviceProvider .Setup(x => x.GetService(typeof(IHttpClientService))) .Returns(new HttpClientTestService()); serviceProvider .Setup(x => x.GetService(typeof(InternalPurchaseOrderFacade))) .Returns(new InternalPurchaseOrderFacade(serviceProvider.Object, _dbContext(testname))); var services = new ServiceCollection(); services.AddMemoryCache(); var serviceProviders = services.BuildServiceProvider(); var memoryCache = serviceProviders.GetService <IMemoryCache>(); //var memoryCacheService = serviceProviders.GetService<IMemoryCacheManager>(); //memoryCacheService.Set(MemoryCacheConstant.Categories, new List<CategoryCOAResult>() { new CategoryCOAResult() { _id = 1 } }); var opts = Options.Create(new MemoryDistributedCacheOptions()); var cache = new MemoryDistributedCache(opts); serviceProvider .Setup(x => x.GetService(typeof(IDistributedCache))) .Returns(cache); var memoryCacheManager = new MemoryCacheManager(memoryCache); memoryCacheManager.Set(MemoryCacheConstant.Categories, new List <CategoryCOAResult>() { new CategoryCOAResult() { Id = 1 } }); serviceProvider .Setup(x => x.GetService(typeof(IMemoryCacheManager))) .Returns(memoryCacheManager); var mockCurrencyProvider = new Mock <ICurrencyProvider>(); mockCurrencyProvider .Setup(x => x.GetCurrencyByCurrencyCode(It.IsAny <string>())) .ReturnsAsync((Currency)null); serviceProvider .Setup(x => x.GetService(typeof(ICurrencyProvider))) .Returns(mockCurrencyProvider.Object); return(serviceProvider); }
public ActionResult ClearCache() { var cacheManager = new MemoryCacheManager(); cacheManager.Clear(); return(RedirectToAction("Index", "Home")); }
private UserDto GetUsers() { var token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", ""); var users = MemoryCacheManager.GetCache <UserDto>(token); return(users); }
public void Can_get_set_object_from_cache() { var cacheManager = new MemoryCacheManager(new MemoryCache(new MemoryCacheOptions())); cacheManager.Set("key_1", 1, int.MaxValue); cacheManager.Get("key_1", () => 0).ShouldEqual(1); }
public void MemoryCacheManager_Should_Not_Throw_Exception_When_Trying_To_Remove_A_Non_Excisting_Key() { ICacheManager cacheManager = new MemoryCacheManager(); cacheManager.Remove("Test"); Assert.IsFalse(cacheManager.Contains("Test")); }
public void Can_set_and_get_object_from_cache() { var cacheManager = new MemoryCacheManager(new MemoryCache(new MemoryCacheOptions())); cacheManager.Set("some_key_1", 3, int.MaxValue); Assert.True(cacheManager.Get <int>("some_key_1") == 3); }
public void Setup() { _cacheManager = new MemoryCacheManager(new DefaultInMemoryCachingProvider("nopCommerce.tests", new List <IInMemoryCaching> { new InMemoryCaching("nopCommerce.tests", new InMemoryCachingOptions()) }, new InMemoryOptions())); }
public void MemoryCacheManager_Should_Return_Null_When_Key_Not_Available() { ICacheManager cacheManager = new MemoryCacheManager(); string value = cacheManager.Get <string>("Test"); Assert.IsNull(value); }
public ResponseDto <String> Logout() { MemoryCacheManager.Remove(this.Token); return(new ResponseDto <string>() { Code = CommonEnum.ToLoginCode }); }
public override void OnSuccess(MethodExecutionArgs args) { var cacheManager = new MemoryCacheManager(); cacheManager.RemoveByPattern(string.IsNullOrEmpty(_pattern) ? string.Format("{0}.{1}.*", args.Method.ReflectedType.Namespace, args.Method.ReflectedType.Name) : _pattern); }
public void TestInitialize() { var cacheManager = new MemoryCacheManager(new Mock <IMemoryCache>().Object); config = new ConfigFileSettingService(new List <ICacheManager> { cacheManager }, null, null, null); }
public void Can_clear_cache() { var cacheManager = new MemoryCacheManager(); cacheManager.Set("some_key_1", 3, int.MaxValue); cacheManager.Clear(); cacheManager.IsSet("some_key_1").ShouldEqual(false); }
public void Can_validate_whetherobject_is_cached() { var cacheManager = new MemoryCacheManager(); cacheManager.Set("some_key_1", 3, int.MaxValue); cacheManager.Set("some_key_2", 4, int.MaxValue); cacheManager.IsSet("some_key_1").ShouldEqual(true); cacheManager.IsSet("some_key_3").ShouldEqual(false); }
public void MemoryCacheManager测试() { string key = "Memory_TEST_KEY"; string memoryValue = "Memory测试"; ICacheManager cache = new MemoryCacheManager(); cache.Set(key, memoryValue, 60); string value= cache.Get<string>(key); Assert.AreEqual(value, memoryValue); cache.Remove(key); }
public ActionResult ClearCache() { var cacheManager = new MemoryCacheManager(); cacheManager.Clear(); // set this in the activity log activityService.InsertActivity(SystemActivityLogTypeNames.ClearCache, string.Empty, string.Empty); SuccessNotification("Application cache has been cleared."); return RedirectToRoute(SystemRouteNames.HomePage); }
public static List<EntityMenuModel> GetMenus() { List<EntityMenuModel> menus = null; if (Authentication.CurrentEntity != null) { string key = string.Format(ENTITYMENUKEY, Authentication.CurrentEntity.EntityID); ICacheManager cacheManager = new MemoryCacheManager(); menus = cacheManager.Get(key, () => { IAdminRepository adminRepository = new AdminRepository(); return adminRepository.GetAllEntityMenus(); }); } else { menus = new List<EntityMenuModel>(); } return menus; }
public ActionResult ImportInvestorBankExcel(FormCollection collection) { ImportInvestorBankExcelModel model = new ImportInvestorBankExcelModel(); ResultModel resultModel = new ResultModel(); MemoryCacheManager cacheManager = new MemoryCacheManager(); int totalPages = 0; int totalRows = 0; int completedRows = 0; int? succssRows = 0; int? errorRows = 0; this.TryUpdateModel(model); if (ModelState.IsValid) { string key = string.Format(EXCELINVESTORBANKERROR_BY_KEY, model.SessionKey); List<DeepBlue.Models.Deal.ImportExcelError> errors = cacheManager.Get(key, () => { return new List<DeepBlue.Models.Deal.ImportExcelError>(); }); DataSet ds = ExcelConnection.ImportExcelDataset(model.SessionKey); if (ds != null) { PagingDataTable importExcelTable = null; if (ds.Tables[model.InvestorBankTableName] != null) { importExcelTable = (PagingDataTable)ds.Tables[model.InvestorBankTableName]; } if (importExcelTable != null) { importExcelTable.PageSize = model.PageSize; PagingDataTable table = importExcelTable.Skip(model.PageIndex); totalPages = importExcelTable.TotalPages; totalRows = importExcelTable.TotalRows; if (totalPages > model.PageIndex) { completedRows = (model.PageIndex * importExcelTable.PageSize); } else { completedRows = totalRows; } int rowNumber = 0; string investorName = string.Empty; string bankName = string.Empty; int abaNumber = 0; string accountName = string.Empty; string accountNumber = string.Empty; string ffcName = string.Empty; string ffcNumber = string.Empty; string reference = string.Empty; string swift = string.Empty; string iban = string.Empty; string phone = string.Empty; string fax = string.Empty; DeepBlue.Models.Deal.ImportExcelError error; EmailAttribute emailValidation = new EmailAttribute(); ZipAttribute zipAttribute = new ZipAttribute(); WebAddressAttribute webAttribute = new WebAddressAttribute(); IEnumerable<ErrorInfo> errorInfo; StringBuilder rowErrors; foreach (DataRow row in table.Rows) { int.TryParse(row.GetValue("RowNumber"), out rowNumber); error = new DeepBlue.Models.Deal.ImportExcelError { RowNumber = rowNumber }; rowErrors = new StringBuilder(); investorName = row.GetValue(model.InvestorName); bankName = row.GetValue(model.BankName); int.TryParse(row.GetValue(model.ABANumber), out abaNumber); accountName = row.GetValue(model.AccountName); accountNumber = row.GetValue(model.AccountNumber); ffcName = row.GetValue(model.FFCName); ffcNumber = row.GetValue(model.FFCNumber); reference = row.GetValue(model.Reference); swift = row.GetValue(model.Swift); iban = row.GetValue(model.IBAN); phone = row.GetValue(model.Phone); fax = row.GetValue(model.Fax); DeepBlue.Models.Entity.Investor investor = InvestorRepository.FindInvestor(investorName); if (investor == null) { error.Errors.Add(new ErrorInfo(model.InvestorName, "Investor does not exist")); } else { // Attempt to create new investor account. InvestorAccount investorAccount = InvestorRepository.FindInvestorAccount( investor.InvestorID, bankName, abaNumber, accountName, accountNumber, ffcName, ffcNumber, reference, swift, iban, phone, fax ); if (investorAccount == null) { investorAccount = new InvestorAccount(); investorAccount.CreatedBy = Authentication.CurrentUser.UserID; investorAccount.CreatedDate = DateTime.Now; } else { error.Errors.Add(new ErrorInfo(model.InvestorName, "Investor Bank Account Information already exist")); } if (error.Errors.Count() == 0) { investorAccount.Comments = string.Empty; investorAccount.EntityID = Authentication.CurrentEntity.EntityID; investorAccount.IsPrimary = false; investorAccount.LastUpdatedBy = Authentication.CurrentUser.UserID; investorAccount.LastUpdatedDate = DateTime.Now; investorAccount.Routing = abaNumber; investorAccount.Reference = reference; investorAccount.FFC = ffcName; investorAccount.FFCNumber = ffcNumber; investorAccount.IBAN = iban; investorAccount.SWIFT = swift; investorAccount.Account = accountName; investorAccount.AccountNumberCash = accountNumber; investorAccount.BankName = bankName; investorAccount.Phone = phone; investorAccount.Fax = fax; investorAccount.InvestorID = investor.InvestorID; if (error.Errors.Count() == 0) { errorInfo = InvestorRepository.SaveInvestorAccount(investorAccount); if (errorInfo != null) { error.Errors.Add(new ErrorInfo(model.InvestorName, ValidationHelper.GetErrorInfo(errorInfo))); } } } } StringBuilder sberror = new StringBuilder(); foreach (var e in error.Errors) { sberror.AppendFormat("{0},", e.ErrorMessage); } importExcelTable.AddError(rowNumber - 1, sberror.ToString()); errors.Add(error); } } } if (errors != null) { succssRows = errors.Where(e => e.Errors.Count == 0).Count(); errorRows = errors.Where(e => e.Errors.Count > 0).Count(); } } else { foreach (var values in ModelState.Values.ToList()) { foreach (var err in values.Errors.ToList()) { if (string.IsNullOrEmpty(err.ErrorMessage) == false) { resultModel.Result += err.ErrorMessage + "\n"; } } } } return Json(new { Result = resultModel.Result, TotalRows = totalRows, CompletedRows = completedRows, TotalPages = totalPages, PageIndex = model.PageIndex, SuccessRows = succssRows, ErrorRows = errorRows }); }
public ActionResult ImportCapitalDistributionExcel(FormCollection collection) { ImportManualCapitalDistributionExcelModel model=new ImportManualCapitalDistributionExcelModel(); ResultModel resultModel=new ResultModel(); MemoryCacheManager cacheManager=new MemoryCacheManager(); int totalPages=0; int totalRows=0; int completedRows=0; int? succssRows=0; int? errorRows=0; this.TryUpdateModel(model); if(ModelState.IsValid) { string key=string.Format(EXCELCAPITALCALLERROR_BY_KEY,model.SessionKey); List<DeepBlue.Models.Deal.ImportExcelError> errors=cacheManager.Get(key,() => { return new List<DeepBlue.Models.Deal.ImportExcelError>(); }); DataSet ds=ExcelConnection.ImportExcelDataset(model.SessionKey); if(ds!=null) { PagingDataTable importExcelTable=null; if(ds.Tables[model.ManualCapitalDistributionTableName]!=null) { importExcelTable=(PagingDataTable)ds.Tables[model.ManualCapitalDistributionTableName]; } if(importExcelTable!=null) { importExcelTable.PageSize=model.PageSize; PagingDataTable table=importExcelTable.Skip(model.PageIndex); totalPages=importExcelTable.TotalPages; totalRows=importExcelTable.TotalRows; if(totalPages>model.PageIndex) { completedRows=(model.PageIndex*importExcelTable.PageSize); } else { completedRows=totalRows; } int rowNumber=0; string investorName=string.Empty; string fundName=string.Empty; decimal capitalDistributionAmount=0; decimal returnManagementFees=0; decimal returnFundExpenses=0; decimal costReturned=0; decimal profits=0; decimal profitsReturned=0; DateTime distributionDate; DateTime distributionDueDate; DeepBlue.Models.Deal.ImportExcelError error; DeepBlue.Models.Entity.Investor investor; DeepBlue.Models.Entity.Fund fund; DeepBlue.Models.Entity.InvestorFund investorFund; EmailAttribute emailValidation=new EmailAttribute(); ZipAttribute zipAttribute=new ZipAttribute(); WebAddressAttribute webAttribute=new WebAddressAttribute(); IEnumerable<ErrorInfo> errorInfo; StringBuilder rowErrors; foreach(DataRow row in table.Rows) { int.TryParse(row.GetValue("RowNumber"),out rowNumber); error=new DeepBlue.Models.Deal.ImportExcelError { RowNumber=rowNumber }; rowErrors=new StringBuilder(); investorName=row.GetValue(model.InvestorName); fundName=row.GetValue(model.FundName); decimal.TryParse(row.GetValue(model.CapitalDistributionAmount),out capitalDistributionAmount); decimal.TryParse(row.GetValue(model.ReturnManagementFees),out returnManagementFees); decimal.TryParse(row.GetValue(model.ReturnFundExpenses),out returnFundExpenses); decimal.TryParse(row.GetValue(model.CostReturned),out costReturned); decimal.TryParse(row.GetValue(model.Profits),out profits); decimal.TryParse(row.GetValue(model.ProfitsReturned),out profitsReturned); DateTime.TryParse(row.GetValue(model.DistributionDate),out distributionDate); DateTime.TryParse(row.GetValue(model.DistributionDueDate),out distributionDueDate); investor=null; fund=null; investorFund=null; if(string.IsNullOrEmpty(investorName)==false) { investor=InvestorRepository.FindInvestor(investorName); } else { error.Errors.Add(new ErrorInfo(model.InvestorName,"Investor is required")); } if(string.IsNullOrEmpty(fundName)==false) { fund=FundRepository.FindFund(fundName); } else { error.Errors.Add(new ErrorInfo(model.InvestorName,"Fund is required")); } if(investor!=null&&fund!=null) { investorFund=InvestorRepository.FindInvestorFund(investor.InvestorID,fund.FundID); } if(error.Errors.Count()==0) { if(investorFund==null) { error.Errors.Add(new ErrorInfo(model.InvestorName,"Investror Commitment does not exist")); } } if(error.Errors.Count()==0) { Models.Entity.CapitalDistribution distribution=CapitalCallRepository.FindCapitalDistribution( (fund!=null?fund.FundID:0), distributionDate, distributionDueDate, true); if(distribution==null) { distribution=new Models.Entity.CapitalDistribution(); distribution.CreatedBy=Authentication.CurrentUser.UserID; distribution.CreatedDate=DateTime.Now; } distribution.CapitalDistributionDate=distributionDate; distribution.CapitalDistributionDueDate=distributionDueDate; distribution.PreferredReturn=(distribution.PreferredReturn??0)+profitsReturned; distribution.ReturnManagementFees=(distribution.ReturnManagementFees??0)+returnManagementFees; distribution.ReturnFundExpenses=(distribution.ReturnFundExpenses??0)+returnFundExpenses; distribution.Profits=(distribution.Profits??0)+profits; distribution.DistributionAmount=distribution.DistributionAmount+capitalDistributionAmount; distribution.LastUpdatedBy=Authentication.CurrentUser.UserID; distribution.LastUpdatedDate=DateTime.Now; distribution.DistributionNumber=Convert.ToString(CapitalCallRepository.FindCapitalCallDistributionNumber((fund!=null?fund.FundID:0))); distribution.FundID=(fund!=null?fund.FundID:0); distribution.CapitalReturn=(distribution.CapitalReturn??0)+costReturned; distribution.IsManual=true; if(error.Errors.Count()==0) { errorInfo=CapitalCallRepository.SaveCapitalDistribution(distribution); if(errorInfo!=null) { error.Errors.Add(new ErrorInfo(model.InvestorName,ValidationHelper.GetErrorInfo(errorInfo))); } } if(error.Errors.Count()==0) { CapitalDistributionLineItem item=CapitalCallRepository.FindCapitalDistributionLineItem(distribution.CapitalDistributionID,investor.InvestorID); if(item==null) { item=new CapitalDistributionLineItem(); item.CreatedBy=Authentication.CurrentUser.UserID; item.CreatedDate=DateTime.Now; } item.CapitalReturn=0; item.CreatedBy=Authentication.CurrentUser.UserID; item.CreatedDate=DateTime.Now; item.LastUpdatedBy=Authentication.CurrentUser.UserID; item.LastUpdatedDate=DateTime.Now; item.InvestorID=(investor!=null?investor.InvestorID:0); item.DistributionAmount=capitalDistributionAmount; item.ReturnManagementFees=returnManagementFees; item.ReturnFundExpenses=returnFundExpenses; item.Profits=profits; item.PreferredReturn=profitsReturned; item.CapitalReturn=costReturned; item.CapitalDistributionID=distribution.CapitalDistributionID; errorInfo=CapitalCallRepository.SaveCapitalDistributionLineItem(item); if(errorInfo!=null) { error.Errors.Add(new ErrorInfo(model.InvestorName,ValidationHelper.GetErrorInfo(errorInfo))); } } } StringBuilder sberror=new StringBuilder(); foreach(var e in error.Errors) { sberror.AppendFormat("{0},",e.ErrorMessage); } importExcelTable.AddError(rowNumber-1,sberror.ToString()); errors.Add(error); } } } if(errors!=null) { succssRows=errors.Where(e => e.Errors.Count==0).Count(); errorRows=errors.Where(e => e.Errors.Count>0).Count(); } } else { foreach(var values in ModelState.Values.ToList()) { foreach(var err in values.Errors.ToList()) { if(string.IsNullOrEmpty(err.ErrorMessage)==false) { resultModel.Result+=err.ErrorMessage+"\n"; } } } } return Json(new { Result=resultModel.Result, TotalRows=totalRows, CompletedRows=completedRows, TotalPages=totalPages, PageIndex=model.PageIndex, SuccessRows=succssRows, ErrorRows=errorRows }); }
private void RemoveWidgetZoneFromCache(string widgetZoneName) { var cacheManager = new MemoryCacheManager(); var cacheKey = string.Format(ModelCacheEventConsumer.WIDGET_MODEL_KEY, _storeContext.CurrentStore.Id, widgetZoneName); cacheManager.Remove(cacheKey); }
public static DataSet GetDataSet(string path, string fileName, ref string errorMessage, ref string sessionKey) { ICacheManager cacheManager = new MemoryCacheManager(); DataSet ds = new DataSet(); PagingDataTable dt = null; try { string inputFileName = System.IO.Path.Combine(path, fileName); using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(inputFileName, false)) { //Access the main Workbook part, which contains data WorkbookPart workbookPart = myWorkbook.WorkbookPart; WorksheetPart worksheetPart = null; List<Sheet> sheets = workbookPart.Workbook.Descendants<Sheet>().ToList(); foreach (var ss in sheets) { dt = new PagingDataTable(); dt.TableName = ss.Name; worksheetPart = (WorksheetPart)workbookPart.GetPartById(ss.Id); SharedStringTablePart stringTablePart = workbookPart.SharedStringTablePart; if (worksheetPart != null) { string relationshipId = sheets.First().Id.Value; Worksheet workSheet = worksheetPart.Worksheet; SheetData sheetData = workSheet.GetFirstChild<SheetData>(); IEnumerable<Row> rows = sheetData.Descendants<Row>(); if (rows.ToArray().Count() > 0) { foreach (Cell cell in rows.ElementAt(0)) { dt.Columns.Add(GetCellValue(myWorkbook, cell)); } int rowIndex = 0; foreach (Row row in rows) //this will also include your header row... { if (rowIndex > 0) { DataRow tempRow = dt.NewRow(); int columnIndex = 0; foreach (Cell cell in row.Descendants<Cell>()) { // Gets the column index of the cell with data int cellColumnIndex = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference)); cellColumnIndex--; //zero based index if (columnIndex < cellColumnIndex) { do { try { tempRow[columnIndex] = ""; //Insert blank data here; } catch { } columnIndex++; } while (columnIndex < cellColumnIndex); } try { tempRow[columnIndex] = GetCellValue(myWorkbook, cell); } catch { } columnIndex++; } bool isAllColumnBlank = true; foreach (DataColumn col in dt.Columns) { if (string.IsNullOrEmpty(Convert.ToString(tempRow[col.ColumnName])) == false) { isAllColumnBlank = false; break; } } if (isAllColumnBlank == false) { dt.Rows.Add(tempRow); } } rowIndex++; } dt.Columns.Add(new DataColumn { DataType = typeof(int), //AutoIncrement = true, //AutoIncrementSeed = 1, //AutoIncrementStep = 1, ColumnName = "RowNumber", //AllowDBNull = false, }); dt.Columns.Add(new DataColumn { ColumnName = "ImportError", }); rowIndex = 1; foreach (DataRow row in dt.Rows) { row["RowNumber"] = rowIndex; rowIndex++; } ds.Tables.Add(dt); } } } } Guid guid = System.Guid.NewGuid(); sessionKey = string.Format(EXCELDATABASE_BY_KEY, guid); cacheManager.Set(sessionKey, ds, 120); } catch (Exception ex) { errorMessage = ex.Message.ToString(); } finally { UploadFileHelper.DeleteFile("TempPath", fileName); } return ds; }
public static DataSet ImportExcelDataset(string key) { ICacheManager cacheManager = new MemoryCacheManager(); return cacheManager.Get<DataSet>(key); }
public ActionResult ClearCache() { if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenance)) return AccessDeniedView(); var cacheManager = new MemoryCacheManager(); cacheManager.Clear(); return RedirectToAction("Index", "Home"); }
public ActionResult UpdateEntityMenuSortOrder(FormCollection collection) { ICacheManager cacheManager=new MemoryCacheManager(); ResultModel resultModel=new ResultModel(); int entityMenuID=0; int alterEntityMenuID=0; int.TryParse(collection["entityMenuID"],out entityMenuID); int.TryParse(collection["alterEntityMenuID"],out alterEntityMenuID); EntityMenu entityMenu=AdminRepository.FindEntityMenu(entityMenuID); EntityMenu alterEntityMenu=AdminRepository.FindEntityMenu(alterEntityMenuID); IEnumerable<ErrorInfo> errorInfo=null; if(entityMenu!=null&&alterEntityMenu!=null) { int entityMenuSortOrder=entityMenu.SortOrder; int alterEntityMenuSortOrder=alterEntityMenu.SortOrder; entityMenu.SortOrder=alterEntityMenuSortOrder; alterEntityMenu.SortOrder=entityMenuSortOrder; AdminRepository.SaveEntityMenu(entityMenu); AdminRepository.SaveEntityMenu(alterEntityMenu); } if(errorInfo!=null) { resultModel.Result+=ValidationHelper.GetErrorInfo(errorInfo); } else { // Remove entity menu cache cacheManager.RemoveByPattern(string.Format(MenuHelper.ENTITYMENUKEY,entityMenu.EntityID)); resultModel.Result="True||"+entityMenu.EntityMenuID; } return View("Result",resultModel); }
public ActionResult UpdateEntityMenu(FormCollection collection) { ICacheManager cacheManager=new MemoryCacheManager(); EditEntityMenuModel model=new EditEntityMenuModel(); ResultModel resultModel=new ResultModel(); this.TryUpdateModel(model); //string ErrorMessage = EntityMenuAvailable(model.DisplayName, model.EntityMenuID); //if (String.IsNullOrEmpty(ErrorMessage) == false) { // ModelState.AddModelError("DisplayName", ErrorMessage); //} if(ModelState.IsValid) { EntityMenu entityMenu=AdminRepository.FindEntityMenu(model.EntityMenuID); if(entityMenu==null) { entityMenu=new EntityMenu(); } entityMenu.DisplayName=model.DisplayName; entityMenu.MenuID=model.MenuID; entityMenu.EntityID=Authentication.CurrentEntity.EntityID; IEnumerable<ErrorInfo> errorInfo=AdminRepository.SaveEntityMenu(entityMenu); if(errorInfo!=null) { resultModel.Result+=ValidationHelper.GetErrorInfo(errorInfo); } else { // Remove entity menu cache cacheManager.RemoveByPattern(string.Format(MenuHelper.ENTITYMENUKEY,entityMenu.EntityID)); resultModel.Result="True||"+entityMenu.EntityMenuID; } } else { foreach(var values in ModelState.Values.ToList()) { foreach(var err in values.Errors.ToList()) { if(string.IsNullOrEmpty(err.ErrorMessage)==false) { resultModel.Result+=err.ErrorMessage+"\n"; } } } } return View("Result",resultModel); }
public string DeleteMenu(int id) { if(AdminRepository.DeleteMenu(id)==false) { return "Cann't Delete! Child record found!"; } else { // Remove entity menu cache ICacheManager cacheManager=new MemoryCacheManager(); cacheManager.RemoveByPattern(MenuHelper.ENTITYMENUKEY); return string.Empty; } }
public ActionResult UpdateEntity(FormCollection collection) { ICacheManager cacheManager=new MemoryCacheManager(); ENTITY model=new ENTITY(); ResultModel resultModel=new ResultModel(); this.TryUpdateModel(model); bool isNewEntity=false; string ErrorMessage=EntityNameAvailable(model.EntityName,model.EntityID); if(String.IsNullOrEmpty(ErrorMessage)==false) { ModelState.AddModelError("EntityName",ErrorMessage); } ErrorMessage=EntityCodeAvailable(model.EntityCode,model.EntityID); if(String.IsNullOrEmpty(ErrorMessage)==false) { ModelState.AddModelError("EntityCode",ErrorMessage); } if(ModelState.IsValid) { ENTITY entity=AdminRepository.FindEntity(model.EntityID); if(entity==null) { entity=new ENTITY(); entity.CreatedDate=DateTime.Now; isNewEntity=true; } entity.EntityName=model.EntityName; entity.EntityCode=model.EntityCode; entity.Enabled=model.Enabled; IEnumerable<ErrorInfo> errorInfo=AdminRepository.SaveEntity(entity); if(errorInfo!=null) { resultModel.Result+=ValidationHelper.GetErrorInfo(errorInfo); } else { resultModel.Result="True||"+entity.EntityID; // Create default user if(isNewEntity) { string username="******"; string password="******"; string firstname="admin"; string lastname="admin"; string email="*****@*****.**"; USER user=new USER(); user.Login=username; user.PasswordSalt=SecurityExtensions.CreateSalt(); user.PasswordHash=password.CreateHash(user.PasswordSalt); user.Email=email; user.FirstName=firstname; user.LastName=lastname; user.EntityID=entity.EntityID; user.CreatedDate=DateTime.Now; user.LastUpdatedDate=DateTime.Now; user.Enabled=true; user.IsAdmin=true; AdminRepository.SaveUser(user); } } // Create entity menu if(AdminRepository.GetEntityMenuCount(entity.EntityID)<=0) { AdminRepository.SaveEntityMenu(entity.EntityID); // Remove entity menu cache cacheManager.RemoveByPattern(string.Format(MenuHelper.ENTITYMENUKEY,entity.EntityID)); } } else { foreach(var values in ModelState.Values.ToList()) { foreach(var err in values.Errors.ToList()) { if(string.IsNullOrEmpty(err.ErrorMessage)==false) { resultModel.Result+=err.ErrorMessage+"\n"; } } } } return View("Result",resultModel); }
public ActionResult UpdateMenu(FormCollection collection) { ICacheManager cacheManager=new MemoryCacheManager(); EditMenuModel model=new EditMenuModel(); ResultModel resultModel=new ResultModel(); this.TryUpdateModel(model); if(ModelState.IsValid) { Menu menu=AdminRepository.FindMenu(model.MenuID); if(menu==null) { menu=new Menu(); } menu.DisplayName=model.DisplayName; menu.ParentMenuID=model.ParentMenuID; menu.URL=model.URL; menu.Title=model.Title; IEnumerable<ErrorInfo> errorInfo=AdminRepository.SaveMenu(menu); if(errorInfo!=null) { resultModel.Result+=ValidationHelper.GetErrorInfo(errorInfo); } else { // Remove entity menu cache cacheManager.RemoveByPattern(MenuHelper.ENTITYMENUKEY); resultModel.Result="True||"+menu.MenuID; } } else { foreach(var values in ModelState.Values.ToList()) { foreach(var err in values.Errors.ToList()) { if(string.IsNullOrEmpty(err.ErrorMessage)==false) { resultModel.Result+=err.ErrorMessage+"\n"; } } } } return View("Result",resultModel); }
public ActionResult ImportInvestorExcel(FormCollection collection) { ImportInvestorExcelModel model = new ImportInvestorExcelModel(); ResultModel resultModel = new ResultModel(); MemoryCacheManager cacheManager = new MemoryCacheManager(); int totalPages = 0; int totalRows = 0; int completedRows = 0; int? succssRows = 0; int? errorRows = 0; this.TryUpdateModel(model); if (ModelState.IsValid) { string key = string.Format(EXCELINVESTORERROR_BY_KEY, model.SessionKey); List<DeepBlue.Models.Deal.ImportExcelError> errors = cacheManager.Get(key, () => { return new List<DeepBlue.Models.Deal.ImportExcelError>(); }); DataSet ds = ExcelConnection.ImportExcelDataset(model.SessionKey); if (ds != null) { PagingDataTable importExcelTable = null; if (ds.Tables[model.InvestorTableName] != null) { importExcelTable = (PagingDataTable)ds.Tables[model.InvestorTableName]; } if (importExcelTable != null) { importExcelTable.PageSize = model.PageSize; PagingDataTable table = importExcelTable.Skip(model.PageIndex); totalPages = importExcelTable.TotalPages; totalRows = importExcelTable.TotalRows; if (totalPages > model.PageIndex) { completedRows = (model.PageIndex * importExcelTable.PageSize); } else { completedRows = totalRows; } int rowNumber = 0; string investorName = string.Empty; string displayName = string.Empty; string socialSecurityID = string.Empty; bool domesticForeign = false; string stateOfResidencyName = string.Empty; string entityType = string.Empty; string source = string.Empty; bool foia = false; bool erisa = false; string notes = string.Empty; string phone = string.Empty; string fax = string.Empty; string email = string.Empty; string webAddress = string.Empty; string address1 = string.Empty; string address2 = string.Empty; string city = string.Empty; string stateName = string.Empty; string zip = string.Empty; string countryName = string.Empty; Models.Entity.InvestorEntityType investorEntityType; Models.Entity.STATE stateOfResidency; Models.Entity.COUNTRY country; Models.Entity.STATE state; DeepBlue.Models.Deal.ImportExcelError error; EmailAttribute emailValidation = new EmailAttribute(); ZipAttribute zipAttribute = new ZipAttribute(); WebAddressAttribute webAttribute = new WebAddressAttribute(); IEnumerable<ErrorInfo> errorInfo; StringBuilder rowErrors; foreach (DataRow row in table.Rows) { int.TryParse(row.GetValue("RowNumber"), out rowNumber); error = new DeepBlue.Models.Deal.ImportExcelError { RowNumber = rowNumber }; rowErrors = new StringBuilder(); investorName = row.GetValue(model.InvestorName); displayName = row.GetValue(model.DisplayName); socialSecurityID = row.GetValue(model.SocialSecurityID); domesticForeign = row.GetValue(model.DomesticForeign).ToLower() == "domestic"; stateOfResidencyName = row.GetValue(model.StateOfResidency); entityType = row.GetValue(model.EntityType); source = row.GetValue(model.Source); bool.TryParse(row.GetValue(model.FOIA), out foia); bool.TryParse(row.GetValue(model.ERISA), out erisa); phone = row.GetValue(model.Phone); fax = row.GetValue(model.Fax); email = row.GetValue(model.Email); webAddress = row.GetValue(model.WebAddress); address1 = row.GetValue(model.Address1); address2 = row.GetValue(model.Address2); city = row.GetValue(model.City); stateName = row.GetValue(model.State); zip = row.GetValue(model.Zip); countryName = row.GetValue(model.Country); investorEntityType = null; stateOfResidency = null; state = null; country = null; DeepBlue.Models.Entity.Investor investor = InvestorRepository.FindInvestor(investorName); if (investor != null) { error.Errors.Add(new ErrorInfo(model.InvestorName, "Investor already exist")); } else { investor = new Models.Entity.Investor(); if (string.IsNullOrEmpty(entityType) == false) { investorEntityType = AdminRepository.FindInvestorEntityType(entityType); } if (string.IsNullOrEmpty(stateOfResidencyName) == false) { stateOfResidency = AdminRepository.FindState(stateOfResidencyName); } if (string.IsNullOrEmpty(countryName) == false) { country = AdminRepository.FindCountry(countryName); } if (string.IsNullOrEmpty(stateName) == false) { state = AdminRepository.FindState(stateName); } investor.Alias = displayName; investor.IsDomestic = domesticForeign; investor.InvestorEntityTypeID = (investorEntityType != null ? investorEntityType.InvestorEntityTypeID : 0); investor.InvestorName = investorName; investor.FirstName = displayName; investor.ResidencyState = (stateOfResidency != null ? stateOfResidency.StateID : 0); investor.Social = socialSecurityID; investor.Notes = notes; investor.TaxID = 0; investor.FirstName = string.Empty; investor.LastName = "n/a"; investor.ManagerName = string.Empty; investor.MiddleName = string.Empty; investor.PrevInvestorID = 0; investor.CreatedBy = Authentication.CurrentUser.UserID; investor.CreatedDate = DateTime.Now; investor.LastUpdatedBy = Authentication.CurrentUser.UserID; investor.LastUpdatedDate = DateTime.Now; investor.EntityID = Authentication.CurrentEntity.EntityID; investor.TaxExempt = false; investor.Source = source; investor.ERISA = erisa; investor.FOIA = foia; // Attempt to create new investor address. InvestorAddress investorAddress = new InvestorAddress(); investorAddress.CreatedBy = Authentication.CurrentUser.UserID; investorAddress.CreatedDate = DateTime.Now; investorAddress.EntityID = Authentication.CurrentEntity.EntityID; investorAddress.LastUpdatedBy = Authentication.CurrentUser.UserID; investorAddress.LastUpdatedDate = DateTime.Now; investorAddress.Address = new Address(); investorAddress.Address.Address1 = address1; investorAddress.Address.Address2 = address2; investorAddress.Address.AddressTypeID = (int)DeepBlue.Models.Admin.Enums.AddressType.Work; investorAddress.Address.City = city; investorAddress.Address.Country = (country != null ? country.CountryID : 0); investorAddress.Address.CreatedBy = Authentication.CurrentUser.UserID; investorAddress.Address.CreatedDate = DateTime.Now; investorAddress.Address.LastUpdatedBy = Authentication.CurrentUser.UserID; investorAddress.Address.LastUpdatedDate = DateTime.Now; investorAddress.Address.EntityID = Authentication.CurrentEntity.EntityID; investorAddress.Address.PostalCode = zip; investorAddress.Address.State = (state != null ? state.StateID : 0); if (string.IsNullOrEmpty(investorAddress.Address.Address1) == false || string.IsNullOrEmpty(investorAddress.Address.Address2) == false || string.IsNullOrEmpty(investorAddress.Address.City) == false || string.IsNullOrEmpty(investorAddress.Address.PostalCode) == false || string.IsNullOrEmpty(investorAddress.Address.County) == false || string.IsNullOrEmpty(phone) == false || string.IsNullOrEmpty(email) == false || string.IsNullOrEmpty(webAddress) == false || string.IsNullOrEmpty(fax) == false ) { errorInfo = ValidationHelper.Validate(investorAddress.Address); if (errorInfo.Any()) { error.Errors.Add(new ErrorInfo(model.Address1, ValidationHelper.GetErrorInfo(errorInfo))); } if (emailValidation.IsValid(email) == false) error.Errors.Add(new ErrorInfo(model.Email, "Invalid Email")); if (zipAttribute.IsValid(zip) == false) error.Errors.Add(new ErrorInfo(model.Email, "Invalid Zip")); if (webAttribute.IsValid(webAddress) == false) error.Errors.Add(new ErrorInfo(model.Email, "Invalid Web Address")); if (error.Errors.Count() == 0) { /* Add New Investor Address */ investor.InvestorAddresses.Add(investorAddress); /* Investor Communication Values */ AddCommunication(investor, Models.Admin.Enums.CommunicationType.HomePhone, phone); AddCommunication(investor, Models.Admin.Enums.CommunicationType.Email, email); AddCommunication(investor, Models.Admin.Enums.CommunicationType.WebAddress, webAddress); AddCommunication(investor, Models.Admin.Enums.CommunicationType.Fax, fax); } } if (error.Errors.Count() == 0) { errorInfo = InvestorRepository.SaveInvestor(investor); if (errorInfo != null) { error.Errors.Add(new ErrorInfo(model.InvestorName, ValidationHelper.GetErrorInfo(errorInfo))); } } } StringBuilder sberror = new StringBuilder(); foreach (var e in error.Errors) { sberror.AppendFormat("{0},", e.ErrorMessage); } importExcelTable.AddError(rowNumber - 1, sberror.ToString()); errors.Add(error); } } } if (errors != null) { succssRows = errors.Where(e => e.Errors.Count == 0).Count(); errorRows = errors.Where(e => e.Errors.Count > 0).Count(); } } else { foreach (var values in ModelState.Values.ToList()) { foreach (var err in values.Errors.ToList()) { if (string.IsNullOrEmpty(err.ErrorMessage) == false) { resultModel.Result += err.ErrorMessage + "\n"; } } } } return Json(new { Result = resultModel.Result, TotalRows = totalRows, CompletedRows = completedRows, TotalPages = totalPages, PageIndex = model.PageIndex, SuccessRows = succssRows, ErrorRows = errorRows }); }
public ActionResult GetImportErrorExcel(string sessionKey, string tableName) { MemoryCacheManager cacheManager = new MemoryCacheManager(); ActionResult result = null; DataSet ds = ExcelConnection.ImportExcelDataset(sessionKey); if (ds != null) { PagingDataTable importExcelTable = null; if (ds.Tables[tableName] != null) { importExcelTable = (PagingDataTable)ds.Tables[tableName]; } PagingDataTable errorTable = (PagingDataTable)importExcelTable.Clone(); DataRow[] rows = importExcelTable.Select("ImportError<>''"); foreach (var row in rows) { errorTable.ImportRow(row); } //if (importExcelTable != null) { result = new ExportExcel { TableName = string.Format("{0}_{1}", tableName, sessionKey), GridData = errorTable }; //} } return result; }
public static void InsertData(DataSet dataSet) { if (dataSet == null) throw new ArgumentNullException("DataSet param is null"); try { //ConcurrentDictionary<string, object> cache = new ConcurrentDictionary<string, object>(); ICacheManager cache = new MemoryCacheManager(); var exceptions = new ConcurrentQueue<Exception>(); List<Task> tasks = new List<Task>(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); using (var container = new ModelsContainer()) { foreach (DataTable dt in dataSet.Tables) { //Task task = Task.Factory.StartNew(() => //{ try { Console.WriteLine("----------Table name is : {0}---------", dt.TableName); int cursor = 0; foreach (DataRow dr in dt.Rows) { Record record = new Record(); string brandsName = dr[0].ToString(); var brands = cache.Get<Brands>(brandsName, () => { return new Brands() { Name = brandsName }; }); record.Brands = brands; string modelsName = dr[1].ToString(); var models = cache.Get<Models>(modelsName, () => { return new Models() { Name = modelsName }; }); record.Models = models; record.City = dr[2].ToString(); string dv = dr[3].ToString().Replace(".", ""); string d = string.Format("{0}-{1}-01", dv.Substring(0, 4), dv.Substring(4, 2)).Trim(); var buyYear = cache.Get<BuyYear>(d, () => { return new BuyYear() { Time = Convert.ToDateTime(d) }; }); record.BuyYear = buyYear; d = string.Format("{0}-01-01", dr[4].ToString()); record.Both = DateTime.Parse(d); bool g = dr[5].ToString().Equals("男") ? true : false; record.Gender = Convert.ToBoolean(g); record.Address = dr[6].ToString(); record.Zip = dr[7].ToString(); container.Set<Record>().Add(record); Console.WriteLine("address {0}, cursor = {1}, threadId = {2}", record.Address, cursor, Thread.CurrentThread.ManagedThreadId); cursor++; if (cursor == 100) { cursor = 0; container.SaveChanges(); } } } catch (Exception ex) { exceptions.Enqueue(ex); } //}); //tasks.Add(task); container.SaveChanges(); } } //Task.WaitAll(tasks.ToArray()); stopwatch.Stop(); TimeSpan ts = stopwatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime " + elapsedTime); if (exceptions.Any()) { Console.WriteLine("Parallel have exceptions, count = {0}", exceptions.Count()); } } catch (Exception ex) { string msg = ex.OutputMessage(); Console.WriteLine("{0}", msg); } }
public ActionResult ImportInvestorContactExcel(FormCollection collection) { ImportInvestorContactExcelModel model = new ImportInvestorContactExcelModel(); ResultModel resultModel = new ResultModel(); MemoryCacheManager cacheManager = new MemoryCacheManager(); int totalPages = 0; int totalRows = 0; int completedRows = 0; int? succssRows = 0; int? errorRows = 0; this.TryUpdateModel(model); if (ModelState.IsValid) { string key = string.Format(EXCELINVESTORCONTACTERROR_BY_KEY, model.SessionKey); List<DeepBlue.Models.Deal.ImportExcelError> errors = cacheManager.Get(key, () => { return new List<DeepBlue.Models.Deal.ImportExcelError>(); }); DataSet ds = ExcelConnection.ImportExcelDataset(model.SessionKey); if (ds != null) { PagingDataTable importExcelTable = null; if (ds.Tables[model.InvestorContactTableName] != null) { importExcelTable = (PagingDataTable)ds.Tables[model.InvestorContactTableName]; } if (importExcelTable != null) { importExcelTable.PageSize = model.PageSize; PagingDataTable table = importExcelTable.Skip(model.PageIndex); totalPages = importExcelTable.TotalPages; totalRows = importExcelTable.TotalRows; if (totalPages > model.PageIndex) { completedRows = (model.PageIndex * importExcelTable.PageSize); } else { completedRows = totalRows; } int rowNumber = 0; string investorName = string.Empty; string contactPerson = string.Empty; string designation = string.Empty; string telephone = string.Empty; string fax = string.Empty; string email = string.Empty; string webAddress = string.Empty; string address = string.Empty; string city = string.Empty; string stateName = string.Empty; string zip = string.Empty; string countryName = string.Empty; bool receivesDistributionCapitalCallNotices = false; bool financials = false; bool k1 = false; bool investorLetters = false; COUNTRY country = null; STATE state = null; DeepBlue.Models.Deal.ImportExcelError error; DeepBlue.Models.Entity.Investor investor; EmailAttribute emailValidation = new EmailAttribute(); ZipAttribute zipAttribute = new ZipAttribute(); WebAddressAttribute webAttribute = new WebAddressAttribute(); IEnumerable<ErrorInfo> errorInfo; StringBuilder rowErrors; foreach (DataRow row in table.Rows) { int.TryParse(row.GetValue("RowNumber"), out rowNumber); error = new DeepBlue.Models.Deal.ImportExcelError { RowNumber = rowNumber }; rowErrors = new StringBuilder(); investorName = row.GetValue(model.InvestorName); contactPerson = row.GetValue(model.ContactPerson); designation = row.GetValue(model.Designation); telephone = row.GetValue(model.Telephone); fax = row.GetValue(model.Fax); email = row.GetValue(model.Email); webAddress = row.GetValue(model.WebAddress); address = row.GetValue(model.Address); city = row.GetValue(model.City); stateName = row.GetValue(model.State); zip = row.GetValue(model.Zip); countryName = row.GetValue(model.Country); bool.TryParse(row.GetValue(model.ReceivesDistributionCapitalCallNotices), out receivesDistributionCapitalCallNotices); bool.TryParse(row.GetValue(model.Financials), out financials); bool.TryParse(row.GetValue(model.InvestorLetters), out investorLetters); bool.TryParse(row.GetValue(model.K1), out k1); investor = null; country = null; state = null; if (string.IsNullOrEmpty(investorName) == false) { investor = InvestorRepository.FindInvestor(investorName); } if (investor == null) { error.Errors.Add(new ErrorInfo(model.InvestorName, "Investor does not exist")); } else { if (string.IsNullOrEmpty(countryName) == false) { country = AdminRepository.FindCountry(countryName); } if (string.IsNullOrEmpty(stateName) == false) { state = AdminRepository.FindState(stateName); } // Attempt to create new investor contact. InvestorContact investorContact = InvestorRepository.FindInvestorContact(investor.InvestorID, contactPerson, designation, receivesDistributionCapitalCallNotices, financials, k1, investorLetters ); if (investorContact == null) { investorContact = new InvestorContact(); investorContact.CreatedBy = Authentication.CurrentUser.UserID; investorContact.CreatedDate = DateTime.Now; } else { error.Errors.Add(new ErrorInfo(model.InvestorName, "Investor contact already exist")); } if (error.Errors.Count() == 0) { investorContact.InvestorID = investor.InvestorID; investorContact.EntityID = Authentication.CurrentEntity.EntityID; investorContact.LastUpdatedBy = Authentication.CurrentUser.UserID; investorContact.LastUpdatedDate = DateTime.Now; investorContact.Contact = new Contact(); investorContact.Contact.CreatedBy = Authentication.CurrentUser.UserID; investorContact.Contact.CreatedDate = DateTime.Now; investorContact.Contact.ContactName = contactPerson; investorContact.Contact.FirstName = "n/a"; investorContact.Contact.LastName = "n/a"; investorContact.Contact.LastUpdatedBy = Authentication.CurrentUser.UserID; investorContact.Contact.LastUpdatedDate = DateTime.Now; investorContact.Contact.ReceivesDistributionNotices = receivesDistributionCapitalCallNotices; investorContact.Contact.ReceivesFinancials = financials; investorContact.Contact.ReceivesInvestorLetters = investorLetters; investorContact.Contact.ReceivesK1 = k1; investorContact.Contact.Designation = designation; investorContact.Contact.EntityID = Authentication.CurrentEntity.EntityID; // Attempt to create new investor contact address. ContactAddress contactAddress = null; contactAddress = new ContactAddress(); contactAddress.CreatedBy = Authentication.CurrentUser.UserID; contactAddress.CreatedDate = DateTime.Now; contactAddress.EntityID = Authentication.CurrentEntity.EntityID; contactAddress.LastUpdatedBy = Authentication.CurrentUser.UserID; contactAddress.LastUpdatedDate = DateTime.Now; contactAddress.Address = new Address(); contactAddress.Address.CreatedBy = Authentication.CurrentUser.UserID; contactAddress.Address.CreatedDate = DateTime.Now; contactAddress.Address.Address1 = address; contactAddress.Address.AddressTypeID = (int)DeepBlue.Models.Admin.Enums.AddressType.Work; contactAddress.Address.City = city; contactAddress.Address.Country = (country != null ? country.CountryID : 0); contactAddress.Address.EntityID = Authentication.CurrentEntity.EntityID; contactAddress.Address.LastUpdatedBy = Authentication.CurrentUser.UserID; contactAddress.Address.LastUpdatedDate = DateTime.Now; contactAddress.Address.PostalCode = zip; contactAddress.Address.State = (state != null ? state.StateID : 0); /* Add Investor Contact Communication Values */ if (string.IsNullOrEmpty(contactAddress.Address.Address1) == false || string.IsNullOrEmpty(contactAddress.Address.Address2) == false || string.IsNullOrEmpty(contactAddress.Address.City) == false || string.IsNullOrEmpty(contactAddress.Address.PostalCode) == false || string.IsNullOrEmpty(investorContact.Contact.ContactName) == false || string.IsNullOrEmpty(fax) == false || string.IsNullOrEmpty(email) == false || string.IsNullOrEmpty(webAddress) == false ) { errorInfo = ValidationHelper.Validate(contactAddress.Address); errorInfo = errorInfo.Union(ValidationHelper.Validate(investorContact.Contact)); if (errorInfo.Any()) { error.Errors.Add(new ErrorInfo(model.InvestorName, ValidationHelper.GetErrorInfo(errorInfo))); } if (emailValidation.IsValid(email) == false) error.Errors.Add(new ErrorInfo(model.Email, "Invalid Email")); if (webAttribute.IsValid(webAddress) == false) error.Errors.Add(new ErrorInfo(model.WebAddress, "Invalid Web Address")); if (zipAttribute.IsValid(contactAddress.Address.PostalCode) == false) error.Errors.Add(new ErrorInfo(model.Zip, "Invalid Zip")); if (error.Errors.Count() == 0) { investorContact.Contact.ContactAddresses.Add(contactAddress); AddCommunication(investorContact.Contact, Models.Admin.Enums.CommunicationType.HomePhone, telephone); AddCommunication(investorContact.Contact, Models.Admin.Enums.CommunicationType.Fax, fax); AddCommunication(investorContact.Contact, Models.Admin.Enums.CommunicationType.Email, email); AddCommunication(investorContact.Contact, Models.Admin.Enums.CommunicationType.WebAddress, webAddress); } } if (error.Errors.Count() == 0) { errorInfo = InvestorRepository.SaveInvestorContact(investorContact); if (errorInfo != null) { error.Errors.Add(new ErrorInfo(model.InvestorName, ValidationHelper.GetErrorInfo(errorInfo))); } } } } StringBuilder sberror = new StringBuilder(); foreach (var e in error.Errors) { sberror.AppendFormat("{0},", e.ErrorMessage); } importExcelTable.AddError(rowNumber - 1, sberror.ToString()); errors.Add(error); } } } if (errors != null) { succssRows = errors.Where(e => e.Errors.Count == 0).Count(); errorRows = errors.Where(e => e.Errors.Count > 0).Count(); } } else { foreach (var values in ModelState.Values.ToList()) { foreach (var err in values.Errors.ToList()) { if (string.IsNullOrEmpty(err.ErrorMessage) == false) { resultModel.Result += err.ErrorMessage + "\n"; } } } } return Json(new { Result = resultModel.Result, TotalRows = totalRows, CompletedRows = completedRows, TotalPages = totalPages, PageIndex = model.PageIndex, SuccessRows = succssRows, ErrorRows = errorRows }); }
public ActionResult ClearCache(string returnUrl = "") { if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenance)) return AccessDeniedView(); var cacheManager = new MemoryCacheManager(); cacheManager.Clear(); //home page if (String.IsNullOrEmpty(returnUrl)) return RedirectToAction("Index", "Home", new { area = "Admin" }); //prevent open redirection attack if (!Url.IsLocalUrl(returnUrl)) return RedirectToAction("Index", "Home", new { area = "Admin" }); return Redirect(returnUrl); }
/// <summary> /// Executes a task /// </summary> public void Execute() { var cacheManager = new MemoryCacheManager(); cacheManager.Clear(); }
public ActionResult ImportCapitalCallExcel(FormCollection collection) { ImportManualCapitalCallExcelModel model=new ImportManualCapitalCallExcelModel(); ResultModel resultModel=new ResultModel(); MemoryCacheManager cacheManager=new MemoryCacheManager(); int totalPages=0; int totalRows=0; int completedRows=0; int? succssRows=0; int? errorRows=0; this.TryUpdateModel(model); if(ModelState.IsValid) { string key=string.Format(EXCELCAPITALCALLERROR_BY_KEY,model.SessionKey); List<DeepBlue.Models.Deal.ImportExcelError> errors=cacheManager.Get(key,() => { return new List<DeepBlue.Models.Deal.ImportExcelError>(); }); DataSet ds=ExcelConnection.ImportExcelDataset(model.SessionKey); if(ds!=null) { PagingDataTable importExcelTable=null; if(ds.Tables[model.ManualCapitalCallTableName]!=null) { importExcelTable=(PagingDataTable)ds.Tables[model.ManualCapitalCallTableName]; } if(importExcelTable!=null) { importExcelTable.PageSize=model.PageSize; PagingDataTable table=importExcelTable.Skip(model.PageIndex); totalPages=importExcelTable.TotalPages; totalRows=importExcelTable.TotalRows; if(totalPages>model.PageIndex) { completedRows=(model.PageIndex*importExcelTable.PageSize); } else { completedRows=totalRows; } int rowNumber=0; string investorName=string.Empty; string fundName=string.Empty; decimal capitalCallAmount=0; decimal managementFeesInterest=0; decimal investedAmountInterest=0; decimal managementFees=0; decimal fundExpenses=0; DateTime capitalCallDate; DateTime capitalCallDueDate; DeepBlue.Models.Deal.ImportExcelError error; DeepBlue.Models.Entity.Investor investor; DeepBlue.Models.Entity.Fund fund; DeepBlue.Models.Entity.InvestorFund investorFund; EmailAttribute emailValidation=new EmailAttribute(); ZipAttribute zipAttribute=new ZipAttribute(); WebAddressAttribute webAttribute=new WebAddressAttribute(); IEnumerable<ErrorInfo> errorInfo; StringBuilder rowErrors; foreach(DataRow row in table.Rows) { int.TryParse(row.GetValue("RowNumber"),out rowNumber); error=new DeepBlue.Models.Deal.ImportExcelError { RowNumber=rowNumber }; rowErrors=new StringBuilder(); investorName=row.GetValue(model.InvestorName); fundName=row.GetValue(model.FundName); decimal.TryParse(row.GetValue(model.CapitalCallAmount),out capitalCallAmount); decimal.TryParse(row.GetValue(model.ManagementFeesInterest),out managementFeesInterest); decimal.TryParse(row.GetValue(model.InvestedAmountInterest),out investedAmountInterest); decimal.TryParse(row.GetValue(model.ManagementFees),out managementFees); decimal.TryParse(row.GetValue(model.FundExpenses),out fundExpenses); DateTime.TryParse(row.GetValue(model.CapitalCallDate),out capitalCallDate); DateTime.TryParse(row.GetValue(model.CapitalCallDueDate),out capitalCallDueDate); investor=null; fund=null; investorFund=null; if(string.IsNullOrEmpty(investorName)==false) { investor=InvestorRepository.FindInvestor(investorName); } else { error.Errors.Add(new ErrorInfo(model.InvestorName,"Investor is required")); } if(string.IsNullOrEmpty(fundName)==false) { fund=FundRepository.FindFund(fundName); } else { error.Errors.Add(new ErrorInfo(model.InvestorName,"Fund is required")); } if(investor!=null&&fund!=null) { investorFund=InvestorRepository.FindInvestorFund(investor.InvestorID,fund.FundID); } if(error.Errors.Count()==0) { if(investorFund==null) { error.Errors.Add(new ErrorInfo(model.InvestorName,"Investror Commitment does not exist")); } } if(error.Errors.Count()==0) { Models.Entity.CapitalCall capitalCall=CapitalCallRepository.FindCapitalCall( (fund!=null?fund.FundID:0), capitalCallDate, capitalCallDueDate, (int)Models.CapitalCall.Enums.CapitalCallType.Manual); if(capitalCall==null) { capitalCall=new Models.Entity.CapitalCall(); capitalCall.CreatedBy=Authentication.CurrentUser.UserID; capitalCall.CreatedDate=DateTime.Now; } capitalCall.CapitalCallDate=capitalCallDate; capitalCall.CapitalCallDueDate=capitalCallDueDate; capitalCall.CapitalCallTypeID=(int)Models.CapitalCall.Enums.CapitalCallType.Manual; capitalCall.LastUpdatedBy=Authentication.CurrentUser.UserID; capitalCall.LastUpdatedDate=DateTime.Now; capitalCall.FundID=(fund!=null?fund.FundID:0); capitalCall.InvestedAmountInterest=0; capitalCall.CapitalAmountCalled+=capitalCallAmount; capitalCall.InvestedAmountInterest=(capitalCall.ExistingInvestmentAmount??0)+investedAmountInterest; capitalCall.FundExpenses=(capitalCall.FundExpenses??0)+fundExpenses; capitalCall.ManagementFees=(capitalCall.ManagementFees??0)+managementFees; capitalCall.ManagementFeeInterest=(capitalCall.ManagementFeeInterest??0)+managementFeesInterest; capitalCall.CapitalCallNumber=Convert.ToString(CapitalCallRepository.FindCapitalCallNumber((fund!=null?fund.FundID:0))); if(error.Errors.Count()==0) { errorInfo=CapitalCallRepository.SaveCapitalCall(capitalCall); if(errorInfo!=null) { error.Errors.Add(new ErrorInfo(model.InvestorName,ValidationHelper.GetErrorInfo(errorInfo))); } } if(error.Errors.Count()==0) { bool isNewItem=false; CapitalCallLineItem item=CapitalCallRepository.FindCapitalCallLineItem(capitalCall.CapitalCallID,investor.InvestorID); if(item==null) { item=new CapitalCallLineItem(); item.CreatedBy=Authentication.CurrentUser.UserID; item.CreatedDate=DateTime.Now; isNewItem=true; } item.LastUpdatedBy=Authentication.CurrentUser.UserID; item.LastUpdatedDate=DateTime.Now; item.CapitalAmountCalled=capitalCallAmount; item.ManagementFeeInterest=managementFeesInterest; item.InvestedAmountInterest=investedAmountInterest; item.ManagementFees=managementFees; item.FundExpenses=fundExpenses; item.InvestorID=investor.InvestorID; item.CapitalCallID=capitalCall.CapitalCallID; errorInfo=CapitalCallRepository.SaveCapitalCallLineItem(item); if(errorInfo!=null) { error.Errors.Add(new ErrorInfo(model.InvestorName,ValidationHelper.GetErrorInfo(errorInfo))); } else { if(isNewItem) { if(item.InvestorID>0) { if(investorFund!=null) { // Reduce investor unfunded amount = investor unfunded amount – capital call amount for investor. investorFund.UnfundedAmount=investorFund.UnfundedAmount-item.CapitalAmountCalled; errorInfo=InvestorRepository.SaveInvestorFund(investorFund); if(errorInfo!=null) { error.Errors.Add(new ErrorInfo(model.InvestorName,ValidationHelper.GetErrorInfo(errorInfo))); } } } } } } } StringBuilder sberror=new StringBuilder(); foreach(var e in error.Errors) { sberror.AppendFormat("{0},",e.ErrorMessage); } importExcelTable.AddError(rowNumber-1,sberror.ToString()); errors.Add(error); } } } if(errors!=null) { succssRows=errors.Where(e => e.Errors.Count==0).Count(); errorRows=errors.Where(e => e.Errors.Count>0).Count(); } } else { foreach(var values in ModelState.Values.ToList()) { foreach(var err in values.Errors.ToList()) { if(string.IsNullOrEmpty(err.ErrorMessage)==false) { resultModel.Result+=err.ErrorMessage+"\n"; } } } } return Json(new { Result=resultModel.Result, TotalRows=totalRows, CompletedRows=completedRows, TotalPages=totalPages, PageIndex=model.PageIndex, SuccessRows=succssRows, ErrorRows=errorRows }); }
static CacheManagerFactory() { DefaultCacheManager = new MemoryCacheManager(); }