public async Task <IActionResult> Edit(int id, [Bind("Name,Price")] Fines fines) { if (id != fines.FinesID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(fines); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!FinesExists(fines.FinesID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(fines)); }
public IHttpActionResult PutFines(int id, Fines fines) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != fines.Id) { return(BadRequest()); } db.Entry(fines).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!FinesExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public static void Update(Fines f) { using (var db = new LibraryDBEntities()) { db.Entry(f).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } }
public static void Add(Fines f) { using (var db = new LibraryDBEntities()) { db.Fines.Add(f); db.SaveChanges(); } }
private async void ProcessFinesAsync() { administrators = await database_API.GetAdministratorsAsync(); residents = await database_API.GetResidentsAsync(); fines = ProcessFinesWithNameAsync(fines); database_API.postNewFineAsync(fines); }
private Fines ProcessFinesWithNameAsync(Fines fines) { int residentId = (from resident in residents where resident.Name == residentName select resident.ResidentID).FirstOrDefault(); int adminId = (from administrator in administrators where administrator.Username == Application.Current.Properties["Username"] select administrator.AdminID).FirstOrDefault(); fines.ResID = residentId; fines.AdmID = 1; return(fines); }
public static Fines MapToFines(FinesDTO finesDTO) { var fines = new Fines(); fines.FineId = finesDTO.FineId; fines.FineTitle = finesDTO.FineTitle; fines.FineText = finesDTO.FineText; return(fines); }
public ArbolObjetivoDTO ConsultarArbolObjetivosFinal(int IdProyecto) { var arbol = (from i in entity.ArbolObjetivos where i.IdProyecto == IdProyecto select i).FirstOrDefault(); List <Medios> ListaoMedios = new List <Medios>(); var medios = (from i in entity.MedioDirecto where i.IdArbolObj == arbol.IdArbolObj select i).ToList(); foreach (var item in medios) { Medios oMedios = new Medios(); var mediosDirectos = (from i in entity.MediosIndirectos where i.IdMedio == item.IdMedio select i.MedioIndirecto).ToList(); oMedios.Medio = item.MedioDirecto1; oMedios.MediosIndirectos = mediosDirectos; ListaoMedios.Add(oMedios); } var fines = (from i in entity.FinesDirectos where i.IdArbolObj == arbol.IdArbolObj select i).ToList(); List <Fines> ListaoFines = new List <Fines>(); foreach (var item in fines) { Fines oFin = new Fines(); var FinesIndirectos = (from i in entity.FinesIndirectos where i.IdFIn == item.IdFin select i.FinIndirecto).ToList(); oFin.fin = item.FinDirecto; oFin.FinesIndirectos = FinesIndirectos; ListaoFines.Add(oFin); } ArbolObjetivoDTO oArbolDTO = new ArbolObjetivoDTO(); oArbolDTO.IdProyecto = IdProyecto; oArbolDTO.ObjetivoCentral = arbol.ObjetivoCentral; oArbolDTO.Fines = ListaoFines; oArbolDTO.Medios = ListaoMedios; return(oArbolDTO); }
public IHttpActionResult GetFines(int id) { Fines fines = db.Fines.Find(id); if (fines == null) { return(NotFound()); } return(Ok(fines)); }
//Post Fines public async void postNewFineAsync(Fines fines) { HttpResponseMessage response1 = await client.PostAsJsonAsync("fines", fines); if (!response1.IsSuccessStatusCode) { ////Setting the data to the model //return finesDB = await response.Content.ReadAsAsync<List<fines>>(); Console.WriteLine("Internal server Error"); } }
public override ValidationResult Validate(object value, CultureInfo cultureInfo) { float RemainingAmount; if (float.TryParse(value.ToString().Trim(), out RemainingAmount)) { Fines F = new Fines(); return(ValidationResult.ValidResult); } return(ValidationResult.ValidResult); }
public IHttpActionResult PostFines(Fines fines) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.Fines.Add(fines); db.SaveChanges(); return(CreatedAtRoute("DefaultApi", new { id = fines.Id }, fines)); }
public IHttpActionResult DeleteFines(int id) { Fines fines = db.Fines.Find(id); if (fines == null) { return(NotFound()); } db.Fines.Remove(fines); db.SaveChanges(); return(Ok(fines)); }
public String Resolve() { if (Fines == null || Fines.Count() == 0) { return("Гражданинът няма никакви глоби за плащане."); } ResultText = "Гражданина има за плащане следните глоби:\n"; double Amount = 0.0; foreach (Fine f in Fines) { ResultText += "Глоба с номер: " + f.Id + "\n"; ResultText += "За автомобил: " + f.Vehicle.Model + " на стойност: " + f.DueAmount + "\n"; Amount += f.DueAmount; } return(ResultText += "Обща сума за плащане: " + Amount); }
public void LoadFine(Fines fines) { Data data = Fines.Datas[FineInc]; Data = data; BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(data.Photo); bitmapImage.EndInit(); carNumBox.Text = data.CarNum; licenceNumBox.Text = data.LicenceNum; createDateBox.Text = data.CreateDate.ToString(); regionNumBox.Text = data.Region; finesImage.Source = bitmapImage; FineInc++; }
private void btnReturnBook_Click(object sender, EventArgs e) { int selectIndex = dgvIssueBookList.CurrentRow.Index; var issueBookID = dgvIssueBookList.Rows[selectIndex].Cells[0].Value; var ib = IssueBooksHelper.GetIssueBookByID(Convert.ToInt32(issueBookID)); ib.Status = 0; IssueBooksHelper.Update(ib); if (DateTime.Now > ib.DateOfReturn) { gbFine.Enabled = true; Fines f = new Fines(); f.StudentID = ib.StudentID; f.BookID = ib.BookID; f.StaffID = _staffID; f.Date = DateTime.Now; f.FineAmount = Convert.ToInt32(txtTotalAmount.Text); f.RecivedAmount = 0; f.Status = 1; FinesHelper.Add(f); } ReturnBooks rb = new ReturnBooks(); rb.BookID = ib.BookID; rb.StudentID = ib.StudentID; rb.StaffID = _staffID; rb.IssueDate = ib.DateOfIssue; rb.ReturnDate = ib.DateOfReturn; rb.Date = DateTime.Now; ReturnBooksHelper.Add(rb); Books b = BooksHelper.GetBookByID(ib.BookID); b.NoOfCopies += 1; BooksHelper.Update(b); MessageBox.Show("Kitap iade başarılı!", "Library Management System", MessageBoxButtons.OK, MessageBoxIcon.Information); DisableComponent(); }
private void GetFinesButton_Click(object sender, RoutedEventArgs e) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.CreateHttp("http://solutions2019.hakta.pro/api/getFines?participant=06"); httpWebRequest.Method = "GET"; HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (Stream stream = httpWebResponse.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(stream)) { var Result = streamReader.ReadToEnd(); Console.WriteLine(Result); Fines = JsonConvert.DeserializeObject <Fines>(Result); } } LoadFine(Fines); }
public async Task <IActionResult> Create([Bind("FinesID,Name,Price")] Fines fines) { try { if (ModelState.IsValid) { _context.Add(fines); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } catch (DbUpdateException /* ex */) { //Log the error (uncomment ex variable name and write a log. ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator."); } return(View(fines)); }
public void UpdateFines() { connection(); List <Loan> loans = new List <Loan>(); List <Fines> fines = new List <Fines>(); SqlCommand command = new SqlCommand("Select * from book_loans", con); SqlDataAdapter da = new SqlDataAdapter(command); DataTable dt = new DataTable(); con.Open(); da.Fill(dt); con.Close(); foreach (DataRow dr in dt.Rows) { if ((dr["date_in"] is DBNull)) { dr["date_in"] = DateTime.MinValue; } loans.Add( new Loan { loan_id = Convert.ToString(dr["loan_id"]), isbn = Convert.ToString(dr["isbn"]), card_id = Convert.ToString(dr["card_id"]), date_out = Convert.ToDateTime(dr["date_out"]), due_date = Convert.ToDateTime(dr["due_date"]), date_in = Convert.ToDateTime(dr["date_in"]) }); } command = new SqlCommand("Select * from fines", con); da = new SqlDataAdapter(command); dt = new DataTable(); con.Open(); da.Fill(dt); con.Close(); foreach (DataRow dr in dt.Rows) { fines.Add( new Fines { loan_id = Convert.ToString(dr["loan_id"]), fine_amt = Convert.ToDouble(dr["fine_amt"]), paid = Convert.ToBoolean(dr["paid"]) }); } foreach (Loan loan in loans) { double fine_amt = 0; bool flag = false; if (!loan.date_in.Equals(DateTime.MinValue) && loan.date_in > loan.due_date) { fine_amt = (loan.date_in - loan.due_date).Days * 0.25; flag = true; } else if (loan.date_in.Equals(DateTime.MinValue) && DateTime.Now > loan.due_date) { fine_amt = (DateTime.Now - loan.due_date).Days * 0.25; flag = true; } if (flag) { Fines fine_row = fines.Find(x => x.loan_id == loan.loan_id); if (fine_row != null) { if (!fine_row.paid) { fine_row.fine_amt = fine_amt; } } else { fines.Add( new Fines { loan_id = loan.loan_id, fine_amt = fine_amt, paid = false } ); } } } SqlCommand update = new SqlCommand("delete from fines", con); con.Open(); update.ExecuteNonQuery(); con.Close(); DataTable updateDt = new DataTable(); updateDt = ConvertToDataTable(fines); con.Open(); using (SqlBulkCopy bulkcopy = new SqlBulkCopy(con)) { bulkcopy.BulkCopyTimeout = 660; bulkcopy.DestinationTableName = "Fines"; bulkcopy.WriteToServer(updateDt); bulkcopy.Close(); } con.Close(); }
public async Task <IHttpActionResult> Register(Individual model) { try { if (!ModelState.IsValid) { var modelErrors = new List <string>(); foreach (var modelState in ModelState.Values) { foreach (var modelError in modelState.Errors) { modelErrors.Add(modelError.ErrorMessage); } } return(Content(HttpStatusCode.BadRequest, modelErrors[0].ToString())); } string phone = model.MobNum.CountryCode.ToString().Trim() + model.MobNum.Num.ToString().Trim(); if (await _bucket.ExistsAsync(model.EmiratiID)) { return(Content(HttpStatusCode.Conflict, new Error($"EmiratiId already exists"))); } if (await _bucket.ExistsAsync(model.Email)) { return(Content(HttpStatusCode.Conflict, new Error($"The e-mail already exists "))); } if (await _bucket.ExistsAsync(phone)) { return(Content(HttpStatusCode.Conflict, new Error($"Mobile number already exists"))); } Individual individual = new Individual(); MobNum mobNum = new MobNum(); mobNum.CountryCode = model.MobNum.CountryCode; mobNum.Num = model.MobNum.Num; TelNum telNum = new TelNum(); telNum.CountryCode = model.MobNum.CountryCode; telNum.Num = model.MobNum.Num; AuditInfo auditInfo = new AuditInfo(); auditInfo.Version = "1"; auditInfo.Status = "true"; auditInfo.LastChangeDate = DateTime.Now.ToString(); auditInfo.LastChangeBy = model.Email; List <Roles> lstRoles = new List <Roles>(); foreach (var role in model.Roles) { Roles roles = new Roles(); roles.Code = role.Code; roles.Name = role.Name; lstRoles.Add(roles); } List <Fines> lstFines = new List <Fines>(); foreach (var fine in model.Fines) { Fines fines = new Fines(); fines.Amount = fine.Amount; fines.Date = fine.Date; fines.Remark = fine.Remark; lstFines.Add(fines); } List <Documents> lstDocuments = new List <Documents>(); foreach (var document in model.Documents) { Documents documents = new Documents(); documents.Date = document.Date; documents.Name = document.Name; documents.Path = document.Path; lstDocuments.Add(document); } List <Vehicles> lstVehicles = new List <Vehicles>(); foreach (var vehicle in model.Vehicles) { Vehicles vehicles = new Vehicles(); vehicles.Name = vehicle.Name; vehicles.Model = vehicle.Model; vehicles.Type = vehicle.Type; lstVehicles.Add(vehicles); } Name name = new Name(); EN en = new EN(); en.FullName = model.Name.EN.FullName; name.EN = en; AR ar = new AR(); ar.FullName = model.Name.EN.FullName; name.AR = ar; var eotp = GenerateOtp(); var motp = GenerateOtp(); sendEmail.SendOtpViaEmail(model.Email, model.Name.EN.FullName, eotp); SendOtpViaMobile(model.MobNum, motp); string password = Guid.NewGuid().ToString("d").Substring(1, 4); var individualDoc = new Document <Individual>() { Id = "individual_" + model.EmiratiID, Content = new Individual { KeyID = "individual_" + model.EmiratiID, Name = name, DOB = model.DOB, Nationality = model.Nationality, Gender = model.Gender, Fines = lstFines, Language = model.Language, MaritalStatus = model.MaritalStatus, MobNum = mobNum, AuditInfo = auditInfo, Vehicles = lstVehicles, Roles = lstRoles, TelNum = model.TelNum, DocType = model.DocType, Documents = lstDocuments, Email = model.Email, Notes = model.Notes, }, }; var result = await _bucket.InsertAsync(individualDoc); if (!result.Success) { return(Content(HttpStatusCode.InternalServerError, new Error(result.Message))); } else { //sendEmail.SendUserIdAndPassword(model.Email, password); var userDocLogin = new Document <Login>() { Id = "Login_" + model.Email, Content = new Login { Created_by = model.Email, Created_on = DateTime.Now.ToString(), UserId = model.Email, Password = password, Pre_language = model.Language, Status = "A", Type = "CAST", Role = "User", }, }; IBucket _bucketLogin = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseLoginBucket")); var resultLogin = await _bucketLogin.InsertAsync(userDocLogin); return(Content(HttpStatusCode.Accepted, result.Document.Id)); } } catch (Exception ex) { return(Content(HttpStatusCode.Forbidden, ex.StackTrace)); } }
public void InsertFine(Fines fines) { _finesRepository.InsertFine(fines); }
public void UpdateFine(Fines fines) { _finesRepository.UpdateFine(fines); }
public static void Initialize(HotelContext context) { context.Database.EnsureCreated(); if (context.Clients.Any()) { return; // DB has been seeded } var clients = new Client[] { new Client { Name = "Макушенко", FirstMidName = "Сергійович", LastName = "Олександр", ContactPhone = "911", Email = "*****@*****.**" }, new Client { Name = "Сольшенко", FirstMidName = "Вадимович", LastName = "Євген", ContactPhone = "911", Email = "*****@*****.**" }, new Client { Name = "Коробов", FirstMidName = "Ігорович", LastName = "Олексій", ContactPhone = "911", Email = "*****@*****.**" }, new Client { Name = "Некрасова", FirstMidName = "Максимівна", LastName = "Дарія", ContactPhone = "911", Email = "*****@*****.**" }, new Client { Name = "Лобанов", FirstMidName = "Маркович", LastName = "Дем'ян", ContactPhone = "911", Email = "*****@*****.**" }, new Client { Name = "Козаченко", FirstMidName = "Єрополкович", LastName = "Сергій", ContactPhone = "911", Email = "*****@*****.**" }, new Client { Name = "Рогозіна", FirstMidName = "Артемівна", LastName = "Соломія", ContactPhone = "911", Email = "*****@*****.**" }, new Client { Name = "Серрано", FirstMidName = "Семьюельович", LastName = "Марчелло", ContactPhone = "911", Email = "*****@*****.**" } }; foreach (Client s in clients) { context.Clients.Add(s); } context.SaveChanges(); var rooms = new Room[] { new Room { Number = 1, Title = "Двомісний люкс" }, new Room { Number = 2, Title = "Стандарт на двох" }, new Room { Number = 3, Title = "Одномісна кімната" }, new Room { Number = 4, Title = "Трьохмісна кімната" }, new Room { Number = 5, Title = "Люкс на трьох" }, new Room { Number = 6, Title = "Чотирьохмісний номер" }, new Room { Number = 7, Title = "Просто ліжко голі стіни" } }; foreach (Room c in rooms) { context.Rooms.Add(c); } context.SaveChanges(); var orders = new Orders[] { new Orders { ClientID = 1, RoomID = 1, Check_inDate = DateTime.Parse("2005-09-01"), Check_outDate = DateTime.Parse("2003-09-01"), OrderDate = DateTime.Parse("2002-09-01") }, new Orders { ClientID = 2, RoomID = 2, Check_inDate = DateTime.Parse("2002-09-01"), Check_outDate = DateTime.Parse("2003-09-01"), OrderDate = DateTime.Parse("2002-09-01") }, new Orders { ClientID = 3, RoomID = 3, Check_inDate = DateTime.Parse("2003-09-01"), Check_outDate = DateTime.Parse("2003-09-01"), OrderDate = DateTime.Parse("2002-09-01") }, new Orders { ClientID = 4, RoomID = 4, Check_inDate = DateTime.Parse("2002-09-01"), Check_outDate = DateTime.Parse("2003-09-01"), OrderDate = DateTime.Parse("2002-09-01") }, new Orders { ClientID = 5, RoomID = 5, Check_inDate = DateTime.Parse("2002-09-01"), Check_outDate = DateTime.Parse("2003-09-01"), OrderDate = DateTime.Parse("2002-09-01") }, new Orders { ClientID = 6, RoomID = 6, Check_inDate = DateTime.Parse("2001-09-01"), Check_outDate = DateTime.Parse("2003-09-01"), OrderDate = DateTime.Parse("2002-09-01") }, new Orders { ClientID = 8, RoomID = 7, Check_inDate = DateTime.Parse("2003-09-01"), Check_outDate = DateTime.Parse("2003-09-01"), OrderDate = DateTime.Parse("2002-09-01") }, }; foreach (Orders e in orders) { context.Orders.Add(e); } context.SaveChanges(); var fines = new Fines[] { new Fines { Price = 1456, Name = "Упс" }, new Fines { Price = 234, Name = "Ой йой" }, new Fines { Price = 3645, Name = "Побитий персонал" }, new Fines { Price = 46534, Name = "Зламане вікно" }, new Fines { Price = 5645, Name = "П'яні драки" }, new Fines { Price = 6765, Name = "Пісні Монатіка" }, new Fines { Price = 7345, Name = "Просто так" } }; foreach (Fines c in fines) { context.Fines.Add(c); } context.SaveChanges(); var oddserv = new OddServ[] { new OddServ { Price = 1456, Name = "Щось" }, new OddServ { Price = 234, Name = "Ще щось" }, new OddServ { Price = 3645, Name = "І ще щось" }, new OddServ { Price = 46534, Name = "А потім ще щось" }, new OddServ { Price = 5645, Name = "Оце" }, new OddServ { Price = 6765, Name = "Ну те" }, new OddServ { Price = 7345, Name = "Невідомо" } }; foreach (OddServ c in oddserv) { context.OddServ.Add(c); } context.SaveChanges(); }
public IHttpActionResult CompanyAddFine([FromUri] string id, Fines model) { try { bool isThisFineExist = false; if (!ModelState.IsValid) { var modelErrors = new List <string>(); foreach (var modelState in ModelState.Values) { foreach (var modelError in modelState.Errors) { modelErrors.Add(modelError.ErrorMessage); } } return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), modelErrors[0].ToString()), new JsonMediaTypeFormatter())); } Fines addNewFine = new Fines(); addNewFine.FineID = model.FineID; addNewFine.Amount = model.Amount; addNewFine.Status = model.Status; addNewFine.Remark = model.Remark; addNewFine.DateTime = model.DateTime; /////////////////// Validate Code for Fine already exist or not. var fineDoc = _bucket.Query <object>(@"SELECT fines From " + _bucket.Name + " where meta().id = '" + id + "'").ToList(); foreach (var item1 in fineDoc) { if (((Newtonsoft.Json.Linq.JToken)item1).Root["fines"] != null) { //fines-FineID var finesIsExist = ((Newtonsoft.Json.Linq.JToken)item1).Root["fines"]; foreach (var itemTD in finesIsExist) { if (itemTD["fineID"].ToString() == model.FineID) { isThisFineExist = true; } } } } /////////////////////////////////// if (isThisFineExist == true) { // fine already exist. return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), model.FineID + " already exists"), new JsonMediaTypeFormatter())); } else { // add fine code string query = @"UPDATE " + _bucket.Name + " SET fines = ARRAY_APPEND(fines, " + Newtonsoft.Json.JsonConvert.SerializeObject(addNewFine).ToString() + ") where meta().id='" + id + "'"; var result = _bucket.Query <object>(query); if (ConfigurationManager.AppSettings.Get("NotificationSettingFlag") == "1") { #region Post Notification RoleCodeHODP //////////////// Post Notification Code try { PostNotificationParameters objPostNotificationParameters = new PostNotificationParameters(); objPostNotificationParameters.UserCode = string.Empty; objPostNotificationParameters.RoleCode = AspectEnums.RoleCodeHODP; objPostNotificationParameters.DeptCode = AspectEnums.DeptCodeFROE; objPostNotificationParameters.NotificationType = (int)AspectEnums.NotificationType.FineRequest; objPostNotificationParameters.KeyID = model.FineID;//docOutDocument.KeyID; objPostNotificationParameters.Value = model.Amount; objPostNotificationParameters.Status = model.Status; resultPostNotification = sn.PostNotification(objPostNotificationParameters); //sn.PostNotification(); } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter())); } #endregion #region Post Notification RoleCodeBCKO //////////////// Post Notification Code try { PostNotificationParameters objPostNotificationParameters = new PostNotificationParameters(); objPostNotificationParameters.UserCode = string.Empty; objPostNotificationParameters.RoleCode = AspectEnums.RoleCodeBCKO; objPostNotificationParameters.DeptCode = AspectEnums.DeptCodeFROE; objPostNotificationParameters.NotificationType = (int)AspectEnums.NotificationType.FineRequest; objPostNotificationParameters.KeyID = model.FineID;//docOutDocument.KeyID; objPostNotificationParameters.Value = model.Amount; objPostNotificationParameters.Status = model.Status; resultPostNotification = sn.PostNotification(objPostNotificationParameters); //sn.PostNotification(); } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter())); } #endregion } return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), model.FineID + " has been added sucessfully"), new JsonMediaTypeFormatter())); } } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter())); } }
public IHttpActionResult IndividualAddFine([FromUri] string id, Fines model) { try { bool isThisFineExist = false; if (!ModelState.IsValid) { var modelErrors = new List <string>(); foreach (var modelState in ModelState.Values) { foreach (var modelError in modelState.Errors) { modelErrors.Add(modelError.ErrorMessage); } } return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), modelErrors[0].ToString()), new JsonMediaTypeFormatter())); } Fines addNewFine = new Fines(); addNewFine.FineID = model.FineID; addNewFine.Amount = model.Amount; addNewFine.Status = model.Status; addNewFine.Remark = model.Remark; addNewFine.DateTime = model.DateTime; /////////////////// Validate Code for Fine already exist or not. var fineDoc = _bucket.Query <object>(@"SELECT fines From " + _bucket.Name + " where meta().id = '" + id + "'").ToList(); foreach (var item1 in fineDoc) { if (((Newtonsoft.Json.Linq.JToken)item1).Root["fines"] != null) { //fines-FineID var finesIsExist = ((Newtonsoft.Json.Linq.JToken)item1).Root["fines"]; foreach (var itemTD in finesIsExist) { if (itemTD["fineID"].ToString() == model.FineID) { isThisFineExist = true; } } } } /////////////////////////////////// if (isThisFineExist == true) { // fine already exist. return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), model.FineID + " already exists"), new JsonMediaTypeFormatter())); } else { // add fine code string query = @"UPDATE " + _bucket.Name + " SET fines = ARRAY_APPEND(fines, " + Newtonsoft.Json.JsonConvert.SerializeObject(addNewFine).ToString() + ") where meta().id='" + id + "'"; var result = _bucket.Query <object>(query); return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), model.FineID + " has been added sucessfully"), new JsonMediaTypeFormatter())); } } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter())); } }
public async Task <IHttpActionResult> Register(Company model) { var serializer = new JavaScriptSerializer(); try { string keyId = "company_" + model.Email; var userDocument = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where keyID= '" + keyId + "'").ToList(); if (userDocument.Count > 0) { return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "The e-mail already exists"), new JsonMediaTypeFormatter())); } if (!ModelState.IsValid) { var modelErrors = new List <string>(); foreach (var modelState in ModelState.Values) { foreach (var modelError in modelState.Errors) { //modelErrors.Add(modelError.ErrorMessage); modelErrors.Add(modelError.ErrorMessage == "" ? modelError.Exception.Message : modelError.ErrorMessage); } } return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), modelErrors[0].ToString()), new JsonMediaTypeFormatter())); } var userDocumentPhone = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where " + _bucket.Name + ".mobNum.num= '" + model.MobNum.NumM + "'").ToList(); if (userDocumentPhone.Count > 0) { return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "104-Mobile number already exists"), new JsonMediaTypeFormatter())); } MobNum mobNum = new MobNum(); mobNum.CountryCodeM = model.MobNum.CountryCodeM; mobNum.NumM = model.MobNum.NumM; TelNum telNum = new TelNum(); telNum.CountryCodeT = model.TelNum.CountryCodeT; telNum.NumT = model.TelNum.NumT; AuditInfo auditInfo = new AuditInfo(); auditInfo.Version = "1"; auditInfo.Status = "true"; auditInfo.LastChangeDate = DataConversion.ConvertYMDHMS(DateTime.Now.ToString());; auditInfo.LastChangeBy = model.Email; List <Roles> lstRoles = new List <Roles>(); foreach (var role in model.Roles) { Roles roles = new Roles(); roles.RoleID = role.RoleID; roles.Link = role.Link; lstRoles.Add(roles); } /*List<CompanyRoles> lstRoles = new List<CompanyRoles>(); * * foreach (var role in model.Roles) * { * CompanyRoles roles = new CompanyRoles(); * roles.RoleID = role.RoleID; * roles.Link = role.Link; * lstRoles.Add(roles); * }*/ List <Fines> lstFines = new List <Fines>(); foreach (var fine in model.Fines) { Fines fines = new Fines(); fines.FineID = fine.FineID; fines.DateTime = fine.DateTime; fines.Amount = fine.Amount; fines.Status = fine.Status; fines.Remark = fine.Remark; lstFines.Add(fines); } List <Documents> lstDocuments = new List <Documents>(); foreach (var document in model.Documents) { Documents addnewDocument = new Documents(); addnewDocument.DocumentID = document.DocumentID; addnewDocument.Type = document.Type; addnewDocument.Version = document.Version; addnewDocument.ExpDate = document.ExpDate; addnewDocument.DocStatus = document.DocStatus; lstDocuments.Add(document); } List <Vehicles> lstVehicles = new List <Vehicles>(); foreach (var vehicle in model.Vehicles) { Vehicles vehicles = new Vehicles(); vehicles.VehicleID = vehicle.VehicleID; vehicles.Make = vehicle.Make; vehicles.ModelYear = vehicle.ModelYear; vehicles.VehType = vehicle.VehType; vehicles.Status = vehicle.Status; lstVehicles.Add(vehicles); } CompanyAddress address = new CompanyAddress(); address.City = model.Address.City; address.Zip = model.Address.Zip; address.State = model.Address.State; address.Country = model.Address.Country; Line line = new Line(); line.Line1 = model.Address.Line.Line1; line.Line2 = model.Address.Line.Line2; address.Line = line; FullName fullname = new FullName(); fullname.En_US = model.fullName.En_US; fullname.Ar_SA = model.fullName.Ar_SA; var eotp = GenerateOtp(); var motp = GenerateOtp(); sendEmail.SendOtpViaEmail(model.Email, fullname.En_US, eotp); SendOtpViaMobile(model.MobNum, motp); string password = Guid.NewGuid().ToString("d").Substring(1, 4); var companyDoc = new Document <Company>() { Id = "company_" + model.Email, Content = new Company { KeyID = "company_" + model.Email, fullName = fullname, Fines = lstFines, MobNum = mobNum, AuditInfo = auditInfo, Vehicles = lstVehicles, Roles = lstRoles, TelNum = model.TelNum, DocType = model.DocType, Documents = lstDocuments, Email = model.Email, Address = address, Website = model.Website }, }; var result = await _bucket.InsertAsync(companyDoc); if (!result.Success) { return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), result.Message), new JsonMediaTypeFormatter())); } else { return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result.Document.Id), new JsonMediaTypeFormatter())); } } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter())); } }