protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { MovieCatalogBL context = new MovieCatalogBL(); var query = context.GetMoviesExpiry(); ListView2.DataSource = query; ListView2.DataBind(); } catch (Exception) { lblMessage2.Text = "An error occurred while retrieving movies. Please try again."; lblMessage2.Attributes.Add("style", "color:red; font: bold 14px/16px Sans-Serif,Arial"); } } }
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { try { int movieID = Convert.ToInt32(e.Keys[0]); string movieTitle = e.Values["OriginalName"].ToString(); MovieCatalogBL context = new MovieCatalogBL(); context.DeleteMovieByID(movieID); //FilterMovies(); // after deletion rebind gridview with filter FilterButton_Click(sender, e); lblMessage.Text = "Movie: " + movieID + "-" + movieTitle + " deleted!"; //Server.Transfer("~/Default.aspx"); //Response.Redirect("~/Default.aspx"); } catch (Exception) { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "An error occurred while deleting movie record. Make sure that movie exists. " + "It is possible that other user deleted movie record."; } }
// try catch block for exception handling is added where "FilterMovies()" method is called protected List <Movie> FilterMovies() { MovieCatalogBL context1 = new MovieCatalogBL(); // if both Items are selected if (selectedItems == 2) { // select only those movies which have SVODRights and AncillaryRights set to "Yes" // var query = context2.Movies.Where(m => m.SVODRights == "Yes" && m.AncillaryRights == "Yes").ToList(); var query1 = context1.GetMovies().Where(m => m.SVODRights == "Yes" && m.AncillaryRights == "Yes").ToList(); return(query1); } // if only one (first) Item is selected else if (filterMoviesCheckBoxList.SelectedIndex == 0) { // if index is 0 then only first rights (SVOD), else only second rights (Ancillary) var query1 = context1.GetMovies().Where(m => m.SVODRights == "Yes").ToList(); return(query1); } else // try this - (filterMoviesCheckBoxList.SelectedIndex == 1) -> NO! { // if index NOT 0 then only second rights (Ancillary) - (if index NOT 0 then it's 1, because there is only 2 items in list) var query1 = context1.GetMovies().Where(m => m.AncillaryRights == "Yes").ToList(); return(query1); } }
protected void btnExportToExcel_Click(object sender, EventArgs e) { try { MovieCatalogBL context = new MovieCatalogBL(); List <Movie> movieList = context.GetMovies().ToList(); if (movieList.Count > 0) { string path = Server.MapPath("~/exportedfiles/"); if (!Directory.Exists(path)) // CHECK IF THE FOLDER EXISTS. IF NOT, CREATE A NEW FOLDER. { Directory.CreateDirectory(path); } // "File.Delete" method does not throw an exception when a file doesn't exist. File.Delete(path + "Movies.xls"); // DELETE THE FILE BEFORE CREATING A NEW ONE. // ADD A WORKBOOK USING THE EXCEL APPLICATION. Excel.Application xlAppToExport = new Excel.Application(); xlAppToExport.Workbooks.Add(""); // ADD A WORKSHEET. Excel.Worksheet xlWorkSheetToExport = default(Excel.Worksheet); xlWorkSheetToExport = (Excel.Worksheet)xlAppToExport.Sheets["Sheet1"]; // ROW ID FROM WHERE THE DATA STARTS SHOWING. int iRowCnt = 4; // SHOW THE HEADER. xlWorkSheetToExport.Cells[1, 1] = "Movies list."; Excel.Range range = xlWorkSheetToExport.Cells[1, 1] as Excel.Range; range.EntireRow.Font.Name = "Arial"; range.EntireRow.Font.Bold = true; range.EntireRow.Font.Size = 20; // Depends how long the title is xlWorkSheetToExport.Range["A1:F1"].MergeCells = true; // MERGE CELLS OF THE HEADER. // SHOW COLUMNS ON THE TOP. xlWorkSheetToExport.Cells[iRowCnt - 1, 1] = "Title"; xlWorkSheetToExport.Cells[iRowCnt - 1, 2] = "Country"; xlWorkSheetToExport.Cells[iRowCnt - 1, 3] = "Genre"; xlWorkSheetToExport.Cells[iRowCnt - 1, 4] = "Year Of Production"; xlWorkSheetToExport.Cells[iRowCnt - 1, 5] = "Content Provider"; xlWorkSheetToExport.Cells[iRowCnt - 1, 6] = "Duration"; xlWorkSheetToExport.Cells[iRowCnt - 1, 7] = "IPTV Rights"; xlWorkSheetToExport.Cells[iRowCnt - 1, 8] = "VOD Rights"; xlWorkSheetToExport.Cells[iRowCnt - 1, 9] = "SVOD Rights"; xlWorkSheetToExport.Cells[iRowCnt - 1, 10] = "Ancillary Rights"; xlWorkSheetToExport.Cells[iRowCnt - 1, 11] = "Start Date"; xlWorkSheetToExport.Cells[iRowCnt - 1, 12] = "Expiry Date"; xlWorkSheetToExport.Cells[iRowCnt - 1, 13] = "Comment"; foreach (var item in movieList) { xlWorkSheetToExport.Cells[iRowCnt, 1] = item.OriginalName; xlWorkSheetToExport.Cells[iRowCnt, 2] = item.Country; xlWorkSheetToExport.Cells[iRowCnt, 3] = item.Genre; xlWorkSheetToExport.Cells[iRowCnt, 4] = item.Year; xlWorkSheetToExport.Cells[iRowCnt, 5] = item.ContentProvider; // Duration has to be converted to string (Duration.ToString()), otherwise data can not be exported xlWorkSheetToExport.Cells[iRowCnt, 6] = item.Duration.ToString(); xlWorkSheetToExport.Cells[iRowCnt, 7] = item.RightsIPTV; xlWorkSheetToExport.Cells[iRowCnt, 8] = item.RightsVOD; xlWorkSheetToExport.Cells[iRowCnt, 9] = item.SVODRights; xlWorkSheetToExport.Cells[iRowCnt, 10] = item.AncillaryRights; xlWorkSheetToExport.Cells[iRowCnt, 11] = item.StartDate; xlWorkSheetToExport.Cells[iRowCnt, 12] = item.ExpireDate; xlWorkSheetToExport.Cells[iRowCnt, 13] = item.Comment; iRowCnt = iRowCnt + 1; } // FINALLY, FORMAT THE EXCEL SHEET USING EXCEL'S AUTOFORMAT FUNCTION. Excel.Range range1 = xlAppToExport.ActiveCell.Worksheet.Cells[4, 1] as Excel.Range; range1.AutoFormat(ExcelAutoFormat.xlRangeAutoFormatList3); // Set width of Column xlWorkSheetToExport.Columns[2].ColumnWidth = 25; xlWorkSheetToExport.Columns[7].ColumnWidth = 25; xlWorkSheetToExport.Columns[8].ColumnWidth = 25; // SAVE THE FILE IN A FOLDER. (XLS or XLSX format) xlWorkSheetToExport.SaveAs(path + "Movies.xls"); // xlWorkSheetToExport.SaveAs(path + "Movies.xlsx"); // CLEAR. xlAppToExport.Workbooks.Close(); xlAppToExport.Quit(); xlAppToExport = null; xlWorkSheetToExport = null; lblMessage.Text = "Data Exported."; lblMessage.Attributes.Add("style", "color:green; font: bold 14px/16px Sans-Serif,Arial"); } } catch (IOException) { lblMessage.Text = "There was an error while exporting data. Check if file is in use by another application (MS Excel)."; lblMessage.Attributes.Add("style", "color:red; font: bold 14px/16px Sans-Serif,Arial"); } catch (Exception) { lblMessage.Text = "There was an error while exporting data. Try again."; lblMessage.Attributes.Add("style", "color:red; font: bold 14px/16px Sans-Serif,Arial"); } }
private void BindGridView1() { //try - START try { // if "sortDirection" is not set then on first PageLoad there will be error string sortDirection = "ASC"; string sortExpression = ""; MovieCatalogBL context = new MovieCatalogBL(); var query = context.GetMovies(); // if there is no filter - get all movies if (filterMoviesCheckBoxList.SelectedIndex == -1) { query = context.GetMovies(); if (ViewState["SortDirection"] != null) { sortDirection = ViewState["SortDirection"].ToString(); } if (ViewState["SortExpression"] != null) { sortExpression = ViewState["SortExpression"].ToString(); if (sortDirection == "ASC") { query = query.OrderBy(mov => mov.GetType().GetProperty(sortExpression).GetValue(mov, null)).ToList(); } else if (sortDirection == "DESC") { query = query.OrderByDescending(mov => mov.GetType().GetProperty(sortExpression).GetValue(mov, null)).ToList(); } } } // END OF: if there is no filter - get all movies // If there is filter - Start else { if (ViewState["SortDirection"] != null) { sortDirection = ViewState["SortDirection"].ToString(); } if (ViewState["SortExpression"] != null) { sortExpression = ViewState["SortExpression"].ToString(); if (sortDirection == "ASC") { query = FilterMovies().OrderBy(mov => mov.GetType().GetProperty(sortExpression).GetValue(mov, null)).ToList(); } else if (sortDirection == "DESC") { query = FilterMovies().OrderByDescending(mov => mov.GetType().GetProperty(sortExpression).GetValue(mov, null)).ToList(); } } } // If there is filter - END GridView1.DataSource = query; GridView1.DataBind(); // TRY -END } catch (Exception ex) { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "An error occurred while retrieving movies. Please try again." + "<br/>" + ex.ToString(); } }
protected void MovieDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e) { try { MovieCatalogBL contextBL = new MovieCatalogBL(); string contentProvider = null; if (e.Values["ContentProvider"] == null || e.Values["ContentProvider"].ToString() == "") { contentProvider = ""; } else { contentProvider = e.Values["ContentProvider"].ToString(); } string title = e.Values["OriginalName"].ToString(); string genre = e.Values["Genre"].ToString(); //msdn.microsoft.com/en-us/library/system.timespan%28v=vs.110%29.aspx //string value = "12:12:15"; //TimeSpan ts = TimeSpan.Parse(value); TimeSpan movieDuration = TimeSpan.Zero; // find DropDownList control inside DetailsView DropDownList ddlHours = (DropDownList)MovieDetailsView.FindControl("ddlHours"); DropDownList ddlMinutes = (DropDownList)MovieDetailsView.FindControl("ddlMinutes"); DropDownList ddlSeconds = (DropDownList)MovieDetailsView.FindControl("ddlSeconds"); string hours = ddlHours.SelectedValue.ToString().Trim(); string minutes = ddlMinutes.SelectedValue.ToString().Trim(); string seconds = ddlSeconds.SelectedValue.ToString().Trim(); //string value = "12:12:15"; //TimeSpan ts = TimeSpan.Parse(value); string duration1 = hours + ":" + minutes + ":" + seconds; movieDuration = TimeSpan.Parse(duration1); string country = e.Values["Country"].ToString(); string rightsIPTV = null; if (e.Values["RightsIPTV"] == null || e.Values["RightsIPTV"].ToString() == "") { rightsIPTV = string.Empty; } else { rightsIPTV = e.Values["RightsIPTV"].ToString(); } string rightsVOD = null; if (e.Values["RightsVOD"] == null || e.Values["RightsVOD"].ToString() == "") { rightsVOD = string.Empty; } else { rightsVOD = e.Values["RightsVOD"].ToString(); } string svodRights = null; if (e.Values["SVODRights"] == null || e.Values["SVODRights"].ToString() == "") { svodRights = string.Empty; } else { svodRights = e.Values["SVODRights"].ToString(); } string ancillaryRights = null; if (e.Values["AncillaryRights"] == null || e.Values["AncillaryRights"].ToString() == "") { ancillaryRights = string.Empty; } else { ancillaryRights = e.Values["AncillaryRights"].ToString(); } DateTime startDate = Convert.ToDateTime(e.Values["StartDate"]); DateTime expireDate = Convert.ToDateTime(e.Values["ExpireDate"]); int result = DateTime.Compare(startDate, expireDate); string relationship = "Expiry Date is earlier than Start Date !"; //msdn.microsoft.com/en-us/library/5ata5aya%28v=vs.110%29.aspx // if startDate is later than expireDate result is (1) greater than 0 (zero) if (result > 0) { e.Cancel = true; ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + relationship + "');", true); return; } string comment = null; if (e.Values["Comment"] == null || e.Values["Comment"].ToString() == "") { comment = string.Empty; } else { comment = e.Values["Comment"].ToString(); } Int16 year = Convert.ToInt16(e.Values["Year"]); contextBL.InsertMovie(contentProvider, title, genre, movieDuration, country, rightsIPTV, rightsVOD, svodRights, ancillaryRights, startDate, expireDate, comment, year); lblMessage.ForeColor = System.Drawing.Color.Black; lblMessage.Text = "Movie " + title + " added."; } catch (InvalidOperationException) { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Error while adding new movie. Invalid data provided. Please try again."; } catch (Exception) { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Error while adding new movie. Please try again."; } }
protected void MovieDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e) { try { MovieCatalogBL contextBL = new MovieCatalogBL(); var movieToUpdate = contextBL.GetMovieByID(movieID); string contentProvider = null; if (e.NewValues["ContentProvider"] == null || e.NewValues["ContentProvider"].ToString() == "") { contentProvider = ""; } else { contentProvider = e.NewValues["ContentProvider"].ToString(); } string title = e.NewValues["OriginalName"].ToString(); string genre = e.NewValues["Genre"].ToString(); //msdn.microsoft.com/en-us/library/system.timespan%28v=vs.110%29.aspx //string value = "12:12:15"; //TimeSpan ts = TimeSpan.Parse(value); TimeSpan movieDuration = TimeSpan.Zero; // find DropDownList control inside DetailsView DropDownList ddlHours = (DropDownList)MovieDetailsView.FindControl("ddlHours"); DropDownList ddlMinutes = (DropDownList)MovieDetailsView.FindControl("ddlMinutes"); DropDownList ddlSeconds = (DropDownList)MovieDetailsView.FindControl("ddlSeconds"); string hours = ddlHours.SelectedValue.ToString().Trim(); string minutes = ddlMinutes.SelectedValue.ToString().Trim(); string seconds = ddlSeconds.SelectedValue.ToString().Trim(); //string value = "12:12:15"; //TimeSpan ts = TimeSpan.Parse(value); string duration1 = hours + ":" + minutes + ":" + seconds; movieDuration = TimeSpan.Parse(duration1); string country = e.NewValues["Country"].ToString(); string rightsIPTV = null; if (e.NewValues["RightsIPTV"] == null || e.NewValues["RightsIPTV"].ToString() == "") { rightsIPTV = string.Empty; } else { rightsIPTV = e.NewValues["RightsIPTV"].ToString(); } string rightsVOD = null; if (e.NewValues["RightsVOD"] == null || e.NewValues["RightsVOD"].ToString() == "") { rightsVOD = string.Empty; } else { rightsVOD = e.NewValues["RightsVOD"].ToString(); } string svodRights = null; if (e.NewValues["SVODRights"] == null || e.NewValues["SVODRights"].ToString() == "") { svodRights = string.Empty; } else { svodRights = e.NewValues["SVODRights"].ToString(); } string ancillaryRights = null; if (e.NewValues["AncillaryRights"] == null || e.NewValues["AncillaryRights"].ToString() == "") { ancillaryRights = string.Empty; } else { ancillaryRights = e.NewValues["AncillaryRights"].ToString(); } DateTime startDate = Convert.ToDateTime(e.NewValues["StartDate"]); DateTime expireDate = Convert.ToDateTime(e.NewValues["ExpireDate"]); int result = DateTime.Compare(startDate, expireDate); string relationship = "Expiry Date is earlier than Start Date !"; //msdn.microsoft.com/en-us/library/5ata5aya%28v=vs.110%29.aspx // if startDate is later than expireDate result is (1) greater than 0 (zero) if (result > 0) { // instead of "e.Cancel = true;" can be -> ((DetailsViewInsertEventArgs)e).Cancel = true; // www.noordam.it/validating-detailsview-field-NewValues-during-insert-and-update/ // has to be 'return' after 'e.Cancel = true;' -> at least in some cases e.Cancel = true; ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + relationship + "');", true); return; } string comment = null; if (e.NewValues["Comment"] == null || e.NewValues["Comment"].ToString() == "") { comment = string.Empty; } else { comment = e.NewValues["Comment"].ToString(); } Int16 year = Convert.ToInt16(e.NewValues["Year"]); contextBL.UpdateMovieByID(movieID, contentProvider, title, genre, movieDuration, country, rightsIPTV, rightsVOD, svodRights, ancillaryRights, startDate, expireDate, comment, year); lblMessage.ForeColor = System.Drawing.Color.Black; lblMessage.Text = "Movie " + title + " updated."; } catch (DbUpdateException) { lblMessage.Text = "Update Exception. Error while updating movie data. Please try again."; } catch (NullReferenceException) { lblMessage.Text = "An error occurred while updating movie. Make sure that movie exists."; } catch (ArgumentNullException) { lblMessage.Text = "ArgumentNullException: An error occurred while updating movie. Make sure that movie exists."; } catch (Exception) { lblMessage.Text = "An error occurred while updating movie. Please try again."; } }
protected void Page_Load(object sender, EventArgs e) { // check QueryString not null OR empty - if null OR empty redirect to Previous page if (Request.QueryString["Id"] == null || Request.QueryString["Id"] == "") { Response.Redirect("Default.aspx"); } movieID = Convert.ToInt32(Request.QueryString["Id"]); if (!IsPostBack) { MovieCatalogBL contextBL = new MovieCatalogBL(); try { var queryMovieByID2 = contextBL.GetMovieByID(movieID); // needs to be List MovieDetailsView.DataSource = queryMovieByID2.ToList(); MovieDetailsView.DataBind(); // find DropDownList control inside DetailsView DropDownList ddlHours = (DropDownList)MovieDetailsView.FindControl("ddlHours"); DropDownList ddlMinutes = (DropDownList)MovieDetailsView.FindControl("ddlMinutes"); DropDownList ddlSeconds = (DropDownList)MovieDetailsView.FindControl("ddlSeconds"); // Time DropDownList for (int index = 0; index < 24; index++) { ddlHours.Items.Add(index.ToString("00")); } for (int index = 0; index < 60; index++) { ddlMinutes.Items.Add(index.ToString("00")); ddlSeconds.Items.Add(index.ToString("00")); } // for Calendar control -- Year & Month DropDownLists LoadYears(); LoadMonths(); // for movie production (make) year LoadProductionYears(); DropDownList ddlProductionYear = (DropDownList)MovieDetailsView.FindControl("DropDownListProductionYear"); // set year in DropDownListProductionYear ddlProductionYear.Text = queryMovieByID2.FirstOrDefault().Year.ToString(); // get Duration of movie TimeSpan duration = queryMovieByID2.FirstOrDefault().Duration.Value; // set the text of ddl's for hours, minutes and seconds ddlHours.Text = duration.Hours.ToString("00"); ddlMinutes.Text = duration.Minutes.ToString("00"); ddlSeconds.Text = duration.Seconds.ToString("00"); // Fill CheckBoxLists with countries CheckBoxList ddlCountry = (CheckBoxList)MovieDetailsView.FindControl("ddlCountry"); ddlCountry.DataSource = CountriesList(); ddlCountry.DataBind(); CheckBoxList ddlCountriesIPTV = (CheckBoxList)MovieDetailsView.FindControl("ddlCountriesIPTV"); ddlCountriesIPTV.DataSource = CountriesList(); ddlCountriesIPTV.DataBind(); CheckBoxList ddlCountriesVOD = (CheckBoxList)MovieDetailsView.FindControl("ddlCountriesVOD"); ddlCountriesVOD.DataSource = CountriesList(); ddlCountriesVOD.DataBind(); // select countries in ddlCountry string countriesMovie = queryMovieByID2.FirstOrDefault().Country; //Convert the string into an array of words string[] countryArray = countriesMovie.Split(new char[] { '?', '!', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries); // has to be 'ListItem' "(ListItem item in ddlCountry.Items)" -> NOT "var"(var item in ddlCountries.Items) foreach (ListItem item in ddlCountry.Items) { for (int k = 0; k < countryArray.Length; k++) { if (item.ToString().ToUpperInvariant() == countryArray[k].ToUpperInvariant().Trim()) { item.Selected = true; } } } // select countries in ddlIPTV string countriesIPTV = queryMovieByID2.FirstOrDefault().RightsIPTV; //Convert the string into an array of words string[] iptvArray = countriesIPTV.Split(new char[] { '?', '!', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries); // has to be 'ListItem' "(ListItem item in ddlcountriesIPTV.Items)" -> NOT "var"(var item in ddlCountries.Items) foreach (ListItem item in ddlCountriesIPTV.Items) { for (int k = 0; k < iptvArray.Length; k++) { if (item.ToString().ToUpperInvariant() == iptvArray[k].ToUpperInvariant().Trim()) { item.Selected = true; } } } // select countries in ddlVOD string countriesVOD = queryMovieByID2.FirstOrDefault().RightsVOD; //Convert the string into an array of words string[] VODArray = countriesVOD.Split(new char[] { '?', '!', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries); // has to be 'ListItem' "(ListItem item in ddlCountriesVOD.Items)" -> NOT "var"(var item in ddlCountriesVOD.Items) foreach (ListItem item in ddlCountriesVOD.Items) { for (int k = 0; k < VODArray.Length; k++) { if (item.ToString().ToUpperInvariant() == VODArray[k].ToUpperInvariant().Trim()) { item.Selected = true; } } } // set text/value in DropdDownCheckBox Controls: ddlAncillaryRights and ddlSVODRights string svodRights = queryMovieByID2.FirstOrDefault().SVODRights.ToString(); string ancillaryRights = queryMovieByID2.FirstOrDefault().AncillaryRights.ToString(); DropDownList ddlAncillaryRights = (DropDownList)MovieDetailsView.FindControl("ddlAncillaryRights"); DropDownList ddlSVODRights = (DropDownList)MovieDetailsView.FindControl("ddlSVODRights"); ddlAncillaryRights.Text = ancillaryRights; ddlSVODRights.Text = svodRights; // set the date in startDateCalendar and make it visible in control DateTime startDate = (DateTime)queryMovieByID2.First().StartDate; System.Web.UI.WebControls.Calendar startDateCalendar = (System.Web.UI.WebControls.Calendar)MovieDetailsView.FindControl("startDateCalendar"); startDateCalendar.SelectedDate = startDate; startDateCalendar.VisibleDate = startDate; // set the Year and Month in ddlStartYear and ddlStartMonth DropDownList ddlStartYear = (DropDownList)MovieDetailsView.FindControl("DropDownListYear"); DropDownList ddlStartMonth = (DropDownList)MovieDetailsView.FindControl("DropDownListMonth"); ddlStartYear.Text = startDate.Year.ToString(); ddlStartMonth.Text = startDate.Month.ToString(); // set the date in expiryDateCalendar and make it visible in control DateTime expiryDate = (DateTime)queryMovieByID2.First().ExpireDate; System.Web.UI.WebControls.Calendar expiryDateCalendar = (System.Web.UI.WebControls.Calendar)MovieDetailsView.FindControl("expireDateCalendar"); expiryDateCalendar.SelectedDate = expiryDate; expiryDateCalendar.VisibleDate = expiryDate; // set the Year and Month in ddlExpiryYear and ddlExpiryMonth DropDownList ddlExpiryYear = (DropDownList)MovieDetailsView.FindControl("DropDownListExpireYear"); DropDownList ddlExpiryMonth = (DropDownList)MovieDetailsView.FindControl("DropDownListExpireMonth"); ddlExpiryYear.Text = expiryDate.Year.ToString(); ddlExpiryMonth.Text = expiryDate.Month.ToString(); } catch (Exception) { lblMessage.Text = "An error occurred. Please try again."; } } }