public async Task <ActionResult> Create(BookViewModel model) { if (ModelState.IsValid) { bool existed = CheckISBNExisted(model.ISBN); if (existed) { ModelState.AddModelError("", "The ISBN exists!"); return(View()); } if (model.UploadedCoverFile != null) { var image = model.UploadedCoverFile; model.Cover = new byte[image.ContentLength]; image.InputStream.Read(model.Cover, 0, image.ContentLength); } var bookCommand = new BookCommand(); bool result = await bookCommand.ExecuteAsync(model); if (!result) { ModelState.AddModelError("", ""); return(View()); } return(RedirectToAction("Index")); } return(View()); }
public void Add(BookCommand bookCommand) { Book book = Book.FromBookCommand(bookCommand); _booksValidator.Validate(book); _booksRepository.Add(book); }
public void Update(BookCommand bookCommand) { Title = bookCommand.Title; ISBN = bookCommand.ISBN; LaunchYear = bookCommand.LaunchYear; Author = bookCommand.Author; Category = bookCommand.Category; }
private IActionResult Result(BookCommand request, Result result) { if (result.HasErrors) { result.Errors.ToList().ForEach(err => ModelState.AddModelError(string.Empty, err)); return(View(request)); } return(RedirectToAction(nameof(Index))); }
public async Task <ActionResult> Book( TimeJson req) { if (!req.Valid) { _log.LogWarning("Rejected input {input}", req); return(BadRequest()); } var getTime = new GetTime( sub: GetUserId(), host: req.Host, start: req.Start ); var getTimeResult = (await _db.Submit(_creds, getTime)) .SingleOrDefault(); if (getTimeResult == null) { return(NotFound()); } var conflictsQuery = new GetBookingConflict( sub: GetUserId(), host: getTimeResult.Host, start: getTimeResult.Start, end: getTimeResult.End ); var conflictsResult = (await _db.Submit(_creds, conflictsQuery)) .SingleOrDefault(); if (conflictsResult == null) { var book = new BookCommand( sub: GetUserId(), host: getTimeResult.Host, start: getTimeResult.Start ); var r = await _db.Submit(_creds, book); return(Created( $"bookings/{getTimeResult.Start}", r.Select(x => new TimeJson { Host = x.Host, Name = x.Name, Start = x.Start, Dur = (int)((x.End - x.Start) / 60) }).Single())); } else { return(Conflict(conflictsResult)); } }
public void Book(BookCommand command) { var roomAvailability = roomAvailabilityStore.LoadForRoom(command.RoomId); if (roomAvailability != null) { if (roomAvailability.Book(command.CustomerId, command.Quantity)) { roomAvailabilityStore.Save(roomAvailability); } } }
public IActionResult Add([FromBody] BookCommand bookCommand) { try { _booksWorkflow.Add(bookCommand); return(Ok()); } catch (ValidationException v) { return(BadRequest(v.Errors)); } }
public IActionResult Update([FromRoute] Guid id, [FromBody] BookCommand bookCommand) { try { _booksWorkflow.Update(id, bookCommand); return(Ok()); } catch (ValidationException v) { return(BadRequest(v.Errors)); } }
public static Book FromBookCommand(BookCommand bookCommand) { return(new Book() { Id = Guid.NewGuid(), Title = bookCommand.Title, ISBN = bookCommand.ISBN, LaunchYear = bookCommand.LaunchYear, Author = bookCommand.Author, Category = bookCommand.Category }); }
public void Update(Guid id, BookCommand bookCommand) { Book book = _booksRepository.Find(id); if (book == null) { throw new Exception(); } book.Update(bookCommand); _booksValidator.Validate(book); _booksRepository.Update(book); }
private static List <Models.Booking> getBookingsForWeek() { DateTime now = DateTime.UtcNow; int daynum = BookCommand.dayOfWeekInt(now); DateTime weekStartTemp = now.AddDays(-daynum); DateTime weekStart = new DateTime(weekStartTemp.Year, weekStartTemp.Month, weekStartTemp.Day); DateTime weekEnd = weekStart.AddDays(+7); List <Models.Booking> bookings; using (MobileContext db = new MobileContext()) { //TODO выяснить почему если убрать запрос к таблице Participants, то в таблице Bookings все ссылки на Participants будут null var parts = db.Participants.ToList(); bookings = db.Bookings.Where(c => (c.TimeStart > weekStart) && (c.TimeEnd < weekEnd)).ToList(); } return(bookings); }
public void CreateBookFromBookCommand() { var bookCommand = new BookCommand() { Title = "Book", ISBN = "978–85–333–0227–3", LaunchYear = DateTime.Now.Year, Author = "Author", Category = "Category" }; var book = Book.FromBookCommand(bookCommand); Assert.Equal(book.Title, bookCommand.Title); Assert.Equal(book.ISBN, bookCommand.ISBN); Assert.Equal(book.LaunchYear, bookCommand.LaunchYear); Assert.Equal(book.Author, bookCommand.Author); Assert.Equal(book.Category, bookCommand.Category); }
public async Task <ActionResult> DeleteConfirmed(int id) { if (ModelState.IsValid) { var bookCommand = new BookCommand(); bool result = await bookCommand.RemoveAsync(id); if (!result) { ModelState.AddModelError("", ""); return(View()); } else { return(RedirectToAction("Index")); } } return(View()); }
public static void Show() { BookCommand vehiculo1 = new BookCommand("LIBRO 1", DateTime.Now, 1000.0); BookCommand vehiculo2 = new BookCommand("LIBRO 2", DateTime.Now.AddDays(-1), 2000.0); BookCommand vehiculo3 = new BookCommand("LIBRO 3", DateTime.Now.AddDays(-2), 3000.0); CatalogoCommand catalogo = new CatalogoCommand(); catalogo.Agrega(vehiculo1); catalogo.Agrega(vehiculo2); catalogo.Agrega(vehiculo3); Console.WriteLine("Visualización inicial del catálogo"); catalogo.Visualiza(); Console.WriteLine(); AplicarRebaja solicitudRebaja = new AplicarRebaja(10, 0.1); catalogo.commandRebaja(solicitudRebaja); Console.WriteLine("Visualización del catálogo tras ejecutar la primera solicitud"); catalogo.Visualiza(); Console.WriteLine(); AplicarRebaja solicitudRebaja2 = new AplicarRebaja(10, 0.5); catalogo.commandRebaja(solicitudRebaja2); Console.WriteLine("Visualización del católogo tras ejecutar la segunda solicitud"); catalogo.Visualiza(); Console.WriteLine(); catalogo.CommandAnulaRebaja(1); Console.WriteLine("Visualización del católogo tras anular la primera solicitud"); catalogo.Visualiza(); Console.WriteLine(); catalogo.RestablecerSolicitudRebaja(1); Console.WriteLine("Visualización del catálogo tras restablecer la primera solicitud"); catalogo.Visualiza(); Console.WriteLine(); }
public void UpdateBookFromBookCommand() { var book = new Book(Guid.NewGuid(), "Wrong Title", "368–22–987–3658–5", 1990, "Wrong Author", "Wrong Category"); var bookCommand = new BookCommand() { Title = "Book", ISBN = "978–85–333–0227–3", LaunchYear = DateTime.Now.Year, Author = "Author", Category = "Category" }; book.Update(bookCommand); Assert.Equal(book.Title, bookCommand.Title); Assert.Equal(book.ISBN, bookCommand.ISBN); Assert.Equal(book.LaunchYear, bookCommand.LaunchYear); Assert.Equal(book.Author, bookCommand.Author); Assert.Equal(book.Category, bookCommand.Category); }
private void Process(string strCommand) { try { BookCommand command = JsonConvert.DeserializeObject <BookCommand>(strCommand); switch (command.CommandType) { case BookCommand.SubscribeType.SUBSCRIBE: marketFaced.SubscribeMinibook((IUserChannelNotification)this, command.Stock); break; case BookCommand.SubscribeType.UN_SUBSCRIBE: marketFaced.UnSubscribeMinibook((IUserChannelNotification)this, command.Stock); break; } } catch (Exception e) { logger.LogError("Process", e); } }
void Bot_OnMessage(object sender, MessageEventArgs e) { Message message = e.Message; if (message.Text == null) { return; } //Запись в админского бота с логом Console.WriteLine($"@{message.From.Username}: " + message.Text); AdminBot.adminLog(message); //проверка наличия человека в базе Participant participant; using (MobileContext db = new MobileContext()) { //var parts = db.Participants.ToList(); //var books = db.Bookings.ToList(); //db.Bookings.Add(new Booking(books[0].Participant, DateTime.Now, DateTime.Now)); //db.SaveChanges(); //db.Participants.Add(new Participant("Виталий", "RunGiantBoom", new DateTime(2019, 12, 25, 12, 40, 20), "owner")); //db.SaveChanges(); try { participant = db.Participants.Single(c => c.Alias == message.From.Username); } catch (Exception ex) { Message mes = mainbot.SendTextMessageAsync(message.Chat.Id, "Привет. Мы пока не знакомы. Напиши @RunGiantBoom чтобы получить доступ к музкомнате.", replyToMessageId: message.MessageId).Result; AdminBot.adminLog("Exception " + ex.Message); return; } } //вызов команды при её наличии и выход из функции switch (message.Text) { case "/book": BookCommand.ReplyWithImageSchedule(message, mainbot, participant); return; case "/book_text_version": BookCommand.ReplyWithTextSchedule(message, mainbot); return; case "/cancel": CancelCommand.PerformAnswer(message, mainbot, participant); return; case "/start": StartCommand.PerformAnswer(message, mainbot); return; case "/help": HelpCommand.PerformAnswer(message, mainbot); return; case "/checkin": return; case "/status": return; case "Пн": BookCommand.ReplyWithTimeInput(message, mainbot, participant, 0); return; case "Вт": BookCommand.ReplyWithTimeInput(message, mainbot, participant, 1); return; case "Ср": BookCommand.ReplyWithTimeInput(message, mainbot, participant, 2); return; case "Чт": BookCommand.ReplyWithTimeInput(message, mainbot, participant, 3); return; case "Пт": BookCommand.ReplyWithTimeInput(message, mainbot, participant, 4); return; case "Сб": BookCommand.ReplyWithTimeInput(message, mainbot, participant, 5); return; case "Вс": BookCommand.ReplyWithTimeInput(message, mainbot, participant, 6); return; default: //Если команды в сообщении не было, значит пытаемся распарсить время и создать бронь TextInputCommand.Book(message, mainbot, participant); return; } //commands.Add(new HelloCommand()); //Update[] updates = bot.GetUpdatesAsync().Result; //foreach( Update update in updates) //{ // foreach( Command command in commands) // { // command.Execute(update.Message, bot); // } //} }
private async void BookCommandExecute() { bool? dialogResult = null; string confirmText = Properties.Resources.MESSAGE_ASK_BEFORE_BOOKING_ENQUIRY; RadWindow.Confirm(new DialogParameters() { Owner = Application.Current.MainWindow, Content = confirmText, Closed = (sender, args) => { dialogResult = args.DialogResult; } }); if (dialogResult != true) { return; } Enquiry.EnquiryStatus = EnquiryStatuses.FirstOrDefault(x => x.Status == "Booked"); EnquiryStatus = Enquiry.EnquiryStatus; var newEvent = new Event() { ID = Guid.NewGuid(), Name = Enquiry.Name, Date = (DateTime)Enquiry.Date, Places = (int)Enquiry.Places, CreationDate = DateTime.Now, ShowOnCalendar = true, IsDeleted = false, LastEditDate = DateTime.Now, EventTypeID = Enquiry.EventType.ID, EnquiryID = Enquiry.Enquiry.ID, EventStatusID = _eventStatuses.FirstOrDefault(x => x.Name == "Provisional").ID }; if (_enquiry.PrimaryContact != null) { newEvent.ContactID = _enquiry.PrimaryContact.Contact.ID; } _crmDataUnit.EventsRepository.Add(newEvent); var update = new EventUpdate() { ID = Guid.NewGuid(), EventID = newEvent.ID, Date = DateTime.Now, UserID = AccessService.Current.User.ID, Message = string.Format("Event {0} was created", newEvent.Name), OldValue = null, NewValue = newEvent.Name, ItemId = newEvent.ID, ItemType = "Event", Field = "Event", Action = UpdateAction.Added }; _crmDataUnit.EventUpdatesRepository.Add(update); _crmDataUnit.SaveChanges(); // Warning: Here we use EventDataUnit! var events = await _eventDataUnit.EventsRepository.GetLightEventsAsync(x => x.ID == newEvent.ID); var @event = events.FirstOrDefault(); var item = new EventModel(@event); // Open Add Event window in UI thread Application.Current.Dispatcher.BeginInvoke(new Action(() => { var bookingView = new BookingView(BookingViews.Event, item); bookingView.ShowDialog(); if (bookingView.DialogResult != null && bookingView.DialogResult == true) { string campaingText = Enquiry.Campaign == null ? "" : ", via Campaign " + Enquiry.Campaign.Name; var note = new EventNoteModel(new EventNote() { ID = Guid.NewGuid(), EventID = newEvent.ID, Date = DateTime.Now, EventNoteType = _eventNoteTypes.FirstOrDefault(x => x.Type == "Internal"), UserID = AccessService.Current.User.ID, Note = String.Format("From Enquiry, made on {0}, Taken by {1} Assigned to {2} enquiry via {3} {4}. {5} Notes, {6} Updates, {7} Activities & {8} Follow-Ups.", DateTime.Now, Enquiry.LoggedUser.FirstName, Enquiry.AssignedToUser.FirstName, Enquiry.ReceivedMethod.ReceiveMethod, campaingText, Enquiry.EnquiryNotes.Count, Enquiry.EnquiryUpdates.Count, Enquiry.Activities.Count, Enquiry.FollowUps.Count) }); _crmDataUnit.EventNotesRepository.Add(note.EventNote); _crmDataUnit.SaveChanges(); } })); BookCommand.RaiseCanExecuteChanged(); }
public static FileStream FormScheduleImage(Participant participant) { // Берём начало недели. DateTime now = DateTime.Today; int daynum = BookCommand.dayOfWeekInt(now); DateTime weekStart = now.AddDays(-daynum); DateTime weekEnd = weekStart.AddDays(+7); //60, 91, левый верхний угол //279, 91 //498, 91 //279, 131 //498, 171 //219 на 40, размер секции длинной в час Image image = Image.FromFile("to_paint_form1280.png"); //var form = File.OpenRead("schedule_form.png"); Color lightGreen = Color.FromArgb(255, 123, 209, 72); Pen pen = new Pen(Color.Green, 3); SolidBrush lightGreenbrush = new SolidBrush(lightGreen); SolidBrush requesterBrush = new SolidBrush(Color.LightBlue); SolidBrush bookingBrush; SolidBrush redbrush = new SolidBrush(Color.Red);; SolidBrush black = new SolidBrush(Color.Black); Font font = new Font(FontFamily.GenericSansSerif, 10); int xbase = 48; int ybase = 73; int xsize = 176; int ysize = 32; // Draw line to screen. using (var graphics = Graphics.FromImage(image)) { int day = 0; var bookings = getBookingsForWeek(); foreach (var booking in bookings) { if (booking.Participant.Alias.Equals(participant.Alias)) { bookingBrush = requesterBrush; } else { bookingBrush = lightGreenbrush; } day = BookCommand.dayOfWeekInt(booking.TimeStart); int ylength = (int)(ysize * (booking.TimeEnd.Subtract(booking.TimeStart).TotalMinutes / (float)60)); int xcorner = xbase + xsize * day; int ycorner = ybase + (int)(ysize * (booking.TimeStart.Hour - 7) + (booking.TimeStart.Minute / (float)60)); graphics.FillRectangle(bookingBrush, xcorner, ycorner, xsize - 10, ylength - 5); string caption = booking.Participant.Alias; if (booking.TimeEnd.Subtract(booking.TimeStart).TotalHours > 1) { caption += "\n"; } else { caption += " "; } graphics.DrawString(caption + booking.TimeStart.ToString("HH:mm") + " " + booking.TimeEnd.ToString("HH:mm"), font, black, xcorner + 2, ycorner + 2); _ = $"{booking.Participant.Alias} {booking.TimeStart} {booking.TimeEnd}\n"; } int nowxcorner = xbase + xsize * BookCommand.dayOfWeekInt(DateTime.Today); int nowycorner = (int)(ybase + ysize * ((DateTime.Now.Hour - 7) + (DateTime.Now.Minute / (float)60))); graphics.FillRectangle(redbrush, nowxcorner, nowycorner, xsize, 2); } //TODO: Костыль. Переделать без сохранения в файл image.Save("result.png"); return(File.OpenRead("result.png")); }