locked
MVC5 Add 1 value works but adding multiple setting it up correctly RRS feed

  • Question

  • User-544325736 posted

    Hello everyone,

    I have a program where I add a partnumber and it works great for 1 value. I need to check the column last4numbers to see if its 9999 and if not I can add it. I have a textbox in my view so you can pick how many times you are going to need to add this partnumber and everytime it will be last4numbers + 1. As long as Its not 9999 ill be able to add the partnumber. I have a loop that will take that number to see how many times it needs to be added. I check if its 9999 and if not I can add but in my current part its setup to be added then in the next loop I need to add 1 to the value. My code isn’t setup correctly it will automatically add 1 in the beginning as well. How should I setup and do this? Here is what I have

    [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult TakeOutPart(PartNumberViewModel model)
            {
                if (ModelState.IsValid)
                {
                    var valDescription = "";
                    var valUnit = "";
                    var valNextNum = Request.Form["txtNextPart"];
                    var valGroup = Request.Form["txtjsongroup"];
                    var valLast4 = Request.Form["txtjsonlast4"];
                    var valAmount = Request.Form["txtNumberNeeded"];
    
                    if(valNextNum == "")
                    {
                        if(model.PartBook != null || model.PartBook != "")
                        {
                            int.TryParse(model.PartBook, out int parseId);
    
                            var book = (from pb in context.PartBooks
                                        where pb.ID == parseId
                                        select pb).FirstOrDefault();
    
                            if(book != null)
                            {
                                var recordsPNum = (from pn in context.PartNumbers
                                                   where pn.PartGroup == book.Series
                                                   orderby pn.Last4Number descending
                                                   select pn).Take(10).ToList();
    
                                var recordBiggestPN = recordsPNum.FirstOrDefault();
    
                                if(int.TryParse(recordBiggestPN.Last4Number, out int last4))
                                {
                                    valGroup = recordBiggestPN.PartGroup;
                                    var nextNumber = last4 + 1;
                                    valLast4 = nextNumber.ToString();
                                }
                                else    /* FIGURE OUT HOW TO GET NEXTNUMBER IF 'NAN' (ex. G41) */
                                {
                                    //model.PartGroup = recordBiggestPN.PartGroup;
                                    //model.Last4Number = recordBiggestPN.Last4Number;
                                    valGroup = recordBiggestPN.PartGroup;
                                    valLast4 = recordBiggestPN.Last4Number;
                                }
                                
                                valNextNum = valGroup + "." + valLast4;
                            }
                        }
                        else
                        {
                            //Error Getting PartBook
                            TempData["Error"] = "Couldn't find PartGroup|Series|ParkBook number";
                            return RedirectToAction("TakeOutPart");
                        }
                    }
    
                    // Update to other method in future (Whole DROPDOWNLIST [Value/Text])
                    if(model.Description != null || model.Description != "")
                    {
                        // Currently have 'DESCRIPTION ID' lets change it to TEXT
                        if(int.TryParse(model.Description, out int descID))
                        {
                            valDescription = GetDescriptionNoun(descID);
                        }
                    }
    
                    // Update to other method in future (Whole DROPDOWNLIST [Value/Text])
                    if(model.Units != null || model.Units != "")
                    {
                        // Currently have 'UNIT ID' lets change it to TEXT
                        if(int.TryParse(model.Units, out int unitID))
                        {
                            valUnit = GetUnitsSelection(unitID);
                        }
                    }
                    //else
                    //{
                    //    valUnit = null;
                    //}
    
                    PartNumber partNumber = new PartNumber
                        {
                            PartGroup = valGroup,                        
                            //PartGroup = model.PartGroup,
                            Last4Number = valLast4,
                            //Last4Number = model.Last4Number,
                            PartNumber1 = valNextNum,
    
                            DateEntered = model.DateEntered,
                            EnteredBy = model.EnteredBy,
                            SoftwareType = model.SoftwareType,
                            UsedOnAssembly = model.UsedOnAssembly,
                            GlobalPart = model.GlobalPart,
                            Source = model.Source,
                            Manufacturer = model.Manufacturer,
                            ManufacturerPartNumber = model.ManufacturerPartNumber,
                            Description = valDescription,
                            Usage = model.Usage,
                            ReqOnProject = model.RequiredProject,
                            Quantity = model.Quantity,
                            Units = valUnit, // ?? Convert.DBNull.ToString(),
                            MachineTypes = model.MachineTypes,
                            Comment = model.Comments,
                            Released = false
                        };
    
                    if (valLast4 != "9999" || valLast4 != null || valLast4 != "" || !string.IsNullOrEmpty(valLast4))
                    {
                        if(valAmount == "1")
                        {
                            if (CheckValidPartNumber(partNumber.PartNumber1))
                            {
                                context.PartNumbers.Add(partNumber);
                                context.SaveChanges();
                                TempData["Success"] = "PartNumber Added Successfully";
                                return RedirectToAction("Index");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Multiples");
                            int counter = Convert.ToInt32(valAmount);
                            int nextLast4 = 0;
                            string nextPartNum = "";
    
                            for(int i=0; i<=counter; i++)
                            {
                                if (CheckValidPartNumber(partNumber.PartNumber1))
                                {
                                    if(int.TryParse(partNumber.Last4Number, out int last4))
                                    {
    
                                    }
                                    else  /* FIGURE OUT HOW TO GET NEXTNUMBER IF 'NAN' (ex. G41) */
                                    {
    
                                    }
                                }
                                else
                                {
                                    TempData["Error"] = "This PartNumber already EXISTS in the Database.";
                                    break;
                                }
                            }
    
                        }
                    }
    
                }
    
                CreatePartBookSelectList();
                CreateEnteredBySelectList();
                CreateSoftwareTypeSelectList();
                CreateSourceSelectList();
                CreateManufacturerSelectList();
                CreateDescriptionSelectList();
                CreateUsageSelectList();
                CreateUnitsSelectList();
                model.ListMachTypes = GetMachineTypes();
    
                return View(model);
            } public bool CheckValidPartNumber(string partNumber)
            {
                bool isValid = false;
    
                if(partNumber != null || partNumber != "")
                {
                    var newNumber = context.PartNumbers.Where(x => x.PartNumber1.Equals(partNumber)).FirstOrDefault();
    
                    if (newNumber == null)
                    {
                        isValid = true;
                    }
                    else
                    {
                        isValid = false;
                        TempData["Error"] = "This PartNumber already EXISTS in the Database.";
                    }
                }
    
                return isValid;
            }
    

    Tuesday, June 18, 2019 5:32 PM

All replies

  • User-544325736 posted

    This is what I did.

    Would any1 say this is the proper way to do this or advise something else? IT WORKS! Single and Multiply! 

    if (valLast4 != "9999" || valLast4 != null || valLast4 != "" || !string.IsNullOrEmpty(valLast4))
                    {
                        if(valAmount == "1")
                        {
                            if (CheckValidPartNumber(partNumber.PartNumber1))
                            {
                                context.PartNumbers.Add(partNumber);
                                context.SaveChanges();
                                TempData["Success"] = "PartNumber Added Successfully";
                                return RedirectToAction("Index");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Multiples");
    
                            int counter = Convert.ToInt32(valAmount);
                            int nextLast4 = 0;
                            string nextPartNum = "";
                            
                            for(int i=0; i<counter; i++)
                            {
                                if (int.TryParse(partNumber.Last4Number, out int last4))
                                {
                                    nextLast4 = last4 + i;
                                    partNumber.Last4Number = nextLast4.ToString();
    
                                    if (CheckPartBookHasDecimal(partNumber.PartGroup))
                                    {
                                        partNumber.PartNumber1 = valGroup + "." + nextLast4;
                                    }
                                    else
                                    {
                                        partNumber.PartNumber1 = valGroup + nextLast4;
                                    }
    
                                    if (CheckValidPartNumber(partNumber.PartNumber1))
                                    {
                                        context.PartNumbers.Add(partNumber);
                                        context.SaveChanges();
                                        TempData["Success"] = i+1 + " PartNumbers Added Successfully";
                                    }
                                    else
                                    {
                                        TempData["Error"] = "Couldn't Add Part Numbers OR they already EXIST in the Database.";
                                    }
                                }

    Tuesday, June 18, 2019 7:58 PM
  • User475983607 posted

    The code is a bit fragile as the logic does not handle concurrency very well.  It is not clear what happens if there is an error in the middle for inserting multiple.  Do you rollback, skip the error and try the next, exit with partial populated part numbers and an error message?

    IMHO, this kind of logic is better handled closer to the data store which is SQL Server.  

    Another approach is creating a static Last4Numbers variable and serializing access using locks.  This will force multiple requests (threads) to wait their turn for the next number.

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement

    Tuesday, June 18, 2019 8:46 PM
  • User1724605321 posted

    Hi ExceedingLife ,

    Another point is after getting value from client side , you didn't check whether `valAmount ` is a valid number on server side , you could use int.TryParse or use try...catch to catch the exception . And i also feel that you should check the number and make +1 operation in sql server .

    Best Regards,

    Nan Yu

    Wednesday, June 19, 2019 2:13 AM
  • User-544325736 posted

    Thank you guys I very much appreciate both of your responses! 
    Nan Yu, 'valAmount' is a control in my view of

    @Html.TextBox("txtNumberNeeded", 1,
    new { @class = "form-control", @type = "number", @min = 1 })

    This is the number of how many partnumbers they will need to enter.

    I am going to look into that Lock statement and see if there is a way i can use that while the method is running so multiple engineers cant enter part numbers at the exact same time. That would be an issue. I am completely rebuilding this application from scratch. Its going to be used worldwide in this company so many engineers will be using it and this is gong to be version 1.0 and ill continue adding features and making it run good. I decided to use entity framework for now one of the tasks is to completely rebuild the database and have all the tables in 1 central database. I'll be asking many questions as time comes and could greatly use tips comments and suggestions. As for Last4Numbers that will always be a number in the table ranging 0-9999 I now have single added and multiple added both working just need to do a lil bit with validation and test if the numbers are already there or not and see what happens. I was thinking maybe just enter as many as is allowed and once it hits an error or number taken the program will stop and say x partsnumbers were entered.

    Thank you again!

    Wednesday, June 19, 2019 3:24 PM