Exemplo n.º 1
0
        public static void CreateCountryState(string regName, string CountryName, string CountryCode, string StateName, string StateCode)
        {
            ccEntities context = new ccEntities();
            var        ct      = context.Countries.Where(x => x.Name == CountryName && x.Region.Name == regName);
            var        st      = context.States.Where(x => x.Name == StateName);
            var        reg     = context.Regions.Where(x => x.Name == regName);

            int ct_id = 0, st_id = 0, reg_id = 0;

            if (reg.Any()) //must be - create before
            {
                reg_id = reg.First().Id;
            }

            if (!ct.Any())
            {
                Country c = new Country();
                c.Name     = CountryName;
                c.Code     = CountryCode;
                c.RegionId = reg_id;
                c.IncomeVerificationRequired = true;
                context.Countries.AddObject(c);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                }

                ct    = context.Countries.Where(x => x.Name == CountryName && x.Region.Name == regName);
                ct_id = ct.First().Id;
            }

            if (!st.Any() && StateName != "")
            {
                State s = new State();
                s.CountryId = ct_id;
                s.Name      = StateName;
                s.Code      = StateCode;
                context.States.AddObject(s);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                }
            }
        }
Exemplo n.º 2
0
        public static void CreateApp(string appName, string FundName, string serName, bool cont, decimal grant, decimal req, DateTime from, DateTime to)
        {
            ccEntities context = new ccEntities();
            var        fn      = context.Funds.Where(m => m.Name == FundName);
            int        fn_id   = 0;

            if (fn.Any()) //must be
            {
                fn_id = fn.First().Id;
            }

            var a = context.Apps.Where(app => app.Name == appName);

            if (!a.Any())
            {
                App app = new App();
                app.Name = appName;
                app.AgencyContribution = cont;
                app.CcGrant            = grant;
                app.RequiredMatch      = req;
                app.StartDate          = from;
                app.EndDate            = to;
                app.FundId             = fn_id;
                context.Apps.AddObject(app);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                }
            }

            a = context.Apps.Where(app => app.Name == appName);
            if (a.Any()) //must be
            {
                var ser = a.First().Services.Where(s => s.Name == serName);
                if (!ser.Any())
                {
                    var s1 = context.Services.Where(x => x.Name == serName);
                    if (s1.Any()) //must be
                    {
                        Service ss = s1.First();
                        a.First().Services.Add(ss);
                        context.SaveChanges();
                    }
                }
            }
        }
Exemplo n.º 3
0
        public static User GetUser(FixedRoles role, string AgencyName = "")
        {
            var    context = new ccEntities();
            User   newUser;
            string userName = "******" + role.ToString();

            try
            {
                newUser = context.Users.First(c => c.UserName == userName);
            }
            catch
            {
                newUser = User.CreateUser(userName, userName);
                if (AgencyName == "")
                {
                    AgencyName = "Agency1_FirstTest";
                }
                Agency a1 = context.Agencies.First(c => c.Name == AgencyName);
                newUser.AgencyId = a1.Id;
                newUser.RoleId   = (int)role;
                newUser.Email    = userName;
                //   newUser.RegionId = a1.RegionId;
                newUser.AgencyGroupId = a1.AgencyGroup.Id;
                newUser.MembershipUser.SetPassword(userName);
                context.Users.AddObject(newUser);
                context.MembershipUsers.AddObject(newUser.MembershipUser);

                context.SaveChanges();
            }

            return(newUser);
        }
Exemplo n.º 4
0
        public static void CreateAgency(string agencyName, string groupName)
        {
            var context = new ccEntities();


            int gr_id = 0;


            var gr = context.AgencyGroups.Where(x => x.Name == groupName);

            if (gr.Any())
            {
                gr_id = gr.First().Id;
            }


            var ag = context.Agencies.Where(x => x.Name == agencyName);

            if (!ag.Any())
            {
                Agency a = new Agency();
                a.Name    = agencyName;
                a.GroupId = gr_id;
                context.Agencies.AddObject(a);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                }
            }
        }
Exemplo n.º 5
0
        public static void CreateClient(string FirstName, string LastName, string AgencyName)
        {
            var    context    = new ccEntities();
            Client c1         = new Client();
            int    UpdateById = context.Users.First().Id;


            c1.Agency = context.Agencies.First(c => c.Name == AgencyName);


            c1.FirstName   = FirstName;
            c1.LastName    = LastName;
            c1.UpdatedById = UpdateById;
            c1.CountryId   = c1.Agency.AgencyGroup.CountryId;
            c1.StateId     = c1.Agency.AgencyGroup.StateId;
            c1.JoinDate    = DateTime.Now;

            try
            {
                var client = context.Clients.First(x => x.FirstName == FirstName);
            }
            catch
            {
                context.Clients.AddObject(c1);
                context.SaveChanges();
            }
        }
Exemplo n.º 6
0
        public static void SetClientData(string FirstName, DateTime leaveDate, decimal exHours, decimal gfHours)
        {
            ccEntities context = new ccEntities();
            var        client  = context.Clients.First(x => x.FirstName == FirstName);

            client.LeaveDate        = leaveDate;
            client.ExceptionalHours = exHours;
            client.GfHours          = gfHours;
            context.SaveChanges();
        }
Exemplo n.º 7
0
        public static void AddHomeCareServiceType()
        {
            var context = new ccEntities();
            var t       = context.ServiceTypes.Where(c => c.Name == "Homecare");

            if (!t.Any())
            {
                ServiceType s = new ServiceType();
                s.Name = "HomeCare";
                context.ServiceTypes.AddObject(s);
                context.SaveChanges();
            }
        }
Exemplo n.º 8
0
        public static void AddFuncScore(string FirstName, int dScore, FunctionalityLevel fl)
        {
            ccEntities         context = new ccEntities();
            var                client  = context.Clients.First(x => x.FirstName == FirstName);
            FunctionalityScore fs      = new FunctionalityScore();

            fs.ClientId           = client.Id;
            fs.DiagnosticScore    = dScore;
            fs.FunctionalityLevel = fl;
            fs.UpdatedAt          = DateTime.Now;
            fs.UpdatedBy          = GetAdminUser().Id;
            context.SaveChanges();
        }
 /// <summary>
 /// for clients who have Research in Progress approval status, 90 days after they have been entered into Diamond, they no longer can be provided service, but can be reported on for the first 90 days
 /// But, for the Keren only, the clients have to apply before receiving services or being reported on, they do not get any 90 day grace period.
 /// A new automated daily process will be run to check for any clients with """"Research in Progress"""" that this status was modified before 90 days or more and will be updating leave date for today,
 /// and leave reason ""No Client Follow Up {90 days}"" and will also check mark true a new field Administrative leave.
 /// If any values exists in the deceased date/ reason, the system automated task will not overwrite those.
 /// Once this check box is turned on, the agency is not allowed to change leave reason/ leave date/ leave remarks in any case (acts like deceased date is entered).
 /// If the client deceased during those 90 days, then the system will still allow receiving services, according to the deceased 90 days policy (implemented earlier)
 /// </summary>
 /// <param name="context"></param>
 protected override void ExecuteInternal(IJobExecutionContext contex)
 {
     using (var db = new ccEntities())
     {
         var approvalStatus      = RULE_APPROVAL_STATUS;
         var approvalStatusIdstr = ((int)RULE_APPROVAL_STATUS).ToString();
         var t1            = DateTime.Now.Date.AddDays(-90);
         var leaveDate     = DateTime.Now.Date;
         var now           = DateTime.Now;
         var ruleStartDate = RULE_START_DATE;
         var sysAdminId    = db.Users.Where(f => f.UserName == "sysadmin").Select(f => f.Id).FirstOrDefault();
         var a             = from c in db.Clients
                             let h = (
             from h in db.Histories
             where h.ReferenceId == c.Id
             where h.TableName == "Clients"
             where h.FieldName == "ApprovalStatusId"
             orderby h.UpdateDate descending
             select h
             ).FirstOrDefault()
                                     where h.NewValue == approvalStatusIdstr
                                     where h.UpdateDate >= ruleStartDate
                                     where h.UpdateDate < t1
                                     where c.Agency.GroupId != KEREN_SER_ID
                                     where c.ApprovalStatusId == (int)approvalStatus
                                     where c.LeaveDate == null || !c.AdministrativeLeave
                                     where c.AutoLeaveOverride == null || c.AutoLeaveOverride < leaveDate
                                     select c;
         foreach (var client in a.ToList())
         {
             log.InfoFormat("Updating leave details for client id {0}", client.Id);
             if (client.LeaveDate == null)
             {
                 client.LeaveDate     = leaveDate;
                 client.LeaveReasonId = 11;                         /*No Contact (90 days)*/
             }
             client.AdministrativeLeave = true;
             //updatedat/by for history records
             client.UpdatedById = sysAdminId;
             client.UpdatedAt   = now;
             try
             {
                 db.SaveChanges();
             }
             catch (Exception ex)
             {
                 log.Error(ex.Message, ex);
             }
         }
     }
 }
Exemplo n.º 10
0
        public static void AddHomeCarePeriod(string FirstName, DateTime from, DateTime to)
        {
            ccEntities             context = new ccEntities();
            var                    client  = context.Clients.First(x => x.FirstName == FirstName);
            HomeCareEntitledPeriod hc      = new HomeCareEntitledPeriod();

            hc.ClientId  = client.Id;
            hc.StartDate = from;
            hc.EndDate   = to;
            hc.UpdatedAt = DateTime.Now;
            hc.UpdatedBy = GetAdminUser().Id;
            context.HomeCareEntitledPeriods.AddObject(hc);
            context.SaveChanges();
        }
Exemplo n.º 11
0
        public static Client GetClient(string clName, bool defValue = false)
        {
            ccEntities context = new ccEntities();
            Client     cl1     = context.Clients.First(x => x.FirstName == clName);

            if (defValue)
            //set properties to default values before changes
            {
                cl1.GfHours = 0;

                context.SaveChanges();
            }
            return(cl1);
        }
Exemplo n.º 12
0
        public static void CreateFund(string MasterName, string FundName, DateTime from, DateTime to, decimal Amount, string curr)
        {
            ccEntities context = new ccEntities();
            var        ms      = context.MasterFunds.Where(m => m.Name == MasterName);
            int        ms_id   = 0;

            if (!ms.Any())
            {
                MasterFund mf = new MasterFund();
                mf.Name         = MasterName;
                mf.StartDate    = from;
                mf.EndDate      = to;
                mf.Amount       = Amount;
                mf.CurrencyCode = curr;

                context.MasterFunds.AddObject(mf);
                context.SaveChanges();
                ms = context.MasterFunds.Where(m => m.Name == MasterName);
            }
            ms_id = ms.First().Id;

            var fn = context.Funds.Where(m => m.Name == FundName && m.MasterFundId == ms_id);

            if (!fn.Any())
            {
                Fund f = new Fund();
                f.Name         = FundName;
                f.StartDate    = from;
                f.EndDate      = to;
                f.Amount       = Amount;
                f.CurrencyCode = curr;
                f.MasterFundId = ms_id;

                context.Funds.AddObject(f);
                context.SaveChanges();
            }
        }
Exemplo n.º 13
0
        public static void CreateAgencyGroup(string GroupName, string CountryName, string StateName)
        {
            var         context = new ccEntities();
            AgencyGroup a       = new AgencyGroup();

            a.Name = GroupName;
            var ct = context.Countries.Where(x => x.Name == CountryName);
            var st = context.States.Where(x => x.Name == StateName);


            int c_id = 0, st_id = 0;

            if (ct.Any())
            {
                c_id = ct.First().Id;
            }
            if (st.Any())
            {
                st_id = st.First().Id;
            }


            var g = context.AgencyGroups.Where(c => c.Name == a.Name);

            if (!g.Any())
            {
                AgencyGroup g_new = new AgencyGroup();
                g_new.Name      = GroupName;
                g_new.Addr1     = GroupName + "Test Addr1";
                g_new.Addr2     = GroupName + " Test Addr2";
                g_new.CountryId = c_id;
                if (st_id != 0)
                {
                    g_new.StateId = st_id;
                }
                g_new.ReportingPeriodId = 1;
                context.AgencyGroups.AddObject(g_new);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                }
            }
        }
        private static Import NewMethod(int userId)
        {
            Guid id = Guid.NewGuid();

            using (var db = new ccEntities())
            {
                var import = new Import()
                {
                    Id        = id,
                    StartedAt = DateTime.Now,
                    UserId    = userId
                };

                db.Imports.AddObject(import);
                db.SaveChanges();
                return(import);
            }
        }
Exemplo n.º 15
0
        public static void CreateRegion(string regionName)
        {
            Region r = new Region();

            r.Name = regionName;
            var    context = new ccEntities();
            Region r1;

            try
            {
                r1 = context.Regions.First(x => x.Name == regionName);
            }
            catch
            {
                context.Regions.AddObject(r);
                context.SaveChanges();
            }
        }
        public ActionResult InitUsers()
        {
            var res = new List <Tuple <int, string, string, string> >();

            using (var db = new ccEntities())
            {
                foreach (var agency in db.Agencies.Where(f => !f.Users.Any()))
                {
                    string pass = System.Web.Security.Membership.GeneratePassword(8, 2);
                    var    user = CC.Data.User.CreateUser(agency.Id + "_agencyUser", pass);
                    agency.Users.Add(user);
                    user.RoleId = (int)FixedRoles.AgencyUser;
                    res.Add(new Tuple <int, string, string, string>(agency.Id, agency.Name, user.UserName, pass));
                }
                db.SaveChanges();
            }
            using (var db = new ccEntities())
            {
                foreach (var ser in db.AgencyGroups.Where(f => !f.Users.Any()))
                {
                    string pass = System.Web.Security.Membership.GeneratePassword(8, 2);
                    var    user = CC.Data.User.CreateUser(ser.Id + "_serUser", pass);
                    user.RoleId = (int)FixedRoles.Ser;
                    ser.Users.Add(user);
                    res.Add(new Tuple <int, string, string, string>(ser.Id, ser.DisplayName, user.UserName, pass));
                }
                db.SaveChanges();
            }
            using (var db = new ccEntities())
            {
                foreach (var item in db.Regions.Where(f => f.Id != 0 && !f.Users.Any()))
                {
                    string pass = System.Web.Security.Membership.GeneratePassword(8, 2);
                    var    user = CC.Data.User.CreateUser(item.Id + "_rpo", pass);
                    user.RoleId = (int)FixedRoles.RegionOfficer;
                    item.Users.Add(user);
                    res.Add(new Tuple <int, string, string, string>(item.Id, item.Name, user.UserName, pass));
                }
                db.SaveChanges();
            }
            var sb = new System.Text.StringBuilder();

            return(this.Excel("users", "user", res));
        }
 public override void WriteResource(string name, string culture, string value)
 {
     using (var db = new ccEntities())
     {
         var resources = db.Resources
                         .Where(f => f.Culture == culture && f.Key == name)
                         .FirstOrDefault();
         if (resources == null)
         {
             throw new Exception(string.Format("Resource {0} for culture {1} was not found", name, culture));
         }
         else
         {
             resources.Value = value;
             db.SaveChanges();
             base.UpdateCachedResource(name, culture, value);
         }
     }
 }
Exemplo n.º 18
0
        public static void CreateGroupService(string GroupName, string SerName)
        {
            ccEntities context = new ccEntities();

            int s_id = 0;
            var gs   = context.AgencyGroups.Where(g => g.Name == GroupName);

            if (gs.Any()) //must exists: created before
            {
                var gs_ser = gs.First().Services.Where(s => s.Name == SerName);
                if (!gs_ser.Any()) //must exists: created before
                {
                    var ser = context.Services.Where(s => s.Name == SerName);
                    if (ser.Any())
                    {
                        s_id = ser.First().Id;
                        gs.First().Services.Add(ser.First());
                        context.SaveChanges();
                    }
                }
            }
        }
Exemplo n.º 19
0
        public static void CreateService(string TypeName, string SerName)
        {
            var context = new ccEntities();
            var s       = context.Services.Where(c => c.Name == SerName);

            var t    = context.ServiceTypes.Where(c => c.Name == TypeName);
            int t_id = 0;

            if (t.Any())
            {
                t_id = t.First().Id;
            }
            if (!s.Any())
            {
                Service ser = new Service();
                ser.Name              = SerName;
                ser.TypeId            = t_id;
                ser.ReportingMethodId = 1;
                context.Services.AddObject(ser);
                context.SaveChanges();
            }
        }
        public ActionResult UserAgreement(UserAgreementAudit model)
        {
            ModelState.Clear();

            if (ModelState.IsValid)
            {
                using (var db = new ccEntities())
                {
                    var user = db.Users.SingleOrDefault(f => f.UniqueId == model.User.UniqueId);

                    model.Date = DateTime.Now;
                    model.User = user;
                    model.IP   = Request.ServerVariables["X_FORWARDED_FOR"] ?? Request.UserHostAddress;

                    db.UserAgreementAudits.AddObject(model);
                    db.SaveChanges();
                    FormsAuthentication.RedirectFromLoginPage(user.UserName, false);
                    return(null);
                }
            }
            return(View(model));
        }
        internal void Insert(ccEntities db, CC.Data.Services.IPermissionsBase permissionsBase)
        {
            var c = db.Clients.Where(permissionsBase.ClientsFilter).SingleOrDefault(f => f.Id == this.ClientId);

            if (c == null)
            {
                throw new Exception("Client not found.");
            }
            else
            {
                var gfHour = this.GetGFHour;
                gfHour.UpdatedBy = permissionsBase.User.Id;
                db.GrandfatherHours.AddObject(gfHour);
                try
                {
                    db.SaveChanges();
                }
                catch (System.Data.UpdateException ex)
                {
                    var msg = ex.InnerException.Message;
                    if (msg.Contains("PK_GFHours"))
                    {
                        throw new Exception("Duplicate entry.", ex);
                    }
                    else if (msg.Contains("FK_GFHours_Clients"))
                    {
                        throw new Exception("Client not found.", ex);
                    }
                    else if (msg.Contains("CK_GFHours_Value"))
                    {
                        throw new Exception("Invalid Value.", ex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
        public static void DeleteFile(Guid id, bool isLandingPage, HttpServerUtilityBase Server, ref List <string> Errors)
        {
            string path = Server.MapPath(isLandingPage ? LandingPagePath : DefaultPath);

            using (var db = new ccEntities())
            {
                var file = db.Files.SingleOrDefault(f => f.Id == id);
                try
                {
                    var di      = new DirectoryInfo(path);
                    var name    = id.ToString();
                    var delfile = di.GetFiles().SingleOrDefault(f => f.Name == name);
                    if (delfile != null)
                    {
                        delfile.Delete();
                    }
                    if (file != null)
                    {
                        db.Files.DeleteObject(file);
                        db.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                    if (ex.InnerException != null)
                    {
                        var inner = ex.InnerException;
                        while (inner.InnerException != null)
                        {
                            inner = inner.InnerException;
                        }
                        msg = inner.Message;
                    }
                    Errors.Add(msg);
                }
            }
        }
        internal void Insert(ccEntities db, CC.Data.Services.IPermissionsBase permissionsBase)
        {
            var c = db.Clients.Where(permissionsBase.ClientsFilter).SingleOrDefault(f => f.Id == this.ClientId);

            if (c == null)
            {
                throw new Exception("Client not found.");
            }
            else
            {
                db.UnmetNeedsOthers.AddObject(this.GetUnmetNeedsOther);
                try
                {
                    db.SaveChanges();
                }
                catch (System.Data.UpdateException ex)
                {
                    var msg = ex.InnerException.Message;
                    if (msg.Contains("PK_UnmetNeedsOther"))
                    {
                        throw new Exception("Duplicate entry.", ex);
                    }
                    else if (msg.Contains("FK_UnmetNeedsOther_Clients"))
                    {
                        throw new Exception("Client not found.", ex);
                    }
                    else if (msg.Contains("CK_UnmetNeedsOther_Amount"))
                    {
                        throw new Exception("Invalid Amount Value. Must be >=0", ex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Exemplo n.º 24
0
        public static User GetSerUser(string GroupName)
        {
            var  context = new ccEntities();
            User newUser = null;
            int  ag_id   = 0;
            var  g1      = context.AgencyGroups.Where(g => g.Name == GroupName);

            if (g1.Any())
            {
                ag_id = g1.First().Id;
                string     userName = "******" + ag_id;
                FixedRoles role     = FixedRoles.Ser;

                var us = context.Users.Where(u => u.UserName == userName);

                if (!us.Any())
                {
                    newUser = User.CreateUser(userName, userName);

                    newUser.RegionId      = g1.First().Country.RegionId;
                    newUser.RoleId        = (int)role;
                    newUser.Email         = userName;
                    newUser.AgencyGroupId = ag_id;
                    newUser.MembershipUser.SetPassword(userName);
                    context.Users.AddObject(newUser);
                    context.MembershipUsers.AddObject(newUser.MembershipUser);

                    context.SaveChanges();
                }
                else
                {
                    newUser = us.First();
                }
            }

            return(newUser);
        }
        public ActionResult Upload(HttpPostedFileWrapper file)
        {
            if (file == null)
            {
                var model = new ClientsIndexModel();
                ViewBag.ImportApprovalStatusError = "Please select a file.";
                return(View("Index", model));
            }
            var id = Guid.NewGuid();

            string fileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), id.ToString());

            var csvConf = new CsvHelper.Configuration.CsvConfiguration()
            {
                IsStrictMode     = false,
                IsCaseSensitive  = false,
                SkipEmptyRecords = true
            };

            csvConf.ClassMapping <ApprovalStatusCsvMap>();



            using (var csvReader = new CsvHelper.CsvReader(new System.IO.StreamReader(file.InputStream), csvConf))
            {
                var updatedAt = DateTime.Now;
                var updatedBy = this.Permissions.User.Id;

                var csvChunkSize = 10000;
                var recordIndex  = 1;

                Dictionary <int, int> fsas = new Dictionary <int, int>();

                using (var db = new ccEntities())
                {
                    db.Imports.AddObject(new CC.Data.Import()
                    {
                        Id        = id,
                        StartedAt = DateTime.Now,
                        UserId    = this.Permissions.User.Id
                    });
                    db.SaveChanges();

                    var q = (from fs in db.FundStatuses
                             join a in db.ApprovalStatuses on fs.ApprovalStatusName equals a.Name
                             select new
                    {
                        fsid = fs.Id,
                        asid = a.Id
                    }
                             );
                    foreach (var intem in q)
                    {
                        fsas.Add(intem.fsid, intem.asid);
                    }
                }



                foreach (var csvChunk in csvReader.GetRecords <ImportClient>().Split(csvChunkSize))
                {
                    string connectionString = System.Data.SqlClient.ConnectionStringHelper.GetProviderConnectionString();

                    using (var sqlBulk = new System.Data.SqlClient.SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepNulls))
                    {
                        foreach (var record in csvChunk)
                        {
                            record.RowIndex = recordIndex++;
                            record.ImportId = id;
                            if (record.FundStatusId.HasValue && fsas.ContainsKey(record.FundStatusId.Value))
                            {
                                record.ApprovalStatusId = fsas[record.FundStatusId.Value];
                            }
                            record.UpdatedAt   = updatedAt;
                            record.UpdatedById = updatedBy;
                        }

                        var dataTable = csvChunk.ToDataTable();
                        var q         = dataTable.Columns.OfType <System.Data.DataColumn>().Where(f => f.DataType == typeof(Int32)).Select(f => new
                        {
                            c      = f.ColumnName,
                            values = dataTable.Rows.OfType <System.Data.DataRow>().Select((r, i) => r[f.ColumnName])
                        });

                        sqlBulk.DestinationTableName = "ImportClients";
                        sqlBulk.NotifyAfter          = 1000;
                        sqlBulk.ColumnMappings.Add("ClientId", "ClientId");
                        sqlBulk.ColumnMappings.Add("FundStatusId", "FundStatusId");
                        sqlBulk.ColumnMappings.Add("RowIndex", "RowIndex");
                        sqlBulk.ColumnMappings.Add("ImportId", "ImportId");
                        sqlBulk.ColumnMappings.Add("UpdatedAt", "UpdatedAt");
                        sqlBulk.ColumnMappings.Add("UpdatedById", "UpdatedById");

                        sqlBulk.SqlRowsCopied += (s, e) =>
                        {
                            System.Diagnostics.Debug.Write(e.RowsCopied);
                        };

                        sqlBulk.WriteToServer(dataTable);
                    }
                }
            }

            return(RedirectToAction("Preview", new { id = id }));
        }
 public int SaveChanges(System.Data.Objects.SaveOptions options)
 {
     return(_dataContext.SaveChanges(options));
 }
        public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            var r = value as zz;

            if (destinationType.Equals(typeof(Client)))
            {
                var c = new Client();
                c.Id         = r.CLIENT_ID;
                c.Agency     = agencies.Single(f => f.Id == r.ORG_ID);
                c.LastName   = r.LAST_NAME;
                c.FirstName  = r.FIRST_NAME;
                c.MiddleName = r.MIDDLE_NAME;
                c.BirthDate  = r.DOB;

                c.Address = r.ADDRESS;
                c.City    = r.CITY;
                if (!string.IsNullOrEmpty(r.STATE_CODE))
                {
                    try { c.State = states.Single(f => f.Code == r.STATE_CODE); }
                    catch (InvalidOperationException) { /*ignore states*/ }
                }
                if (!string.IsNullOrEmpty(r.TYPE_OF_ID))
                {
                    try { c.NationalIdType = nationalIdTypes.Single(f => f.Name.Equals(r.TYPE_OF_ID, StringComparison.InvariantCultureIgnoreCase)); }
                    catch (InvalidOperationException)
                    {
                        var n = new NationalIdType()
                        {
                            Name = r.TYPE_OF_ID
                        };
                        using (var db = new ccEntities())
                        {
                            db.NationalIdTypes.AddObject(n);
                            db.SaveChanges();
                            c.NationalIdType = n;
                            nationalIdTypes.Add(n);
                        }
                        //throw new InvalidOperationException("NationalIdType \"" + r.TYPE_OF_ID + "\" is invalid.");
                    }
                }
                c.NationalId = r.Gov_ID;
                c.Phone      = r.PHONE;

                c.IsCeefRecipient = r.CLIENT_COMP_PROGRAM;
                c.CeefId          = r.COMP_PROG_REG_NUM;

                c.AddCompName = r.AdditionalComp;
                c.AddCompId   = r.AdditionalCompNum;

                //c.Deceased
                c.DeceasedDate = r.DOD;
                c.New_Client   = r.New_Client;
                c.UpdatedAt    = r.Upload_Date ?? DateTime.Now;
                c.MatchFlag    = r.MatchFlag;
                c.FundStatus   = r.Fund_Status;


                return(c);
            }
            return(base.ConvertTo(context, culture, value, destinationType));
        }
Exemplo n.º 28
0
        public ActionResult Upload(HttpPostedFileWrapper file)
        {
            if (file == null)
            {
                ModelState.AddModelError(string.Empty, "Please select a file");
                var csvColumnNames = CsvHelper.CsvHelperExtenstions.ColumnHeaderNames <ImportHcepCsvMap>();
                return(View(csvColumnNames));
            }

            var ImportId = Guid.NewGuid();

            string fileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), ImportId.ToString());

            var csvConf = new CsvHelper.Configuration.CsvConfiguration()
            {
                IsStrictMode     = false,
                IsCaseSensitive  = false,
                SkipEmptyRecords = true,
            };

            csvConf.ClassMapping <ImportHcepCsvMap>();


            var updatedAt = DateTime.Now;
            var updatedBy = this.Permissions.User.Id;

            using (var db = new ccEntities())
            {
                db.Imports.AddObject(new Import()
                {
                    Id        = ImportId,
                    StartedAt = updatedAt,
                    UserId    = this.Permissions.User.Id
                });
                db.SaveChanges();
            }

            using (var csvReader = new CsvHelper.CsvReader(new System.IO.StreamReader(file.InputStream), csvConf))
            {
                var csvChunkSize = 10000;
                var recordIndex  = 1;
                foreach (var csvChunk in csvReader.GetRecords <ImportHcep>().Split(csvChunkSize))
                {
                    string connectionString = ConnectionStringHelper.GetProviderConnectionString();

                    using (var sqlBulk = new System.Data.SqlClient.SqlBulkCopy(connectionString))
                    {
                        foreach (var record in csvChunk)
                        {
                            record.RowIndex  = recordIndex++;
                            record.ImportId  = ImportId;
                            record.UpdatedAt = updatedAt;
                            record.UpdatedBy = updatedBy;
                        }


                        sqlBulk.DestinationTableName = "ImportHcep";

                        sqlBulk.ColumnMappings.Add("ImportId", "ImportId");
                        sqlBulk.ColumnMappings.Add("RowIndex", "RowIndex");
                        sqlBulk.ColumnMappings.Add("Id", "Id");
                        sqlBulk.ColumnMappings.Add("ClientId", "ClientId");
                        sqlBulk.ColumnMappings.Add("StartDate", "StartDate");
                        sqlBulk.ColumnMappings.Add("EndDate", "EndDate");
                        sqlBulk.ColumnMappings.Add("UpdatedAt", "UpdatedAt");
                        sqlBulk.ColumnMappings.Add("UpdatedBy", "UpdatedBy");

                        var reader = new CC.Web.Helpers.IEnumerableDataReader <ImportHcep>(csvChunk);
                        sqlBulk.WriteToServer(reader);
                    }
                }
            }


            return(this.RedirectToAction(f => f.Preview(ImportId)));
        }
 public int SaveChanges()
 {
     return(_context.SaveChanges());
 }
 public int SaveChanges()
 {
     return(_objectContext.SaveChanges());
 }