protected void Page_Load(object sender, EventArgs e) { if (Session["Service"] != null) { service = (Service)Session["Service"]; } else { service = new Service(); } rptRepair.DataSource = service.Repairs; rptRepair.DataBind(); if (Request.QueryString["query"] != null) { selectedRepair = service.GetRepair(Convert.ToInt32(Request.QueryString["query"])); tbTramNrRep.Text = Convert.ToString(selectedRepair.Tram.TramNr); tbDescrRep.Text = selectedRepair.Description; ddlUserRep.SelectedItem.Text = selectedRepair.User.ToString(); ddlStatusRep.SelectedItem.Text = "REPAIR"; } if (!IsPostBack) { foreach (User user in service.Users) { ddlUserRep.Items.Add(user.Username); } } }
public Repair[] SortRepairs( Repair[] toSort) { for(int i= 0; i < toSort.Length; i++) { for(int j = 0; j < toSort.Length-1; j++) { if(ReturnsPriorityByNumber(toSort[j].priority) < ReturnsPriorityByNumber(toSort[j+1].priority)) { Swap(ref toSort, j); } } } return toSort; }
public ActionResult DeleteConfirmed(int id) { try { Repair repair = db.Repairs.Find(id); db.Repairs.Remove(repair); db.SaveChanges(); } catch (DataException dex) { return(RedirectToAction("Delete", new { id, errorMessage = dex.InnerException.InnerException.Message, saveChangesError = true })); } return(RedirectToAction("Index")); }
public ActionResult Remove(int id) { Repair.Remove(UserID, Employee.ID, id); var list = Repair.Find(UserID, Employee.ID, Employee.BussinessID); if (Request.IsAjaxRequest()) { return(Json(new { result = true, html = RenderPartialViewToString(Views.HistoryPartial, list) }, JsonRequestBehavior.AllowGet)); } return(View(Views.History, list)); }
public string Create([Bind(Include = "ID,VendorCaseNo,Description,Comment,IsComplete,RepairCreated,UpdatedOn,RepairClosed,IsBoxRequested,BoxRequestedOn,IsShipped,ShippedOn,IsUnitReturned,ReturnedOn,TabletID,RepairTypeID")] Repair repair) { //if (ModelState.IsValid) //{ // db.Repairs.Add(repair); // db.SaveChanges(); // return RedirectToAction("Index"); //} //ViewBag.RepairTypeID = new SelectList(db.RepairTypes, "ID", "RepairTypeDescription", repair.RepairTypeID); //ViewBag.TabletID = new SelectList(db.Tablets, "ID", "TabletName", repair.TabletID); //ViewBag.TechID = new SelectList(db.Teches, "ID", "FirstName", repair.TechID); //return View(repair); return("Not Implemented"); }
public void NewRepair() { var RepTest = new Repair(2, 1, 1, 2330, "Ceiling Fan", "Dusty", "Open", true); RepTest.Complex_ID = 2331; Assert.Equal(RepTest.ID, 2); Assert.Equal(RepTest.Tenant_ID, 1); Assert.Equal(RepTest.Worker_ID, 1); Assert.Equal(RepTest.Complex_ID, 2331); Assert.Equal(RepTest.Issue, "Ceiling Fan"); Assert.Equal(RepTest.IssueDetails, "Dusty"); Assert.Equal(RepTest.Status, "Open"); Assert.Equal(RepTest.ActiveFlag, true); }
public EditRepairViewModel GetEditedRepair(int id) { Repair repair = this.Context.Repairs.Find(id); var allEmployees = this.Context.Employees.ToList(); EditRepairViewModel viewModel = Mapper.Map <EditRepairViewModel>(repair); foreach (Employee employee in allEmployees) { EmployeeRepairViewModel employeeRepairView = Mapper.Map <EmployeeRepairViewModel>(employee); viewModel.Employees.Add(employeeRepairView); } return(viewModel); }
public EditRepairPage(Repair SelectedBRKDWN) { InitializeComponent(); if (SelectedBRKDWN != null) { _CurrentBreakdown = SelectedBRKDWN; } DataContext = _CurrentBreakdown; ComboBreakdown.ItemsSource = AccountingEquipmentEntities.GetContext().Breakdown.ToList(); InventNumber.ItemsSource = AccountingEquipmentEntities.GetContext().EquipmentCard.ToList(); ComboModel.ItemsSource = AccountingEquipmentEntities.GetContext().Equipment.ToList(); ComboServiceName.ItemsSource = AccountingEquipmentEntities.GetContext().ServiceOrganization.ToList(); ComboStatusRepair.ItemsSource = AccountingEquipmentEntities.GetContext().StatusEquipInRepair.ToList(); ComboFIO.ItemsSource = AccountingEquipmentEntities.GetContext().Worker.ToList(); }
private ISoldier GetEngineer(int id, string firstName, string lastName, decimal salary, Corps corps, string[] comands) { IEngineer solder = new Engineer(id, firstName, lastName, salary, corps); for (int i = 6; i < comands.Length; i += 2) { string part = comands[i]; int hours = int.Parse(comands[i + 1]); IRepair repair = new Repair(part, hours); solder.Repairs.Add(repair); } return(solder); }
public ActionResult ConfirmDelete(string Id) { Repair repairToDelete = context.Find(Id); if (repairToDelete == null) { return(HttpNotFound()); } else { context.Delete(Id); context.Commit(); return(RedirectToAction("Index")); } }
private static IEngineer CreateEngineer(string[] cmdArgs, int id, string firstName, string lastName, decimal salary, string corps) { IEngineer engineer = new Engineer(id, firstName, lastName, salary, corps); string[] repairArgs = cmdArgs.Skip(6).ToArray(); for (int i = 0; i < repairArgs.Length; i += 2) { string partName = repairArgs[i]; int hourWorked = int.Parse(repairArgs[i + 1]); IRepair repair = new Repair(partName, hourWorked); engineer.AddRepair(repair); } return(engineer); }
// GET: Repairs/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Repair repair = db.Repairs.Find(id); if (repair == null) { return(HttpNotFound()); } ViewBag.Custid = new SelectList(db.Customers, "Custid", "Company", repair.Custid); return(View(repair)); }
public void TestsSwap() { var expected = new Repair[] { new Repair("tv", "High"), new Repair("clock","Medium") }; var toSwap = new Repair[] { new Repair("clock","Medium"), new Repair("tv", "High") }; Swap(ref toSwap, 0); CollectionAssert.AreEqual(expected, toSwap); }
public EditRepairWindow(Repair repair, List<Client> clients) { oldRepair = new Repair(repair.id, repair.date, repair.client, repair.pricingDate, repair.state, repair.archive, repair.pricingComment); oldRepair.items = new List<Item>(repair.items.Count); foreach (Item item in repair.items) oldRepair.items.Add(new Item(item.repairId, item.id, item.type, item.item, item.description, item.price, item.decision, item.decisionDate, item.receiver, item.receiveDate, item.fabrnum)); actualRepair = repair; actualItem = repair.items[0]; InitializeComponent(); init(clients); }
public ActionResult Create() { int id = 1; Repair repair = this._repairService.GetTop <int>(1, (Repair x) => x.RepairCode != null, (Repair x) => x.Id).FirstOrDefault <Repair>(); if (repair != null) { id = repair.Id; } return(base.View(new RepairViewModel() { RepairCode = string.Concat("DH", id.ToString()), CustomerCode = string.Concat("KH", id.ToString()) })); }
private void BtnSaveRepair_Click(object sender, RoutedEventArgs e) { if (txtVIN.Text == "") { MessageBox.Show("VIN Field cannot be blank"); } else if ((chkNewCustomer.IsChecked == true) && (txtFirstName.Text == "")) { MessageBox.Show("First Name field cannot be blank"); } else if ((chkNewCustomer.IsChecked == true) && (txtLastName.Text == "")) { MessageBox.Show("Last Name field cannot be blank"); } else if ((chkNewCustomer.IsChecked == true) && (txtAddress.Text == "")) { MessageBox.Show("Address field cannot be blank"); } else if ((chkNewCustomer.IsChecked == true) && (txtEmailAddress.Text == "")) { MessageBox.Show("Email Address field cannot be blank"); } else if ((chkNewCustomer.IsChecked == true) && (txtPhoneNumber.Text == "")) { MessageBox.Show("Phone Number field cannot be blank"); } else if (txtDescription.Text == "") { MessageBox.Show("Description field cannot be blank"); } else { repair = new Repair(0, txtDescription.Text, 0, 0, DateTime.Now, 0, txtVIN.Text, _lineItems); if (chkNewCustomer.IsChecked == true) { customer = new Customer(txtFirstName.Text, txtLastName.Text, txtAddress.Text, 0, txtEmailAddress.Text, txtPhoneNumber.Text); } else { customer = _customers[cboCustomers.SelectedIndex]; } saved = true; this.Close(); } }
public ActionResult Edit(TabletRepairViewModel tabletRepair) { Repair repair = tabletRepair; try { if (ModelState.IsValid) { // var problemsToAdd = db.ProblemAreas.Where(p => tabletRepair.AssignedProblems.Contains(p.ID)).ToList(); repair.ProblemAreas = new HashSet <ProblemArea>(); db.Entry(repair).State = EntityState.Modified; db.Entry(repair).Collection(p => p.ProblemAreas).Load(); db.Entry(repair).Collection(p => p.PartOrders).Load(); foreach (var partOrder in repair.PartOrders) { partOrder.IsPartReceived = tabletRepair.PartOrders.Where(p => p.ID == partOrder.ID).Select(p => p.IsPartReceived).SingleOrDefault(); partOrder.ReceivedOn = tabletRepair.PartOrders.Where(p => p.ID == partOrder.ID).Select(p => p.ReceivedOn).SingleOrDefault(); } repair.ProblemAreas = db.ProblemAreas.Where(p => tabletRepair.AssignedProblems.Contains(p.ID)).ToList(); db.SaveChanges(); return(RedirectToAction("Index")); } } catch (DbUpdateConcurrencyException) { //This is implemented by a virtue of having "RowVersion" field in our model and database. watch this video for details: https://youtu.be/Gi_kEbc5faQ ModelState.AddModelError(string.Empty, $"The record you were trying to update was modified by another user. Please go back and try again."); } catch (DataException dex) { if (dex.InnerException.InnerException.Message.Contains("IX_VendorCaseNo")) { ModelState.AddModelError("VendorCaseNo", "Unable to save changes. Vendor Case No. must be unique"); } else { ModelState.AddModelError(string.Empty, $"Database Error occured Copy the error message and send it to Dima </br>: {dex.Message}. + {dex.InnerException.Message} + {dex.InnerException.InnerException.Message}"); } } catch (Exception ex) { ModelState.AddModelError(string.Empty, $"Unexpected error occured. Copy the error message and send it to Dima {ex.Message} | {ex.InnerException.InnerException.Message}" + $"{ex.InnerException.InnerException.Message}"); } return(View(tabletRepair)); }
public ActionResult CreateLineItems2(string data) { try { //Declare variables Repair repair = (Repair)Session["repair"]; List <string> serialNumbers = data.Split(',').ToList(); List <PartVM> parts = _partsManager.getAllParts(); //Add line items to the repair foreach (string serialNumber in serialNumbers) { Part part = parts.Find(x => x.SerialNumber == serialNumber); repair.LineItems.Add(new RepairLineItem() { SerialNumber = part.SerialNumber, Amount = part.Cost, Type = part.PartType }); } //Create a new bill Bill bill = new Bill() { CustomerID = repair.CustomerID, AmountDue = repair.getAmount(), AmountPaid = 0M, IssueDate = DateTime.Now, DueDate = DateTime.Now.AddDays(30), LineItems = new List <BillingLineItem>() }; bill.LineItems.Add(new BillingLineItem() { Amount = repair.getAmount() }); //Add everything to the database _billingManager.newBill(bill); repair.BillingLineItemID = _billingManager.getLastestBillingLineItem(); _repairsManager.addNewRepair(repair); return(RedirectToAction("Index")); } catch (Exception ex) { return(Redirect("~/Home/Error?error=" + ex.Message)); } }
// PUT api/repairs/5 public void Put(int id, [FromBody] dynamic repair) { string SerialNumber = repair.SerialNumber; string Assignee = repair.Assignee; string Note = repair.Note; bool repairCompleted = repair.Completed == "True"; AuleaseEntities db = new AuleaseEntities(); bool completedRepair = db.Components.Where(n => n.SerialNumber == SerialNumber).Single() .Repairs.OrderByDescending(n => n.Timestamp).FirstOrDefault().Status.Id == Status.CompletedRepair; if (completedRepair) { return; } if (!repairCompleted) { // Repair Info Update if (db.Components.Any(n => n.SerialNumber == SerialNumber)) { Component comp = db.Components.Where(n => n.SerialNumber == SerialNumber).Single(); Repair CurrentRepair = comp.Repairs.OrderByDescending(n => n.Timestamp).FirstOrDefault(); CurrentRepair.Assignee = Assignee; CurrentRepair.Note = Note; db.SaveChanges(); } } else { // Close Ticket if (db.Components.Any(n => n.SerialNumber == SerialNumber)) { Component comp = db.Components.Where(n => n.SerialNumber == SerialNumber).Single(); Repair CurrentRepair = comp.Repairs.OrderByDescending(n => n.Timestamp).FirstOrDefault(); CurrentRepair.Assignee = Assignee; CurrentRepair.Note = Note; CurrentRepair.Status = db.Status.Where(n => n.Id == Status.CompletedRepair).Single(); db.SaveChanges(); } } }
//tested private static IEnumerable <Repair> ParseRepairs(string[] input) { IList <Repair> result = new List <Repair>(); for (int i = 6; i < input.Length; i++) { var name = input[i]; i++; var worked = int.Parse(input[i]); var repair = new Repair(name, worked); result.Add(repair); } return(result); //tested }
public RepairDto Save(RepairDto repairDto) { Repair repair = _mapper.Map <Repair>(repairDto); repair.Car.Repair = repair; repair.StatusEntity = _carMechanicContext.StatusEntities.SingleOrDefault(x => x.Status == Status.AddedForService); repair.Car.Type = _carMechanicContext.CarTypes.SingleOrDefault(x => x.Model == repairDto.Car.Type.Model && x.TypeName == repair.Car.Type.TypeName) ?? _mapper.Map <CarType>(repairDto.Car.Type); _carMechanicContext.Repairs.Add(repair); _carMechanicContext.SaveChanges(); RepairDto dto = _mapper.Map <RepairDto>(repair); return(dto); }
// GET: Repairs/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Repair repair = db.Repair.Find(id); if (repair == null) { return(HttpNotFound()); } ViewBag.MechanicID = new SelectList(db.Mechanic, "MechanicID", "FirstName", repair.MechanicID); ViewBag.VehicleID = new SelectList(db.Vehicle, "VehicleID", "VIN", repair.VehicleID); return(View(repair)); }
public bool Delete(int repairId) { try { Repair repair = new Repair(); var repairID = _bheUOW.RepairRepository.Delete(repairId); _bheUOW.SaveChanges(); return(true); } catch (Exception ex) { ExceptionHandler exceptionHandler = new ExceptionHandler(); exceptionHandler.WrapLogException(ex); throw ex; } }
public async Task <IActionResult> Edit(Repair repair) { await GetSelected(); var model = new RepairUpdateDTO { Id = repair.Id, MasterId = repair.MasterId, OwnerId = repair.OwnerId, RepairStatusId = repair.RepairStatusId, Result = repair.Result, Сause = repair.Сause }; return(View(model)); }
public void AddRepair(AddRepairViewModel data) { LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name); s.Restart(); Repair repair = new Repair(); repair.Acceptance = data.Repair.DateOfAcceptance; repair.CreateTime = DateTime.Now; repair.RepairDetail = data.Repair.DamageDescription; repair.DeviceId = getDeviceId(data); _context.Entry(repair).State = EntityState.Added; _context.SaveChanges(); s.Stop(); LoggerController.AddEndMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds); }
public void AttachRepair(Organisation org, int idDev, Repair rep) { organisation = new Organisation(); { foreach (Organisation item in organisations) { foreach (Computer comps in item.devices) { if (comps.Id == idDev) { item.repairs.Add(rep); } } } } }
// GET: Repairs/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Repair repair = db.Repairs.Find(id); if (repair == null) { return(HttpNotFound()); } ViewBag.EmployeeId = new SelectList(db.Employees, "EmployeeId", "Name", repair.EmployeeId); ViewBag.MotorCycleId = new SelectList(db.Motorcycles, "MotorCycleId", "MotorCycleName", repair.MotorCycleId); return(View(repair)); }
public IActionResult Add(Repair r) { if (ModelState.IsValid) { Vehicle v = _vehicleRepository.GetVehicleById(r.VehicleId); if (r.VehicleMileage > v.Mileage) { v.Mileage = r.VehicleMileage; } _repository.CreateRepair(r); return(RedirectToAction("ListRepairs", new { vehicleId = r.VehicleId })); } return(View(r)); }//End Add() [Post]
public ActionResult Create([Bind(Include = "ID,RepairType,VendorCaseNo,RepairDescription,Comment,IsComplete,RepairCreated,UpdatedOn,RepairClosed,IsBoxRequested,BoxRequestedOn,IsShipped,ShippedOn,ReturnedOn,TabletID,TechID")] Repair repair) { if (ModelState.IsValid) { repair.UpdatedOn = DateTime.Now; repair.CreatedOn = DateTime.Now; repair.IsClosed = false; db.Repairs.Add(repair); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.TabletID = new SelectList(db.Tablets, "ID", "TabletName", repair.TabletID); // ViewBag.TechID = new SelectList(db.Teches, "ID", "FirstName", repair.TechID); return(View(repair)); }
public static RepairDto Convert(Repair repair) { if (repair == null) { return(null); } RepairDto repairDto = new RepairDto(); repairDto.CodeMachine = repair.CodeMachine; repairDto.IDRepair = Convert(DaoFactory.GetNameRepairDao().Get(repair.IDRepair)); repairDto.Note = repair.Note; repairDto.StartDate = repair.StartDate; return(repairDto); }
private static void TryCreateEnginner(List <ISoldier> soldiers, string[] inputParams) { Engineer engineer = new Engineer(inputParams[1], inputParams[2], inputParams[3], double.Parse(inputParams[4]), inputParams[5]); int numberOfRepairs = (inputParams.Length - 5) / 2; for (int i = 0; i < numberOfRepairs; i++) { Repair repair = new Repair(inputParams[6 + (i * 2)], int.Parse(inputParams[7 + (i * 2)])); engineer.AddRepair(repair); } soldiers.Add(engineer); }
// GET: Repairs/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Repair repair = db.Repairs.Find(id); if (repair == null) { return(HttpNotFound()); } //ViewBag.TabletID = new SelectList(db.Tablets, "ID", "TabletName", repair.TabletID); // ViewBag.TechID = new SelectList(db.Teches, "ID", "FirstName", repair.TechID); return(View(repair)); }
public static List <Repair> GetRepairs(List <string> repairArgs) { List <Repair> repairs = new List <Repair>(); for (int i = 0; i < repairArgs.Count; i += 2) { string partName = repairArgs[i]; int hoursWorked = int.Parse(repairArgs[i + 1]); Repair repair = new Repair(partName, hoursWorked); repairs.Add(repair); } return(repairs); }
public int Add(RepairDTO repairDTO) { try { Repair entity = RepairMapper.Map(repairDTO); _bheUOW.RepairRepository.Add(entity); _bheUOW.SaveChanges(); return(entity.Id); } catch (Exception ex) { ExceptionHandler exceptionHandler = new ExceptionHandler(); exceptionHandler.WrapLogException(ex); throw ex; } }
protected void btAdjustCln_Click(object sender, EventArgs e) { if (selectedRepair == null) { DateTime date = ClDateRep.SelectedDate; DateTime estimate = ClDateDoneRep.SelectedDate; Tram tram = service.GetTram(Convert.ToInt32(tbTramNrRep.Text)); User user = null; string description = tbDescrRep.Text; foreach (User u in service.Users) { if (u.Name == ddlUserRep.SelectedItem.Text) { user = u; break; } } selectedRepair = new Repair(0, date, " - ", tram, user, estimate, description); service.InsertRepair(selectedRepair); } else { int repairId = selectedRepair.Id; DateTime date = ClDateRep.SelectedDate; DateTime estimate = ClDateDoneRep.SelectedDate; Tram tram = service.GetTram(Convert.ToInt32(tbTramNrRep.Text)); User user = null; string description = tbDescrRep.Text; foreach (User u in service.Users) { if (u.Name == ddlUserRep.SelectedItem.Text) { user = u; break; } } selectedRepair = new Repair(repairId, date, " - ", tram, user, estimate, description); service.UpdateRepair(selectedRepair); } }
[DataObjectMethod(DataObjectMethodType.Select)] //annotate data object select method public static List<Repair> GetRepairsByTechnician(string technician) { List<Repair> RepairsList = new List<Repair>(); SqlConnection connect = new SqlConnection(AppRepairsDB.GetConnectionString()); string select = "SELECT RepairID, DateReported, Title, Description, CustomerID, ProductCode, DateRepaired " + "FROM Repairs " + "WHERE TechID = @TechID " + "ORDER BY DateReported"; SqlCommand command = new SqlCommand(select, connect); command.Parameters.AddWithValue("TechID", technician); connect.Open(); SqlDataReader dr = command.ExecuteReader(); //temp objects for iteration Repair i; DateTime dt = new DateTime(); DateTime? nullableDT = new DateTime?(); while (dr.Read()) { i = new Repair(); i.RepairID = (int)dr["RepairID"]; i.DateReported = (DateTime)dr["DateReported"]; i.Title = dr["Title"].ToString(); i.Description = dr["Description"].ToString(); i.CustomerID = (int)dr["CustomerID"]; i.ProductCode = dr["ProductCode"].ToString(); string date = dr["DateRepaired"].ToString(); if (DateTime.TryParse(date, out dt)) { nullableDT = dt; i.DateRepaired = nullableDT; } else { i.DateRepaired = null; } RepairsList.Add(i); } connect.Close(); return RepairsList; }
public static int UpdateRepair(Repair original_Repair, Repair Repair) { int count = 0; //counter for how many rows get updated SqlConnection connect = new SqlConnection(AppRepairsDB.GetConnectionString()); string update = "UPDATE Repairs " + "SET DateRepaired = @newDateRepaired, " + "Description = @newDescription " + "WHERE RepairID = @original_RepairID " + //concurrency "AND ProductCode = @original_ProductCode " + "AND DateReported = @original_DateReported " + "AND (DateRepaired = @original_DateRepaired " + "OR DateRepaired IS NULL " + "AND @original_DateRepaired IS NULL) " + "AND Title = @original_Title " + "AND Description = @original_Description"; SqlCommand cmd = new SqlCommand(update, connect); //deal with null dates if (Repair.DateRepaired.HasValue) cmd.Parameters.AddWithValue("newDateRepaired", Repair.DateRepaired); else cmd.Parameters.AddWithValue("newDateRepaired", DBNull.Value); cmd.Parameters.AddWithValue("newDescription", Repair.Description); cmd.Parameters.AddWithValue("original_RepairID", original_Repair.RepairID); cmd.Parameters.AddWithValue("original_ProductCode", original_Repair.ProductCode); cmd.Parameters.AddWithValue("original_DateReported", original_Repair.DateReported); //deal with null dates from the original_Repair object if (original_Repair.DateRepaired.HasValue) cmd.Parameters.AddWithValue("original_DateRepaired", original_Repair.DateRepaired); else cmd.Parameters.AddWithValue("original_DateRepaired", DBNull.Value); cmd.Parameters.AddWithValue("original_Title", original_Repair.Title); cmd.Parameters.AddWithValue("original_Description", original_Repair.Description); connect.Open(); count = cmd.ExecuteNonQuery(); //run the update as the count connect.Close(); return count; }
public void TestsTheSortForASevenElementStruct() { var toSort = new Repair[] { new Repair("watch","Medium"), new Repair("tv", "High"), new Repair("clock","Medium"), new Repair("lamp","High"), new Repair("toothbrush","Low"), new Repair("radio", "Low"), new Repair("stove","Medium"), }; var expected = new Repair[] { new Repair("tv", "High"), new Repair("lamp","High"), new Repair("watch","Medium"), new Repair("clock","Medium"), new Repair("stove","Medium"), new Repair("toothbrush","Low"), new Repair("radio", "Low") }; CollectionAssert.AreEqual(expected, SortRepairs(toSort)); }
/// <summary> /// Run in single processing mode for the unique identifier. /// </summary> /// <param name="Options">The collection of options.</param> /// <param name="UniqueIdentifier">The unique identifier.</param> public static void Single(Options Options, string UniqueIdentifier) { // Select the provider. IProvider Provider = _Providers.FirstOrDefault(x => x.Open(UniqueIdentifier) != null); // Check if the provider is valid. if (Provider != null) { // Initialize the series. using (ISeries Series = Provider.Open(UniqueIdentifier)) { // Populate the series. using (Series.Populate()) { // Initialize the series title. string Title = Series.Title.InvalidatePath(); // Initialize the persistence. List<string> Persistence = new List<string>(); // Initialize the persistence file path. string PersistencePath = Path.Combine(Title, ".mangarack-persist"); // Check if persistent synchronization tracking is enabled and a tracking file is available. if (File.Exists(PersistencePath)) { // Iterate through each line in the persistence file. foreach (string Line in File.ReadAllLines(PersistencePath)) { // Add the line to the persistence file names. Persistence.Add(Line); } } // Iterate through each chapter using the chapter and volume filters. foreach (IChapter Chapter in Series.Children.Filter(Options)) { // Initialize whether sychronization has failed. bool HasFailed = false; // Initialize the file name. string FileName = string.Format(Chapter.Volume == -1 ? "{0} #{2}.{3}" : "{0} V{1} #{2}.{3}", Title, Chapter.Volume.ToString("00"), Chapter.Number.ToString("000.####"), Options.FileExtension.InvalidatePath()); // Initialize the file path. string FilePath = Path.Combine(Title, FileName); // Check if persistent synchronization tracking is enabled and the file name is persisted. if (Persistence.Contains(FileName)) { // Continue to the next chapter. continue; } else { // Add the file name to the persistence file names. Persistence.Add(FileName); } // Do the following code. do { // Check if the file should be synchronized. if (Options.DisableDuplicationPrevention || !File.Exists(FilePath)) { // Populate the chapter. using (Chapter.Populate()) { // Initialize a new instance of the Publisher class. using (Publisher Publisher = new Publisher(FilePath, Options, Provider)) { // Initialize a new instance of the Synchronizer class. using (Synchronize Synchronizer = new Synchronize(Publisher, Series, Chapter)) { // Populate synchronously. Synchronizer.Populate(); // Set whether synchronization has failed. HasFailed = false; } } } } else { // Check if a meta-information overwrite should be performed. if (Options.EnableOverwriteMetaInformation) { // Initialize the comic information. ComicInfo ComicInfo = new ComicInfo(), PreviousComicInfo = null; // Initialize a new instance of the ZipFile class. using (ZipFile ZipFile = new ZipFile(FilePath)) { // Find the comic information. ZipEntry ZipEntry = ZipFile.GetEntry("ComicInfo.xml"); // Check if comic information is available. if (ZipEntry != null) { // Load the comic information. PreviousComicInfo = ComicInfo.Load(ZipFile.GetInputStream(ZipEntry)); // Transcribe the series, chapter and pages information. ComicInfo.Transcribe(Series, Chapter, PreviousComicInfo.Pages); // Check if a current genre differs ... if (ComicInfo.Genre.Any(x => !PreviousComicInfo.Genre.Contains(x)) || // ... or if a previous genre differs ... PreviousComicInfo.Genre.Any(x => !ComicInfo.Genre.Contains(x)) || // ... or the manga specification differs ... ComicInfo.Manga != PreviousComicInfo.Manga || // ... or the number differs ... ComicInfo.Number != PreviousComicInfo.Number || // ... or if the page count differs ... ComicInfo.PageCount != PreviousComicInfo.PageCount || // ... or if a current penciller difffers ... ComicInfo.Penciller.Any(x => !PreviousComicInfo.Penciller.Contains(x)) || // ... or if a previous penciller difffers ... PreviousComicInfo.Penciller.Any(x => !ComicInfo.Penciller.Contains(x)) || // ... or if the series differs ... ComicInfo.Series != PreviousComicInfo.Series || // ... or if the summary differs ... ComicInfo.Summary != PreviousComicInfo.Summary || // ... or if the title differs ... ComicInfo.Title != PreviousComicInfo.Title || // ... or if the volume differs ... ComicInfo.Volume != PreviousComicInfo.Volume || // ... or if a current writer differs. ComicInfo.Writer.Any(x => !PreviousComicInfo.Writer.Contains(x)) || // ... or if a previous writer differs. PreviousComicInfo.Writer.Any(x => !ComicInfo.Writer.Contains(x))) { // Initialize a new instance of the MemoryStream class. using (MemoryStream MemoryStream = new MemoryStream()) { // Save the comic information. ComicInfo.Save(MemoryStream); // Rewind the stream. MemoryStream.Position = 0; // Begin updating the compressed file. ZipFile.BeginUpdate(); // Add the file. ZipFile.Add(new DataSource(MemoryStream), "ComicInfo.xml"); // End updating the compressed file. ZipFile.CommitUpdate(); // Write a message. Console.WriteLine("Modified {0}", FileName); } } } } } // Check if a repair should be performed. if (!Options.DisableRepairAndErrorTracking && File.Exists(string.Format("{0}.txt", FilePath))) { // Populate the chapter. using (Chapter.Populate()) { // Initialize the comic information. ComicInfo ComicInfo = null; // Initialize whether there are broken pages. bool HasBrokenPages = false; // Initialize a new instance of the ZipFile class. using (ZipFile ZipFile = new ZipFile(FilePath)) { // Find the comic information. ZipEntry ZipEntry = ZipFile.GetEntry("ComicInfo.xml"); // Check if comic information is available. if (ZipEntry == null) { // Stop the function. return; } else { // Load the comic information. ComicInfo = ComicInfo.Load(ZipFile.GetInputStream(ZipEntry)); } } // Initialize a new instance of the Publisher class. using (Publisher Publisher = new Publisher(FilePath, Options, Provider, true)) { // Initialize a new instance of the Repair class. using (Repair Repair = new Repair(Publisher, Series, Chapter, ComicInfo, File.ReadAllLines(string.Format("{0}.txt", FilePath)))) { // Populate synchronously. Repair.Populate(); // Set whether there are broken pages. HasBrokenPages = Publisher.HasBrokenPages; // Set whether synchronization has failed. HasFailed = Publisher.HasFailed = Repair.HasFailed; } } // Check if there are no broken pages. if (!HasBrokenPages && File.Exists(string.Format("{0}.txt", FilePath))) { // Delete the error file. File.Delete(string.Format("{0}.txt", FilePath)); } } } } } while (HasFailed); // Check if persistent synchronization tracking is enabled. if (Options.EnablePersistentSynchronization) { // Write each line to the persistence file path. File.WriteAllLines(PersistencePath, Persistence.ToArray()); } } } } } }
public Repair LoadRepair(int repairId) { string sql = "SELECT * FROM TRAM_ONDERHOUD WHERE \"TypeOnderhoud\" = 'REPARATIE' AND \"Id\" = :id"; OracleCommand command = new OracleCommand(sql, conn); command.Parameters.Add("id", repairId); Repair repair = null; int id = -1; DateTime date; DateTime estimate; string type; Tram tram; int tramId; int userId; string description; try { if (conn.State == ConnectionState.Closed) { conn.Open(); } OracleDataReader reader = command.ExecuteReader(); while (reader.Read()) { id = Convert.ToInt32(reader["ID"]); date = Convert.ToDateTime(reader["DatumTijdstip"]); estimate = Convert.ToDateTime(reader["BeschikbaarDatum"]); type = Convert.ToString(reader["TypeOnderhoud"]); tramId = Convert.ToInt32(reader["Tram_ID"]); userId = Convert.ToInt32(reader["Medewerker_ID"]); description = Convert.ToString(reader["Beschrijving"]); repair = new Repair(id, date, type, new Tram(tramId, tramId), new User(userId, "", "", ""), estimate, description); break; } reader.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); } repair.Tram = GetTram(repair.Tram.Id); repair.User = GetUser(repair.User.Id); return repair; }
/// <summary> /// Run in single processing mode for the location. /// </summary> /// <param name="location">The location.</param> /// <param name="options">The collection of options.</param> public static void Single(string location, Options options) { var provider = Providers.FirstOrDefault(x => x.Open(location) != null); if (provider == null) return; using (var series = provider.Open(location)) { using (series.Populate()) { var seriesTitle = series.Title.InvalidatePath(); var persistencePath = Path.Combine(seriesTitle, ".mangarack-persist"); var persistence = new List<List<string>>(); if (File.Exists(persistencePath)) { const int persistenceVersion = 2; foreach (var pieces in File.ReadAllLines(persistencePath).Select(line => new List<string>(line.Split('\0')))) { while (pieces.Count < persistenceVersion) pieces.Add(string.Empty); persistence.Add(pieces); } } foreach (var chapter in series.Children) { var line = persistence.FirstOrDefault(x => string.Equals(x[1], chapter.UniqueIdentifier)); if (line == null) continue; var currentFilePath = Path.Combine(seriesTitle, line[0]); var nextFileName = chapter.ToFileName(seriesTitle, options); if (!string.Equals(line[0], nextFileName) && File.Exists(currentFilePath)) { File.Move(currentFilePath, Path.Combine(seriesTitle, nextFileName)); line[0] = nextFileName; Persist(persistencePath, persistence); Console.WriteLine("Switched {0}", nextFileName); } } foreach (var chapter in series.Children.Filter(options)) { var hasFailed = false; var fileName = chapter.ToFileName(seriesTitle, options); var filePath = Path.Combine(seriesTitle, fileName); var persistenceFile = persistence.FirstOrDefault(x => string.Equals(x[0], fileName)); if (options.EnablePersistentSynchronization && persistenceFile != null) { continue; } if (persistenceFile != null) { persistenceFile[1] = chapter.UniqueIdentifier ?? string.Empty; } else { persistence.Add(new List<string> {fileName, chapter.UniqueIdentifier ?? string.Empty}); } do { if (options.DisableDuplicationPrevention || !File.Exists(filePath)) { using (chapter.Populate()) { using (var publisher = new Publisher(filePath, options, provider)) { using (var synchronizer = new Synchronize(publisher, series, chapter)) { synchronizer.Populate(); hasFailed = false; } } } } else { if (options.EnableOverwriteMetaInformation) { var comicInfo = new ComicInfo(); using (var zipFile = new ZipFile(filePath)) { var zipEntry = zipFile.GetEntry("ComicInfo.xml"); if (zipEntry != null) { var previousComicInfo = ComicInfo.Load(zipFile.GetInputStream(zipEntry)); comicInfo.Transcribe(series, chapter, previousComicInfo.Pages); if (comicInfo.Genre.Any(x => !previousComicInfo.Genre.Contains(x)) || previousComicInfo.Genre.Any(x => !comicInfo.Genre.Contains(x)) || comicInfo.Manga != previousComicInfo.Manga || comicInfo.Number != previousComicInfo.Number || comicInfo.PageCount != previousComicInfo.PageCount || comicInfo.Penciller.Any(x => !previousComicInfo.Penciller.Contains(x)) || previousComicInfo.Penciller.Any(x => !comicInfo.Penciller.Contains(x)) || comicInfo.Series != previousComicInfo.Series || comicInfo.Summary != previousComicInfo.Summary || comicInfo.Title != previousComicInfo.Title || comicInfo.Volume != previousComicInfo.Volume || comicInfo.Writer.Any(x => !previousComicInfo.Writer.Contains(x)) || previousComicInfo.Writer.Any(x => !comicInfo.Writer.Contains(x))) { using (var memoryStream = new MemoryStream()) { comicInfo.Save(memoryStream); memoryStream.Position = 0; zipFile.BeginUpdate(); zipFile.Add(new DataSource(memoryStream), "ComicInfo.xml"); zipFile.CommitUpdate(); Console.WriteLine("Modified {0}", fileName); } } } } } if (!options.DisableRepairAndErrorTracking && File.Exists(string.Format("{0}.txt", filePath))) { using (chapter.Populate()) { ComicInfo comicInfo; var hasBrokenPages = false; using (var zipFile = new ZipFile(filePath)) { var zipEntry = zipFile.GetEntry("ComicInfo.xml"); if (zipEntry == null) { return; } comicInfo = ComicInfo.Load(zipFile.GetInputStream(zipEntry)); } using (var publisher = new Publisher(filePath, options, provider, true)) { using (var repair = new Repair(publisher, chapter, comicInfo, File.ReadAllLines(string.Format("{0}.txt", filePath)))) { repair.Populate(); hasBrokenPages = publisher.HasBrokenPages; hasFailed = publisher.HasFailed = repair.HasFailed; } } if (!hasBrokenPages && File.Exists(string.Format("{0}.txt", filePath))) { File.Delete(string.Format("{0}.txt", filePath)); } } } } } while (hasFailed); Persist(persistencePath, persistence); } } } }
public void UpdateRepair(Repair repair) { database.UpdateRepair(repair); }
public void UpdateRepair(Repair repair) { string sql = "UPDATE TRAM_ONDERHOUD SET \"Medewerker_ID\" = :userid, \"Tram_Id\" = :tramid, \"DatumTijdstip\" = :date, \"BeschikbaarDatum\" = :estimate, \"Beschrijving\" = :description WHERE \"ID\" = :id"; OracleCommand command = new OracleCommand(sql, conn); command.Parameters.Add("id", repair.Id); command.Parameters.Add("userid", repair.User.Id); command.Parameters.Add("tramid", repair.Tram.Id); command.Parameters.Add("date", repair.Date); command.Parameters.Add("estimate", repair.Estimate); command.Parameters.Add("description", repair.Description); NonQueryBase(command); }
public void CompleteRepair(Repair repair) { database.RemoveRepair(repair); }
public void InsertRepair(Repair repair) { database.InsertRepair(repair); }
public void InsertRepair(Repair repair) { string sql = "INSERT INTO TRAM_ONDERHOUD(\"Medewerker_ID\", \"Tram_ID\", \"DatumTijdstip\", \"BeschikbaarDatum\", \"TypeOnderhoud\", \"Beschrijving\") VALUES (:userid, :tramid, :datetime, :estimate, 'REPARATIE', :description)"; OracleCommand command = new OracleCommand(sql, conn); command.Parameters.Add("userid", repair.User.Id); command.Parameters.Add("tramid", repair.Tram.Id); command.Parameters.Add("datetime", repair.Date); command.Parameters.Add("estimate", repair.Estimate); command.Parameters.Add("description", repair.Description); NonQueryBase(command); }
/// <summary> /// Run in single processing mode for the unique identifier. /// </summary> /// <param name="Options">The collection of options.</param> /// <param name="UniqueIdentifier">The unique identifier.</param> public static void Single(Options Options, string UniqueIdentifier) { // Select the provider. IProvider Provider = _Providers.FirstOrDefault(x => x.Open(UniqueIdentifier) != null); // Check if the provider is valid. if (Provider != null) { // Initialize the series. using (ISeries Series = Provider.Open(UniqueIdentifier)) { // Populate the series. using (Series.Populate()) { // Initialize the series title. string Title = Series.Title.InvalidatePath(); // Iterate through each chapter using the chapter and volume filters. foreach (IChapter Chapter in Series.Children.Filter(Options)) { // Initialize the file path. string FilePath = Path.Combine(Title, string.Format(Chapter.Volume == -1 ? "{0} #{2}.{3}" : "{0} V{1} #{2}.{3}", Title, Chapter.Volume.ToString("00"), Chapter.Number.ToString("000.####"), Options.FileExtension.InvalidatePath())); // Check if the file should be synchronized. if (Options.DisableDuplicationPrevention || !File.Exists(FilePath)) { // Populate the chapter. using (Chapter.Populate()) { // Initialize a new instance of the Publisher class. using (Publisher Publisher = new Publisher(FilePath, Options, Provider)) { // Initialize a new instance of the Synchronizer class. using (Synchronize Synchronizer = new Synchronize(Publisher, Series, Chapter)) { // Populate synchronously. Synchronizer.Populate(); } } } } else if (!Options.DisableRepairAndErrorTracking && File.Exists(string.Format("{0}.txt", FilePath))) { // Populate the chapter. using (Chapter.Populate()) { // Initialize the comic information. ComicInfo ComicInfo = null; // Initialize whether there are broken pages. bool HasBrokenPages = false; // Initialize whether repairing has failed. bool HasFailed = false; // Initialize a new instance of the ZipFile class. using (ZipFile ZipFile = new ZipFile(FilePath)) { // Find the comic information. ZipEntry ZipEntry = ZipFile.GetEntry("ComicInfo.xml"); // Check if comic information is available. if (ZipEntry == null) { // Stop the function. return; } else { // Load the comic information. ComicInfo = ComicInfo.Load(ZipFile.GetInputStream(ZipEntry)); } } // Initialize a new instance of the Publisher class. using (Publisher Publisher = new Publisher(FilePath, Options, Provider, true)) { // Initialize a new instance of the Repair class. using (Repair Repair = new Repair(Publisher, Series, Chapter, ComicInfo, File.ReadAllLines(string.Format("{0}.txt", FilePath)))) { // Populate synchronously. Repair.Populate(); // Set whether there are broken pages. HasBrokenPages = Publisher.HasBrokenPages; // Set whether repairing has failed. HasFailed = Publisher.HasFailed = Repair.HasFailed; } } // Check if there are no broken pages. if (!HasBrokenPages) { // Delete the error file. File.Delete(string.Format("{0}.txt", FilePath)); } // Check if repairing has failed. if (HasFailed) { // Run in single processing mode for the unique identifier. Single(Options, UniqueIdentifier); } } } } } } } }
static void Swap(ref Repair[] toSort, int position) { Repair temp = toSort[position]; toSort[position] = toSort[position + 1]; toSort[position + 1] = temp; }
public void RemoveRepair(Repair repair) { string sql = "DELETE FROM TRAM_ONDERHOUD WHERE \"ID\" = :id)"; OracleCommand command = new OracleCommand(sql, conn); command.Parameters.Add("id", repair.Id); NonQueryBase(command); }
public void TestsTheSortForAThreeElementStruct() { var expected = new Repair[] { new Repair("tv", "High"), new Repair("clock","Medium"), new Repair("radio", "Low") }; var toSort = new Repair[] { new Repair("clock","Medium"), new Repair("tv", "High"), new Repair("radio", "Low") }; CollectionAssert.AreEqual(expected, SortRepairs(toSort)); }