Exemplo n.º 1
0
        /// <summary>
        /// Read drivers Csv File
        /// </summary>
        /// <param name="strFileName"></param>
        /// <returns></returns>
        public static UploadDrivers ReadExecuteDriverCsvFile(string strFileName)
        {
            UploadDrivers validations = new UploadDrivers();
            var           ValidList   = new List <List <DriversModel> >();

            using (CsvReader reader = new CsvReader(strFileName, Encoding.Default))
            {
                DataTable csvTable         = reader.ReadIntoDataTable();
                var       rangePartitioner = Partitioner.Create(0, csvTable.Rows.Count, 1000);

                Parallel.ForEach(rangePartitioner, (range, loopState) =>
                {
                    var Valid = new List <DriversModel>();
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        var classObj = new DriversModel()
                        {
                            DotNumber     = Convert.ToString(csvTable.Rows[i]["DotNumber"]),
                            FirstName     = Convert.ToString(csvTable.Rows[i]["FirstName"]),
                            LastName      = Convert.ToString(csvTable.Rows[i]["LastName"]),
                            LicenseState  = Convert.ToString(csvTable.Rows[i]["LicenseState"]),
                            isActive      = string.IsNullOrEmpty(Convert.ToString(csvTable.Rows[i]["isActive"])) ? "N" : (Convert.ToString(csvTable.Rows[i]["isActive"]).ToLower() == "y" || Convert.ToString(csvTable.Rows[i]["isActive"]).ToLower() == "yes") ? "Y" : "N",
                            LicenseNumber = Convert.ToString(csvTable.Rows[i]["LicenseNumber"]),
                            DOB           = csvTable.Rows[i]["DOB"].ToString().Replace(" 12:00:00 AM", "")
                        };
                        Valid.Add(classObj);
                    }
                    ValidList.Add(Valid);
                });
            }
            validations.ChunkDriverdata = ValidList;
            return(validations);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Tab delemited txt file reader for Drivers
        /// </summary>
        /// <param name="docPath"></param>
        /// <returns></returns>
        public static UploadDrivers ReadExecuteDelimitedDriverFile(string docPath)
        {
            UploadDrivers validations = new UploadDrivers();
            var           ValidList   = new List <DriversModel>();
            bool          isHeader    = true;

            using (var file = new StreamReader(docPath))
            {
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    if (isHeader == false)
                    {
                        var          delimiters = new char[] { '\t' };
                        var          segments   = line.Split(delimiters, StringSplitOptions.None);
                        DriversModel driverData = new DriversModel();
                        driverData.DotNumber     = segments[0];
                        driverData.FirstName     = segments[1];
                        driverData.LastName      = segments[2];
                        driverData.LicenseState  = segments[3];
                        driverData.isActive      = string.IsNullOrEmpty(segments[4]) ? "N" : Convert.ToString(segments[4]).ToLower().Contains('y') ? "Y" : "N";
                        driverData.LicenseNumber = string.IsNullOrEmpty(segments[5]) ? string.Empty : segments[5];
                        driverData.DOB           = string.IsNullOrEmpty(segments[6]) ? string.Empty : segments[6];
                        ValidList.Add(driverData);
                    }
                    else
                    {
                        isHeader = false;
                    }
                }
                file.Close();
            }
            var ValidLists       = new List <List <DriversModel> >();
            var rangePartitioner = Partitioner.Create(0, ValidList.Count, 1000);

            Parallel.ForEach(rangePartitioner, (range, loopState) =>
            {
                var Valid = new List <DriversModel>();
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    var classObj = new DriversModel()
                    {
                        DotNumber     = Convert.ToString(ValidList[i].DotNumber),
                        FirstName     = Convert.ToString(ValidList[i].FirstName),
                        LastName      = Convert.ToString(ValidList[i].LastName),
                        LicenseState  = Convert.ToString(ValidList[i].LicenseState),
                        isActive      = string.IsNullOrEmpty(Convert.ToString(ValidList[i].isActive)) ? "N" : (Convert.ToString(ValidList[i].isActive).ToLower() == "y" || Convert.ToString(ValidList[i].isActive).ToLower() == "yes") ? "Y" : "N",
                        LicenseNumber = Convert.ToString(ValidList[i].LicenseNumber).Trim(','),
                        DOB           = Convert.ToString(ValidList[i].DOB).Trim(',')
                    };
                    Valid.Add(classObj);
                }
                ValidLists.Add(Valid);
            });
            validations.ChunkDriverdata = ValidLists;
            return(validations);
        }
Exemplo n.º 3
0
        public async Task <StatusResult> UploadBulkDrivers(UploadDrivers model)
        {
            StatusResult c = new StatusResult();

            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => x.Value.Errors.Select(y => y.ErrorMessage)).ToList();
                    Log.Error(Logfornet.LogMessage(model.CompanyID, "UploadBulkDrivers", errors.ToArray(), ""));
                    c.Status = Status.BadRequest.ToString();
                    c.Result = BadRequest();
                    return(c);
                }
                if (User.IsInRole(Roles.SuperAdmin) || User.IsInRole(Roles.PortalAdmin) || User.IsInRole(Roles.AccountAdmin))
                {
                    DriverConfig DriverConfig = new DriverConfig();
                    string       UserID       = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                    var          res          = await DriverConfig.UploadDrivers(model, UserID);

                    if (res != null)
                    {
                        Log.Error(Logfornet.LogMessage(model.CompanyID, "UploadBulkDrivers", "Please upload company logo", ""));
                        c.Status = Status.Success.ToString();
                        c.Result = res.DriverData;
                        return(c);
                    }
                    else
                    {
                        Log.Warn(Logfornet.LogMessage(model.CompanyID, "UploadBulkDrivers", ErrorMessages.AlreadyExists, ""));
                        c.Status = Status.Fail.ToString();
                        c.Result = "Please upload standard file.";
                        return(c);
                    }
                }
                else
                {
                    Log.Warn(Logfornet.LogMessage(model.CompanyID, "UploadBulkDrivers", ErrorMessages.NoAccessDenied, ""));
                    c.Status = Status.NoAccess.ToString();
                    c.Result = "No Access";
                    return(c);
                }
            }
            catch (Exception ex)
            {
                Log.Error(Logfornet.LogMessage(model.CompanyID, "UploadBulkDrivers", ex.Message, ex.StackTrace));
                c.Status     = ExceptionStatus.SqlException.ToString();
                c.StatusCode = (int)ExceptionStatus.SqlException;
                c.Result     = "Please upload standard file.";
                return(c);
            }
        }
Exemplo n.º 4
0
        private async Task InsertDrivers(UploadDrivers model, string Userid)
        {
            var companyId = model.CompanyID;

            foreach (var driver in model.DriverData)
            {
                var Lcount = context.Drivers.Where(m => m.LicenseNumber == driver.LicenseNumber && m.CompanyId == model.CompanyID && m.isDelete == false).FirstOrDefault();
                if (Lcount == null)
                {
                    var drivermodel = new Driver
                    {
                        CompanyId     = companyId,
                        FirstName     = driver.FirstName,
                        LastName      = driver.LastName,
                        DOB           = Convert.ToDateTime(driver.DOB).Date,
                        LicenseState  = driver.LicenseState,
                        LicenseNumber = driver.LicenseNumber,
                        DOTNumber     = driver.DotNumber,
                        CreatedBy     = Userid,
                        CreatedOn     = DateTime.Now,
                        ModifiedBy    = Userid,
                        ModifiedOn    = DateTime.Now,
                        isActive      = (driver.isActive.ToLower() == "yes" || driver.isActive.ToLower() == "y") ? true : false,
                        isDelete      = false
                    };
                    context.Drivers.Add(drivermodel);
                }
                else
                {
                    Lcount.FirstName     = driver.FirstName;
                    Lcount.LastName      = driver.LastName;
                    Lcount.DOB           = Convert.ToDateTime(driver.DOB).Date;
                    Lcount.LicenseState  = driver.LicenseState;
                    Lcount.LicenseNumber = driver.LicenseNumber;
                    Lcount.DOTNumber     = driver.DotNumber;
                    Lcount.ModifiedBy    = Userid;
                    Lcount.ModifiedOn    = DateTime.Now;
                    Lcount.isActive      = (driver.isActive.ToLower() == "yes" || driver.isActive.ToLower() == "y") ? true : false;
                }
                await context.SaveChangesAsync();
            }
        }
Exemplo n.º 5
0
        public async Task <UploadDrivers> UploadDrivers(UploadDrivers model, string UserID)
        {
            IDriverService DriverInfo = new DriverService(model.CompanyID);

            return(await DriverInfo.UploadDrivers(model, UserID));
        }
Exemplo n.º 6
0
        public async Task<ActionResult> UploadDrivers(int CompanyID, HttpPostedFileBase fileDriver)
        {
            CustomerProfile cProfile = new CustomerProfile();
            cProfile.CompanyID = CompanyID;
            try
            {
                if (fileDriver.ContentLength > 0)
                {
                    cProfile.CompanyList = (SelectList)TempData["CompanyList"];
                    TempData.Keep();
                    UploadDrivers filevalidations;
                    ViewBag.FileName = System.IO.Path.GetFileName(fileDriver.FileName);
                    var extension = Path.GetExtension(fileDriver.FileName);
                    string savefilename = Path.Combine(Server.MapPath("~/Uploads"),
                                     Path.GetFileName(fileDriver.FileName));
                    fileDriver.SaveAs(savefilename);
                    if (extension.Contains(".txt"))
                    {

                        filevalidations = CommonFunctions.ReadExecuteDelimitedDriverFile(savefilename);
                    }
                    else
                    {
                        filevalidations = CommonFunctions.ReadExecuteDriverCsvFile(savefilename);
                    }
                    List<HttpResponseMessage> customerData = new List<HttpResponseMessage>();
                    int count = 0;
                    Parallel.ForEach(filevalidations.ChunkDriverdata, driverRes =>
                    {
                        var client = new HttpClient();
                        client.BaseAddress = new Uri(_url);
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        UploadDrivers DriverDataModel = new UploadDrivers();
                        DriverDataModel.CompanyID = CompanyID;
                        DriverDataModel.Driverdata = driverRes;
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userData.AccessToken);
                        client.Timeout = TimeSpan.FromMinutes(60);
                        Task<HttpResponseMessage> responseMessage = client.PostAsJsonAsync(_url + "DriverInfo/UploadBulkDrivers", DriverDataModel);
                        customerData.Add(responseMessage.Result);
                        count++;
                        ViewBag.ProcessStatus = count * 1000 + " Records processed.";
                        responseMessage.Dispose();
                        client.Dispose();
                    });
                    List<DriversModel> responceResults = null;
                    foreach (var customer in customerData)
                    {
                        if (customer.IsSuccessStatusCode)
                        {
                            var result = await customer.Content.ReadAsStringAsync();
                            if (JsonConvert.DeserializeObject<StatusResult>(result).Status.Equals(Status.Success.ToString()))
                            {
                                responceResults = new List<Web.Models.DriversModel>();
                                responceResults.AddRange(JsonConvert.DeserializeObject<List<DriversModel>>(JsonConvert.DeserializeObject<StatusResult>(result).Result.ToString()));
                            }
                        }
                    }
                    if (responceResults == null)
                    {
                        cProfile.SuccessMesage = "Some thing went wrong.";
                        System.IO.File.Delete(Server.MapPath("~/Uploads/" + fileDriver.FileName));
                        return View(cProfile);
                    }
                    else if (responceResults.Count == 0)
                    {
                        cProfile.SuccessMesage = "Your file has been uploaded successfully";
                        System.IO.File.Delete(Server.MapPath("~/Uploads/" + fileDriver.FileName));
                        return View(cProfile);
                    }
                    else
                    {
                        TempData["FailDriverResult"] = responceResults;
                        System.IO.File.Delete(Server.MapPath("~/Uploads/" + fileDriver.FileName));
                        cProfile.UploadFailMessage = "Some entries where not successfully uploaded.Please make necessary corrections and upload a new file.";
                        return View(cProfile);
                    }
                }
            }
            catch (Exception ex)
            {
                System.IO.File.Delete(Server.MapPath("~/Uploads/" + fileDriver.FileName));
                cProfile.ExMessage = ex.Message + "Please upload a standard file";
                return View(cProfile);
            }
            return View();
        }
Exemplo n.º 7
0
        public async Task <UploadDrivers> UploadDrivers(UploadDrivers model, string Userid)
        {
            if (IsActiveProfile)
            {
                //FirstName Empty
                Regex rgx = new Regex("^[a-zA-Z0-9'-]+$");
                var   invalidFirstName = model.DriverData.Where(x => string.IsNullOrEmpty(x.FirstName) || !rgx.IsMatch(x.FirstName))
                                         .Select(y => new DriversModel
                {
                    DOB           = y.DOB,
                    DotNumber     = y.DotNumber,
                    FirstName     = y.FirstName,
                    LastName      = y.LastName,
                    isActive      = y.isActive,
                    LicenseNumber = y.LicenseNumber,
                    LicenseState  = y.LicenseState,
                    Remarks       = "FirstName is empty Or invalid format"
                }).ToList();
                model.DriverData.RemoveAll(x => invalidFirstName.Any(y => y.FirstName == x.FirstName));
                //LastName Empty
                var invalidLastName = model.DriverData.Where(x => string.IsNullOrEmpty(x.LastName) || !rgx.IsMatch(x.LastName))
                                      .Select(y => new DriversModel
                {
                    DOB           = y.DOB,
                    DotNumber     = y.DotNumber,
                    FirstName     = y.FirstName,
                    LastName      = y.LastName,
                    isActive      = y.isActive,
                    LicenseNumber = y.LicenseNumber,
                    LicenseState  = y.LicenseState,
                    Remarks       = "LastName is empty Or invalid format"
                }).ToList();
                model.DriverData.RemoveAll(x => invalidLastName.Any(y => y.LastName == x.LastName));

                //LicenceState Empty
                var invalidLicenseState = model.DriverData.Where(x => string.IsNullOrEmpty(x.LicenseState) && x.LicenseState.Length == 2)
                                          .Select(y => new DriversModel
                {
                    DOB           = y.DOB,
                    DotNumber     = y.DotNumber,
                    FirstName     = y.FirstName,
                    LastName      = y.LastName,
                    isActive      = y.isActive,
                    LicenseNumber = y.LicenseNumber,
                    LicenseState  = y.LicenseState,
                    Remarks       = "License state is empty Or enter state shortname(two digit)"
                }).ToList();
                model.DriverData.RemoveAll(x => invalidLicenseState.Any(y => y.LicenseState == x.LicenseState));

                //Licence No Empty
                var invalidLicenseNumber = model.DriverData.Where(x => string.IsNullOrEmpty(x.LicenseNumber))
                                           .Select(y => new DriversModel
                {
                    DOB           = y.DOB,
                    DotNumber     = y.DotNumber,
                    FirstName     = y.FirstName,
                    LastName      = y.LastName,
                    isActive      = y.isActive,
                    LicenseNumber = y.LicenseNumber,
                    LicenseState  = y.LicenseState,
                    Remarks       = "License number is empty"
                }).ToList();
                model.DriverData.RemoveAll(x => invalidLicenseNumber.Any(y => y.LicenseNumber == x.LicenseNumber));

                //isActive No Empty
                var invalidIsActive = model.DriverData.Where(x => string.IsNullOrEmpty(x.isActive))
                                      .Select(y => new DriversModel
                {
                    DOB           = y.DOB,
                    DotNumber     = y.DotNumber,
                    FirstName     = y.FirstName,
                    LastName      = y.LastName,
                    isActive      = y.isActive,
                    LicenseNumber = y.LicenseNumber,
                    LicenseState  = y.LicenseState,
                    Remarks       = "IsActive is empty"
                }).ToList();
                model.DriverData.RemoveAll(x => invalidIsActive.Any(y => y.isActive == x.isActive));

                //DOB Exists
                var invalidDOB = model.DriverData.Where(x => !CheckDate(x.DOB))
                                 .Select(y => new DriversModel
                {
                    DOB           = y.DOB,
                    DotNumber     = y.DotNumber,
                    FirstName     = y.FirstName,
                    LastName      = y.LastName,
                    isActive      = y.isActive,
                    LicenseNumber = y.LicenseNumber,
                    LicenseState  = y.LicenseState,
                    Remarks       = "date of birth is invalid format"
                }).ToList();
                model.DriverData.RemoveAll(x => invalidDOB.Any(y => y.DOB == x.DOB));

                //Invalid DOT Number
                var invalidDOTnumber = model.DriverData.Where(x => !CheckDotExists(x.DotNumber, model.CompanyID))
                                       .Select(y => new DriversModel
                {
                    DOB           = y.DOB,
                    DotNumber     = y.DotNumber,
                    FirstName     = y.FirstName,
                    LastName      = y.LastName,
                    isActive      = y.isActive,
                    LicenseNumber = y.LicenseNumber,
                    LicenseState  = y.LicenseState,
                    Remarks       = "DOTnumber not exist"
                }).ToList();
                model.DriverData.RemoveAll(x => invalidDOTnumber.Any(y => y.DotNumber == x.DotNumber));


                await InsertDrivers(model, Userid);

                var InvalidModel = invalidFirstName; InvalidModel.AddRange(invalidLastName);
                InvalidModel.AddRange(invalidIsActive); InvalidModel.AddRange(invalidLicenseState);
                InvalidModel.AddRange(invalidLicenseNumber); InvalidModel.AddRange(invalidDOB);
                InvalidModel.AddRange(invalidDOTnumber);
                var InvalidResult = new UploadDrivers();
                InvalidResult.DriverData = new List <DriversModel>();
                InvalidResult.CompanyID  = model.CompanyID;
                InvalidResult.DriverData = InvalidModel;
                return(InvalidResult);
            }
            else
            {
                return(null);
            }
        }