Ejemplo n.º 1
0
        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"));
        }
Ejemplo n.º 2
0
        // GET: People


        public async Task <IActionResult> Index(string name)
        {
            var persons = _cacheManager.Get($"persons.{HttpContext.Session.Id}", () => _context.Persons.ToList(), 2);

            _cacheManager.Get("curDate", () => DateTime.Now, 1);
            //ViewBag.Keys = _cacheManager.IsSet("persons");
            return(View(persons));
            //  return View(_dbCs.All());
        }
        public void ShouldSetCache()
        {
            MemoryCacheManager memoryCacheManager = new MemoryCacheManager();

            memoryCacheManager.Set("student", new Student()
            {
                Id = 1, Name = "dinesh"
            }, 20);
            Student student = memoryCacheManager.Get <Student>("student");

            student.Name = "dinesh Matkar";
            Student student1 = memoryCacheManager.Get <Student>("student");

            Assert.IsTrue(student1.Name == "dinesh Matkar");
        }
Ejemplo n.º 4
0
        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;
            }
        }
Ejemplo n.º 5
0
 /// <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;
     }
 }
Ejemplo n.º 6
0
        /// <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);
        }
Ejemplo n.º 7
0
        public void Test()
        {
            MemoryCacheManager cache = new MemoryCacheManager();

            cache.Set("name", "123456");
            Assert.AreEqual("123456", cache.Get <string>("name"));
        }
        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);
        }
Ejemplo n.º 9
0
        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;
            }));
        }
Ejemplo n.º 10
0
 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);
     }
 }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
0
 public void PassesMemoryCacheManager_Set_Success()
 {
     _cacheManager.Set("name", "joe", int.MaxValue);
     _cacheManager.HasKey("name").TestBeTrue();
     _cacheManager.Get <string>("name").TestEqual("joe");
     _cacheManager.Remove("name");
     _cacheManager.HasKey("name").TestBeFalse();
 }
Ejemplo n.º 15
0
        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 MemoryCacheManager_Should_Return_Null_When_Key_Not_Available()
        {
            ICacheManager cacheManager = new MemoryCacheManager();

            string value = cacheManager.Get <string>("Test");

            Assert.IsNull(value);
        }
        public void CanSetAndGetObjectsFromCache()
        {
            var cacheManager = new MemoryCacheManager();

            cacheManager.Clear();

            // Ensure that simple objects can be cached
            cacheManager.Set("some_key_1", 3, int.MaxValue);
            cacheManager.Get <int>("some_key_1").ShouldEqual(3);

            // Ensure that collections can be cached
            cacheManager.Set("some_key_2", new List <int>()
            {
                1, 2, 3
            }, int.MaxValue);
            cacheManager.Get <List <int> >("some_key_2").ShouldNotBeNull();
            cacheManager.Get <List <int> >("some_key_2").Count.ShouldEqual(3);
        }
Ejemplo n.º 18
0
        public void set_and_get_example_data_by_passing_specified_key()
        {
            string             key                = "exampleKey01";
            byte               data               = 255;
            int                cacheTime          = int.MaxValue;
            MemoryCacheManager memoryCacheManager = new MemoryCacheManager();

            memoryCacheManager.Set(key, data, cacheTime);
            Assert.AreEqual(memoryCacheManager.Get <byte>(key), data);
        }
        public void MemoryCacheManager_Should_Return_Value_When_Key_Available()
        {
            ICacheManager cacheManager = new MemoryCacheManager();

            cacheManager.Add("Test", "Dit is de waarde...", new CacheItemPolicy());

            string value = cacheManager.Get <string>("Test");

            Assert.IsNotNull(value);
        }
Ejemplo n.º 20
0
        public async Task <Publisher> GetPublisherById(int publisherId)
        {
            if (publisherId <= 0)
            {
                return(null);
            }

            string key = string.Format(PUBLISHER_BY_ID_KEY, publisherId);

            return(await _memoryCacheManager.Get(key, async() => await _publisherRepository.GetByIdAsync(publisherId)));
        }
        public void MemoryCacheManager_Should_Return_Value_And_Be_Able_To_Change_Existing_Value()
        {
            ICacheManager cacheManager = new MemoryCacheManager();

            cacheManager.Add("Test", "Dit is de waarde...", new CacheItemPolicy());
            cacheManager.AddOrOverwrite("Test", "Dit is de echte waarde...", new CacheItemPolicy());

            string value = cacheManager.Get <string>("Test");

            Assert.AreSame("Dit is de echte waarde...", value);
        }
Ejemplo n.º 22
0
        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 void MemoryCacheManager_Should_Return_Last_Added_Value_To_Cache()
        {
            ICacheManager cacheManager = new MemoryCacheManager();

            cacheManager.Add("Test", "Dit is de waarde...", new CacheItemPolicy());
            cacheManager.Add("Test", "Dit is de tweede waarde...", new CacheItemPolicy());

            string value = cacheManager.Get <string>("Test");

            Assert.AreSame("Dit is de tweede waarde...", value);
        }
Ejemplo n.º 24
0
        public async Task <Author> GetAuthorById(int authorId)
        {
            if (authorId <= 0)
            {
                return(null);
            }

            string key = string.Format(AUTHOR_BY_ID_KEY, authorId);

            return(await _memoryCacheManager.Get(key, async() => await _authorRepository.GetByIdAsync(authorId)));
        }
Ejemplo n.º 25
0
        public async Task <Book> GetBookById(int bookId)
        {
            if (bookId <= 0)
            {
                return(null);
            }

            string key = string.Format(BOOK_BY_ID_KEY, bookId);

            return(await _memoryCacheManager.Get(key, async() => await _bookRepository.GetByIdAsync(bookId)));
        }
        public void CanOverwriteExistingItemsInCache()
        {
            var cacheManager = new MemoryCacheManager();

            cacheManager.Clear();

            cacheManager.Set("some_key_1", 3, int.MaxValue);
            cacheManager.Set("some_key_1", 99, int.MaxValue);

            cacheManager.Get <int>("some_key_1").ShouldEqual(99);
        }
Ejemplo n.º 27
0
        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);
        }
Ejemplo n.º 28
0
        public async Task Set_and_get_example_data_by_passing_specified_key()
        {
            string             key                = "exampleKey01";
            byte               data               = 255;
            int                cacheTime          = int.MaxValue;
            MemoryCacheManager memoryCacheManager = new MemoryCacheManager(new MemoryCache(new MemoryCacheOptions {
            }));

            await memoryCacheManager.Set(key, data, cacheTime);

            Assert.AreEqual(await memoryCacheManager.Get <byte>(key), data);
        }
Ejemplo n.º 29
0
        public void SetBySlidingExample1()
        {
            ICacheManager cacheManager = new MemoryCacheManager();
            string        inputString  = Console.ReadLine();
            const string  cacheKey     = "MyKey";
            const double  saveHours    = 1;

            cacheManager.SetBySliding(cacheKey, inputString, saveHours);
            string cacheSaveString = cacheManager.Get <string>(cacheKey);

            Console.WriteLine(cacheSaveString);
        }
Ejemplo n.º 30
0
        public void SetBySlidingExample3()
        {
            ICacheManager cacheManager = new MemoryCacheManager();
            string        inputString  = Console.ReadLine();
            const string  cacheKey     = "MyKey";
            DateTime      saveTime     = DateTime.Now.AddHours(1);

            cacheManager.SetBySliding(cacheKey, inputString, saveTime);
            string cacheSaveString = cacheManager.Get <string>(cacheKey);

            Console.WriteLine(cacheSaveString);
        }
Ejemplo n.º 31
0
        public string GetExample2()
        {
            ICacheManager cacheManager = new MemoryCacheManager();
            string        inputString  = Console.ReadLine();
            const string  cacheKey     = "MyKey";
            const double  saveHours    = 1;

            cacheManager.SetByAbsolute(cacheKey, inputString, saveHours);
            string cacheSaveString = cacheManager.Get <string>(cacheKey);

            return(cacheSaveString);
        }
Ejemplo n.º 32
0
        public void SetBySlidingExample4()
        {
            ICacheManager cacheManager = new MemoryCacheManager();
            string        inputString  = Console.ReadLine();
            const string  cacheKey     = "MyKey";
            var           saveTimeSpan = new TimeSpan(4, 0, 0);

            cacheManager.SetBySliding(cacheKey, inputString, saveTimeSpan);
            string cacheSaveString = cacheManager.Get <string>(cacheKey);

            Console.WriteLine(cacheSaveString);
        }
Ejemplo n.º 33
0
 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;
 }
Ejemplo n.º 34
0
 public static DataSet ImportExcelDataset(string key)
 {
     ICacheManager cacheManager = new MemoryCacheManager();
     return cacheManager.Get<DataSet>(key);
 }
Ejemplo n.º 35
0
        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
            });
        }
Ejemplo n.º 36
0
        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
            });
        }
Ejemplo n.º 37
0
        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
            });
        }
Ejemplo n.º 38
0
        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
            });
        }
Ejemplo n.º 39
0
        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);
            }
        }
Ejemplo n.º 40
0
        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
            });
        }