public static void Update(AdditionalService ads) { try { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString)) { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "UPDATE AdditionalService SET Name=@Name, Price=@Price, Deleted=@Deleted WHERE ID = @ID;"; cmd.CommandText += "SELECT SCOPE_IDENTITY();"; cmd.Parameters.AddWithValue("ID", ads.ID); cmd.Parameters.AddWithValue("Name", ads.Name); cmd.Parameters.AddWithValue("Price", ads.Price); cmd.Parameters.AddWithValue("Deleted", ads.Deleted); cmd.ExecuteNonQuery(); foreach (var a in Project.Instance.AdditionalServicesList) { if (ads.ID == a.ID) { a.Name = ads.Name; a.Deleted = ads.Deleted; } } } } catch { MessageBox.Show("Database error!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public IActionResult AddAdditionalService(int idAssessment, AdditionalServiceViewModel additionalService) { if (ModelState.IsValid && idAssessment > 0) { var assessmentAdditional = new AdditionalService() { Description = additionalService.Description, Value = additionalService.Value }; var result = _business.AddAdditionalService(new Assessment() { IdAssessment = idAssessment, IdCompany = User.GetClaim("CompanyId") }, assessmentAdditional); if (result.Sucess) { return(Ok()); } else { return(BadRequest(result.Error)); } } else { return(BadRequest(ModelState)); } }
private void BtnEdit_Click(object sender, RoutedEventArgs e) { if (dgFurniture.Visibility.Equals(Visibility.Visible)) { Furniture copy = (Furniture)SelectedFurniture.Clone(); FurnitureWindow furnitureWindow = new FurnitureWindow(copy, FurnitureWindow.Operation.EDIT); furnitureWindow.Show(); } else if (dgFurnitureType.Visibility.Equals(Visibility.Visible)) { FurnitureType copy = (FurnitureType)SelectedFurnitureType.Clone(); FurnitureTypeWindow furnitureWindow = new FurnitureTypeWindow(copy, FurnitureTypeWindow.Operation.EDIT); furnitureWindow.Show(); } else if (dgSales.Visibility.Equals(Visibility.Visible)) { Sale copy = (Sale)SelectedSale.Clone(); SaleWindow saleWindow = new SaleWindow(copy, SaleWindow.Operation.EDIT); saleWindow.Show(); } else if (dgUsers.Visibility.Equals(Visibility.Visible)) { User copy = (User)SelectedUser.Clone(); UserWindow userWindow = new UserWindow(copy, UserWindow.Operation.EDIT); userWindow.Show(); } else if (dgAdditionalService.Visibility.Equals(Visibility.Visible)) { AdditionalService copy = (AdditionalService)SelectedAdditionalService.Clone(); AdditionalServiceWindow additionalServiceWindow = new AdditionalServiceWindow(copy, AdditionalServiceWindow.Operation.EDIT); additionalServiceWindow.Show(); } }
public static AdditionalService Create(AdditionalService ads) { try { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString)) { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "INSERT INTO AdditionalService(Name, Price, Deleted) VALUES (@Name, @Price, @Deleted);"; cmd.CommandText += "SELECT SCOPE_IDENTITY();"; cmd.Parameters.AddWithValue("Name", ads.Name); cmd.Parameters.AddWithValue("Price", ads.Price); cmd.Parameters.AddWithValue("Deleted", ads.Deleted); ads.ID = int.Parse(cmd.ExecuteScalar().ToString()); } Project.Instance.AdditionalServicesList.Add(ads); return(ads); } catch { MessageBox.Show("", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return(null); } }
public HttpResponseMessage add(AdditionalService post, Int32 languageId = 0) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } else if (Language.MasterPostExists(languageId) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The language does not exist")); } else if (Unit.MasterPostExists(post.unit_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The unit does not exist")); } else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The value added tax does not exist")); } // Make sure that the data is valid post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 50); post.name = AnnytabDataValidation.TruncateString(post.name, 100); post.fee = AnnytabDataValidation.TruncateDecimal(post.fee, 0, 9999999999.99M); post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10); // Add the post Int64 insertId = AdditionalService.AddMasterPost(post); post.id = Convert.ToInt32(insertId); AdditionalService.AddLanguagePost(post, languageId); // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The post has been added")); } // End of the add method
public HttpResponseMessage add(AdditionalService post, Int32 languageId = 0) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } else if (Language.MasterPostExists(languageId) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist"); } else if (Unit.MasterPostExists(post.unit_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The unit does not exist"); } else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The value added tax does not exist"); } // Make sure that the data is valid post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 50); post.name = AnnytabDataValidation.TruncateString(post.name, 100); post.fee = AnnytabDataValidation.TruncateDecimal(post.fee, 0, 9999999999.99M); post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10); // Add the post Int64 insertId = AdditionalService.AddMasterPost(post); post.id = Convert.ToInt32(insertId); AdditionalService.AddLanguagePost(post, languageId); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The post has been added"); } // End of the add method
public static ObservableCollection <AdditionalService> GetAll() { var additionalServices = new ObservableCollection <AdditionalService>(); using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString)) { con.Open(); SqlCommand cmd = con.CreateCommand(); SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); cmd.CommandText = "SELECT * FROM AdditionalService WHERE Deleted = 0;"; da.SelectCommand = cmd; da.Fill(ds, "AdditionalService"); foreach (DataRow row in ds.Tables["AdditionalService"].Rows) { var ads = new AdditionalService(); ads.ID = Convert.ToInt32(row["ID"]); ads.Name = row["Name"].ToString(); ads.Price = Convert.ToDouble(row["Price"]); ads.Deleted = bool.Parse(row["Deleted"].ToString()); additionalServices.Add(ads); } } return(additionalServices); }
public async Task <IActionResult> Edit(int id, [Bind("ServiceId,Name,Description,Price")] AdditionalService additionalService) { if (id != additionalService.ServiceId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(additionalService); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AdditionalServiceExists(additionalService.ServiceId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(additionalService)); }
async void SetText() { UkName.Text = Settings.MobileSettings.main_name; if (!string.IsNullOrWhiteSpace(Settings.Person.companyPhone)) { LabelPhone.Text = "+" + Settings.Person.companyPhone.Replace("+", ""); } else { IconViewLogin.IsVisible = false; LabelPhone.IsVisible = false; } LabelTitle.Text = _announcementInfo.Header; LabelDate.Text = _announcementInfo.Created; LabelText.Text = _announcementInfo.Text; FrameBtnQuest.BackgroundColor = (Color)Application.Current.Resources["MainColor"]; int announcementInfoAdditionalServiceId = _announcementInfo.AdditionalServiceId; if (announcementInfoAdditionalServiceId != -1) { _additional = Settings.GetAdditionalService(announcementInfoAdditionalServiceId); byte[] imageByte = await _server.GetPhotoAdditional(announcementInfoAdditionalServiceId.ToString()); if (imageByte != null) { Stream stream = new MemoryStream(imageByte); ImageAdd.Source = ImageSource.FromStream(() => { return(stream); }); ImageAdd.IsVisible = true; var openAdditional = new TapGestureRecognizer(); openAdditional.Tapped += async(s, e) => { await Navigation.PushAsync(new AdditionalOnePage(_additional)); }; ImageAdd.GestureRecognizers.Add(openAdditional); } } if (_announcementInfo.QuestionGroupID != -1) { _polls = Settings.GetPollInfo(_announcementInfo.QuestionGroupID); FrameBtnQuest.IsVisible = true; } Color hexColor = (Color)Application.Current.Resources["MainColor"]; IconViewLogin.SetAppThemeColor(IconView.ForegroundProperty, hexColor, Color.White); Pancake.SetAppThemeColor(PancakeView.BorderColorProperty, hexColor, Color.Transparent); PancakeViewIcon.SetAppThemeColor(PancakeView.BorderColorProperty, hexColor, Color.Transparent); if (Device.RuntimePlatform == Device.iOS) { if (AppInfo.PackageName == "rom.best.saburovo" || AppInfo.PackageName == "sys_rom.ru.tsg_saburovo") { PancakeViewIcon.Padding = new Thickness(0); } } //LabelTech.SetAppThemeColor(Label.TextColorProperty, hexColor, Color.Black); //IconViewTech.SetAppThemeColor(IconView.ForegroundProperty, hexColor, Color.Black); }
public async Task <AdditionalService> Store(AdditionalService additionalServices) { await _context.AdditionalServices.AddAsync(additionalServices); await _context.SaveChangesAsync(); return(additionalServices); }
private void addButton_Click(object sender, EventArgs e) { var record = new AdditionalService(); record.AMPM = "AM"; _db.AdditionalServices.Add(record); }
private void tbSearchAS_TextChanged(object sender, TextChangedEventArgs e) { additionalServicesView.Filter = x => { AdditionalService aservice = x as AdditionalService; return(aservice.Name.ToLower().Contains(tbSearchAS.Text.ToLower().Trim())); }; }
public List <AdditionalService> get_all_active(Int32 languageId = 0, string sortField = "", string sortOrder = "") { // Create the list to return List <AdditionalService> posts = AdditionalService.GetAllActive(languageId, sortField, sortOrder); // Return the list return(posts); } // End of the get_all_active method
public IActionResult CreateService(string name, string description, double price) { AdditionalService createdService = _dbService.AddAdditioonalService(name, description, price); Response.Cookies.Append("Service", JsonConvert.SerializeObject(createdService)); return(RedirectToAction("Services")); }
public void UpdateThreadByAdditionalService(AdditionalService additionalService) { var thread = additionalService.Thread; UpdatePostsReadOnlyStatus(thread); thread.UpdateModificationDate(); base.Update(thread); }
public AdditionalService get_by_id(Int32 id = 0, Int32 languageId = 0) { // Create the post to return AdditionalService post = AdditionalService.GetOneById(id, languageId); // Return the post return(post); } // End of the get_by_id method
public ScannerView(Core.Scanner.ScanType scanType, AdditionalService additionalService = null) { InitializeComponent(); BindingContext = new ScannerViewModel(scanType, additionalService) { Navigation = Navigation }; }
} // End of the MasterPostExists method /// <summary> /// Get one additional service based on id /// </summary> /// <param name="additionalServiceId">A additional service id</param> /// <param name="languageId">The language id</param> /// <returns>A reference to a additional service post</returns> public static AdditionalService GetOneById(Int32 additionalServiceId, Int32 languageId) { // Create the post to return AdditionalService post = null; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.additional_services_detail AS D INNER JOIN dbo.additional_services AS A ON " + "D.additional_service_id = A.id AND D.additional_service_id = @id AND D.language_id = @language_id;"; // The using block is used to call dispose automatically even if there is a exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add a parameters cmd.Parameters.AddWithValue("@id", additionalServiceId); cmd.Parameters.AddWithValue("@language_id", languageId); // Create a MySqlDataReader SqlDataReader reader = null; // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Fill the reader with one row of data. reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read and add values while (reader.Read()) { post = new AdditionalService(reader); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage. if (reader != null) { reader.Close(); } } } } // Return the post return(post); } // End of the GetOneById method
public ActionResult translate(Int32 id = 0, string returnUrl = "") { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor", "Translator" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get the language id int languageId = 0; if (Request.Params["lang"] != null) { Int32.TryParse(Request.Params["lang"], out languageId); } // Add data to the form ViewBag.LanguageId = languageId; ViewBag.Languages = Language.GetAll(adminLanguageId, "name", "ASC"); ViewBag.StandardAdditionalService = AdditionalService.GetOneById(id, adminLanguageId); ViewBag.TranslatedAdditionalService = AdditionalService.GetOneById(id, languageId); ViewBag.TranslatedTexts = StaticText.GetAll(adminLanguageId, "id", "ASC"); ViewBag.ReturnUrl = returnUrl; // Return the view if (ViewBag.StandardAdditionalService != null) { return View("translate"); } else { return Redirect("/admin_additional_services" + returnUrl); } } // End of the translate method
public void Create(string title, byte[] headPicture, List <byte[]> tourDayPictures, List <string> tourDayTitles, List <string> tourDayDescriptions, DateTime startDate, DateTime endDate, decimal price, int busSeatsNumber, int nights, string startingPoint, string destination, string destinationType, string description, string usefulInformation, List <string> priceIncludes, List <string> priceDoesNotIncludes, List <string> additionalServicesContents, List <decimal> additionalServicesPrices) { var days = new List <Day>(); var additionalServices = new List <AdditionalService>(); var trip = this.CreateTrip(startDate, endDate, price, busSeatsNumber); for (int i = 0; i < tourDayDescriptions.Count; i++) { var day = new Day { DayTitle = tourDayTitles[i], DayDescription = tourDayDescriptions[i], DayPicture = tourDayPictures[i] }; days.Add(day); } for (int i = 0; i < additionalServicesContents.Count; i++) { var additionalService = new AdditionalService { Content = additionalServicesContents[i], Price = additionalServicesPrices[i] }; additionalServices.Add(additionalService); } var tour = new Tour { Title = title, HeaderImage = headPicture, TourDays = days, StartingPoint = startingPoint, Destination = destination, DestinationType = (DestinationType)Enum.Parse(typeof(DestinationType), destinationType), Description = description, AdditionalServices = additionalServices, PriceIncludes = string.Join(Environment.NewLine, priceIncludes), PriceDoesNotIncludes = string.Join(Environment.NewLine, priceDoesNotIncludes), UsefulInformation = usefulInformation, Nights = nights }; tour.Trips.Add(trip); this.db.Tours.Add(tour); this.db.SaveChanges(); }
public AdditionalServiceWindow(AdditionalService additionalService, Operation operation) { InitializeComponent(); this.additionalService = additionalService; this.operation = operation; tbName.DataContext = additionalService; tbPrice.DataContext = additionalService; }
public async Task <IActionResult> Create([Bind("ServiceId,Name,Description,Price")] AdditionalService additionalService) { if (ModelState.IsValid) { _context.Add(additionalService); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(additionalService)); }
private void btDeleteAdditionalService_Click(object sender, RoutedEventArgs e) { AdditionalService additionalService = (AdditionalService)dgAdditionalService.SelectedItem; if (MessageBox.Show($"Are you sure you want to delete : {additionalService.Name} ?", "Deleting", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) { additionalServicesList.Remove(additionalService); additionalServicesView.Refresh(); new AdditionalServiceDAO().Delete(additionalService); } }
public AdditionalServiceWindow(AdditionalService additionalService, Mode mode = Mode.ADD) { InitializeComponent(); this.additionalService = additionalService; this.mode = mode; if (mode == Mode.EDIT) { tbName.DataContext = additionalService; tbPrice.DataContext = additionalService; btnAddEditAdditionalService.Content = "Edit"; } }
public AddServiceViewModel(AddService view, ObservableCollection <AdditionalService> additionalServices, AdditionalService additionalService = null) { _view = view; _additionalServices = additionalServices; AdditionalService = additionalService ?? new AdditionalService(); using (var db = new ModelContainer()) { Services = new ObservableCollection <Service>(db.Services.ToList()); } SelectedService = Services.FirstOrDefault(x => x.Id == AdditionalService.ServiceId); SaveCommand = new Command(Save, CanExecuteCommand); }
private void Button_Click(object sender, RoutedEventArgs e) { AdditionalService additionalService = (AdditionalService)dgAllAdditionalServices.SelectedItem; int pieces = int.Parse(tbPieces.Text.Trim()); SaleItem <AdditionalService> asSaleItem = new SaleItem <AdditionalService>() { ProductForSale = additionalService, Pieces = pieces }; SalesmanWindow.servicesForSale.Add(asSaleItem); Close(); }
public static void AddAdditionalServiceOnBill(Bill bill, AdditionalService additionalService) { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString)) { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "INSERT INTO BillAdditionalServices(BillId, AdditionalServiceId) VALUES (@BillId, @AdditionalServiceId);"; cmd.CommandText += "SELECT SCOPE_IDENTITY();"; cmd.Parameters.AddWithValue("BillId", bill.ID); cmd.Parameters.AddWithValue("AdditionalServiceId", additionalService.ID); cmd.ExecuteNonQuery(); } }
public AdditionalService AddAdditioonalService(string name, string description, double price) { AdditionalService service = new AdditionalService { Name = name, Description = description, Price = price, }; _db.AdditionalServices.Add(service); _db.SaveChanges(); _memoryCache.Remove("services"); return(service); }
public void AddAdditionalService(int tourId, string content, decimal price) { var additionalService = new AdditionalService { Content = content, Price = price }; var tour = this.db.Tours.Where(t => t.Id == tourId).FirstOrDefault(); if (tour == null) { return; } tour.AdditionalServices.Add(additionalService); db.SaveChanges(); }
public ActionResult Create(AdditionalService obj) { try { if (ModelState.IsValid) { int id = db.AddAdditionalService(obj); return(RedirectToAction("Index")); } } catch (DataException ex) { ModelState.AddModelError("", ex.Message.ToString() + " Невозможно сохранить изменения. Попробуйте повторить действия. Если проблема повторится, обратитесь к системному администратору."); } return(RedirectToAction("Index")); }
public async Task <AdditionalService> Update(AdditionalService additionalServices) { var objfromDb = await _context.AdditionalServices.FirstOrDefaultAsync(x => x.IsDeleted == false && x.Id == additionalServices.Id); if (objfromDb != null) { objfromDb.Modified = DateTime.Now; objfromDb.ModifiedBy = ""; objfromDb.Name = additionalServices.Name; objfromDb.Active = additionalServices.Active; await _context.SaveChangesAsync(); return(objfromDb); } return(null); }
} // End of the constructor #endregion #region Insert methods /// <summary> /// Add one master post /// </summary> /// <param name="post">A reference to a additional service post</param> public static long AddMasterPost(AdditionalService post) { // Create the long to return long idOfInsert = 0; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "INSERT INTO dbo.additional_services (product_code, fee, unit_id, price_based_on_mount_time) " + "VALUES (@product_code, @fee, @unit_id, @price_based_on_mount_time);SELECT SCOPE_IDENTITY();"; // The using block is used to call dispose automatically even if there are an exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there are an exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@product_code", post.product_code); cmd.Parameters.AddWithValue("@fee", post.fee); cmd.Parameters.AddWithValue("@unit_id", post.unit_id); cmd.Parameters.AddWithValue("@price_based_on_mount_time", post.price_based_on_mount_time); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases try { // Open the connection cn.Open(); // Execute the insert idOfInsert = Convert.ToInt64(cmd.ExecuteScalar()); } catch (Exception e) { throw e; } } } // Return the id of the inserted item return idOfInsert; } // End of the AddMasterPost method
public HttpResponseMessage update(AdditionalService post, Int32 languageId = 0) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } else if (Language.MasterPostExists(languageId) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist"); } else if (Unit.MasterPostExists(post.unit_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The unit does not exist"); } else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The value added tax does not exist"); } // Make sure that the data is valid post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 50); post.name = AnnytabDataValidation.TruncateString(post.name, 100); post.fee = AnnytabDataValidation.TruncateDecimal(post.fee, 0, 9999999999.99M); post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10); // Get the saved post AdditionalService savedPost = AdditionalService.GetOneById(post.id, languageId); // Check if the service exists if (savedPost == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The record does not exist"); } // Update the post AdditionalService.UpdateMasterPost(post); AdditionalService.UpdateLanguagePost(post, languageId); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful"); } // End of the update method
} // End of the MasterPostExists method /// <summary> /// Get one additional service based on id /// </summary> /// <param name="additionalServiceId">A additional service id</param> /// <param name="languageId">The language id</param> /// <returns>A reference to a additional service post</returns> public static AdditionalService GetOneById(Int32 additionalServiceId, Int32 languageId) { // Create the post to return AdditionalService post = null; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.additional_services_detail AS D INNER JOIN dbo.additional_services AS A ON " + "D.additional_service_id = A.id WHERE A.id = @id AND D.language_id = @language_id;"; // The using block is used to call dispose automatically even if there is a exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add a parameters cmd.Parameters.AddWithValue("@id", additionalServiceId); cmd.Parameters.AddWithValue("@language_id", languageId); // Create a MySqlDataReader SqlDataReader reader = null; // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Fill the reader with one row of data. reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read and add values while (reader.Read()) { post = new AdditionalService(reader); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage. if (reader != null) reader.Close(); } } } // Return the post return post; } // End of the GetOneById method
} // End of the UpdateMasterPost method /// <summary> /// Update a language post /// </summary> /// <param name="post">A reference to a additional service post</param> /// <param name="languageId">The language id</param> public static void UpdateLanguagePost(AdditionalService post, Int32 languageId) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "UPDATE dbo.additional_services_detail SET name = @name, value_added_tax_id = @value_added_tax_id, " + "account_code = @account_code, inactive = @inactive WHERE additional_service_id = @id AND language_id = @language_id;"; // The using block is used to call dispose automatically even if there are an exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there are an exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@id", post.id); cmd.Parameters.AddWithValue("@language_id", languageId); cmd.Parameters.AddWithValue("@name", post.name); cmd.Parameters.AddWithValue("@value_added_tax_id", post.value_added_tax_id); cmd.Parameters.AddWithValue("@account_code", post.account_code); cmd.Parameters.AddWithValue("@inactive", post.inactive); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Execute the update cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } } // End of the UpdateLanguagePost method
} // End of the AddLanguagePost method #endregion #region Update methods /// <summary> /// Update a master post /// </summary> /// <param name="post">A reference to a additional service post</param> public static void UpdateMasterPost(AdditionalService post) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "UPDATE dbo.additional_services SET product_code = @product_code, fee = @fee, " + "unit_id = @unit_id, price_based_on_mount_time = @price_based_on_mount_time " + "WHERE id = @id;"; // The using block is used to call dispose automatically even if there are an exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there are an exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@id", post.id); cmd.Parameters.AddWithValue("@product_code", post.product_code); cmd.Parameters.AddWithValue("@fee", post.fee); cmd.Parameters.AddWithValue("@unit_id", post.unit_id); cmd.Parameters.AddWithValue("@price_based_on_mount_time", post.price_based_on_mount_time); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Execute the update cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } } // End of the UpdateMasterPost method
public ActionResult translate(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor", "Translator" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get the admin default language Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get all the form values Int32 translationLanguageId = Convert.ToInt32(collection["selectLanguage"]); Int32 id = Convert.ToInt32(collection["hiddenAdditionalServiceId"]); string name = collection["txtTranslatedName"]; Int32 value_added_tax_id = Convert.ToInt32(collection["selectValueAddedTax"]); string account_code = collection["txtAccountCode"]; bool inactive = Convert.ToBoolean(collection["cbInactive"]); // Create the translated additional service AdditionalService translatedAdditionalService = new AdditionalService(); translatedAdditionalService.id = id; translatedAdditionalService.name = name; translatedAdditionalService.value_added_tax_id = value_added_tax_id; translatedAdditionalService.account_code = account_code; translatedAdditionalService.inactive = inactive; // Create a error message string errorMessage = string.Empty; // Check for errors if (translatedAdditionalService.name.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "100") + "<br/>"; } if (translatedAdditionalService.value_added_tax_id == 0) { errorMessage += "• " + String.Format(tt.Get("error_select_value"), tt.Get("value_added_tax").ToLower()) + "<br/>"; } if (translatedAdditionalService.account_code.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("account_code"), "10") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Get the saved additional service AdditionalService additionalService = AdditionalService.GetOneById(id, translationLanguageId); if (additionalService == null) { // Add a new translated additional service AdditionalService.AddLanguagePost(translatedAdditionalService, translationLanguageId); } else { // Update the translated additional service additionalService.name = translatedAdditionalService.name; additionalService.value_added_tax_id = translatedAdditionalService.value_added_tax_id; additionalService.account_code = translatedAdditionalService.account_code; additionalService.inactive = translatedAdditionalService.inactive; AdditionalService.UpdateLanguagePost(additionalService, translationLanguageId); } // Redirect the user to the list return Redirect("/admin_additional_services" + returnUrl); } else { // Set form values ViewBag.LanguageId = translationLanguageId; ViewBag.Languages = Language.GetAll(adminLanguageId, "name", "ASC"); ViewBag.StandardAdditionalService = AdditionalService.GetOneById(id, adminLanguageId); ViewBag.TranslatedAdditionalService = translatedAdditionalService; ViewBag.ErrorMessage = errorMessage; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the translate view return View("translate"); } } // End of the translate method
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the form values Int32 id = Convert.ToInt32(collection["txtId"]); string product_code = collection["txtProductCode"]; string name = collection["txtName"]; decimal fee = 0; decimal.TryParse(collection["txtFee"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out fee); Int32 unit_id = Convert.ToInt32(collection["selectUnit"]); bool price_based_on_mount_time = Convert.ToBoolean(collection["cbPriceBasedOnMountTime"]); Int32 value_added_tax_id = Convert.ToInt32(collection["selectValueAddedTax"]); string account_code = collection["txtAccountCode"]; bool inactive = Convert.ToBoolean(collection["cbInactive"]); // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get the additional service AdditionalService additionalService = AdditionalService.GetOneById(id, adminLanguageId); // Check if the additional service exists if (additionalService == null) { // Create a empty additional service additionalService = new AdditionalService(); } // Update values additionalService.product_code = product_code; additionalService.name = name; additionalService.fee = fee; additionalService.unit_id = unit_id; additionalService.price_based_on_mount_time = price_based_on_mount_time; additionalService.value_added_tax_id = value_added_tax_id; additionalService.account_code = account_code; additionalService.inactive = inactive; // Create a error message string errorMessage = string.Empty; // Check for errors in the additional service if (additionalService.product_code.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("product_code"), "50") + "<br/>"; } if (additionalService.name.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "100") + "<br/>"; } if (additionalService.fee < 0 || additionalService.fee > 9999999999.99M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("fee"), "9 999 999 999.99") + "<br/>"; } if (additionalService.account_code.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("account_code"), "10") + "<br/>"; } if (additionalService.unit_id == 0) { errorMessage += "• " + String.Format(tt.Get("error_select_value"), tt.Get("unit").ToLower()) + "<br/>"; } if (additionalService.value_added_tax_id == 0) { errorMessage += "• " + String.Format(tt.Get("error_select_value"), tt.Get("value_added_tax").ToLower()) + "<br/>"; } // Check if there is errors if (errorMessage == "") { // Check if we should add or update the additional service if (additionalService.id == 0) { // Add the additional service Int64 insertId = AdditionalService.AddMasterPost(additionalService); additionalService.id = Convert.ToInt32(insertId); AdditionalService.AddLanguagePost(additionalService, adminLanguageId); } else { // Update the additional service AdditionalService.UpdateMasterPost(additionalService); AdditionalService.UpdateLanguagePost(additionalService, adminLanguageId); } // Redirect the user to the list return Redirect("/admin_additional_services" + returnUrl); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.Units = Unit.GetAll(adminLanguageId, "name", "ASC"); ViewBag.AdditionalService = additionalService; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method