public static Common.DTO.EventDto ToDtoEvent(DAL.Event e) { Common.DTO.EventDto ev = new Common.DTO.EventDto(); ev.event_code = e.event_code; ev.invitation = e.invitation; return(ev); }
public static DAL.Event ToDalEvent(Common.DTO.EventDto e) { DAL.Event ev = new DAL.Event(); ev.event_code = e.event_code; ev.invitation = e.invitation; ///.... return(ev); }
public static Event GetFromEntity(DAL.Event data) { return(new Event() { Description = data.Description, EventDate = data.EventDate, Id = data.Id, LayoutId = data.LayoutId, Name = data.Name }); }
public void FormView1_InsertItem() { var item = new DAL.Event(); TryUpdateModel(item); if (ModelState.IsValid) { // Save changes here HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:44611"); client.PostAsJsonAsync("api/Events", item); } }
public void ProcessRequest(HttpContext context) { var jsonResponse = new JsonEvent(); if(context.Request.QueryString["EventId"] == null) { jsonResponse.Success = false; jsonResponse.ErrorMessage = "No event id provided."; this.Log().Error(string.Format("Event requested from {0}?{1} with no id.", context.Request.Url, context.Request.QueryString)); } else { int eventId = 0; if(!int.TryParse(context.Request["EventId"].ToString(), out eventId)) { jsonResponse.Success = false; jsonResponse.ErrorMessage = "Invalid event id provided."; this.Log().Error(string.Format("Requested event {0} from {1}?{2} - invalid id", context.Request["EventId"].ToString(), context.Request.Url, context.Request.QueryString)); } else { DAL.Event e = new DAL.Event().FetchObject(eventId); if(e == null) { jsonResponse.Success = false; jsonResponse.ErrorMessage = "Event not found."; this.Log().Error(string.Format("Requested event {0} from {1}?{2} - not found", eventId, context.Request.Url, context.Request.QueryString)); } else { var cf = CustomEventFields.FetchObject(); jsonResponse.Success = true; jsonResponse.Title = e.EventTitle; jsonResponse.ShortDescription = e.ShortDescription; jsonResponse.Description = context.Server.HtmlDecode(e.HTML); jsonResponse.When = Event.DisplayEventDateTime(e); if(e.BranchID > 0) { var codeObject = DAL.Codes.FetchObject(e.BranchID); if(codeObject != null) { jsonResponse.Where = codeObject.Description; } } if(!string.IsNullOrWhiteSpace(e.Custom1) && !string.IsNullOrWhiteSpace(cf.Label1)) { jsonResponse.CustomLabel1 = cf.Label1; jsonResponse.CustomValue1 = e.Custom1; } if(!string.IsNullOrWhiteSpace(e.Custom2) && !string.IsNullOrWhiteSpace(cf.Label2)) { jsonResponse.CustomLabel2 = cf.Label2; jsonResponse.CustomValue2 = e.Custom2; } if(!string.IsNullOrWhiteSpace(e.Custom3) && !string.IsNullOrWhiteSpace(cf.Label3)) { jsonResponse.CustomLabel3 = cf.Label3; jsonResponse.CustomValue3 = e.Custom3; } } } } context.Response.ContentType = "application/json"; var settings = new JsonSerializerSettings(); settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml; context.Response.Write(JsonConvert.SerializeObject(jsonResponse, settings)); }
public void ProcessRequest(HttpContext context) { var jsonResponse = new JsonEvent(); if (context.Request.QueryString["EventId"] == null) { jsonResponse.Success = false; jsonResponse.ErrorMessage = "No event id provided."; this.Log().Error(string.Format("Event requested from {0}?{1} with no id.", context.Request.Url, context.Request.QueryString)); } else { int eventId = 0; if (!int.TryParse(context.Request["EventId"].ToString(), out eventId)) { jsonResponse.Success = false; jsonResponse.ErrorMessage = "Invalid event id provided."; this.Log().Error(string.Format("Requested event {0} from {1}?{2} - invalid id", context.Request["EventId"].ToString(), context.Request.Url, context.Request.QueryString)); } else { DAL.Event e = new DAL.Event().FetchObject(eventId); if (e == null || e.HiddenFromPublic == true) { jsonResponse.Success = false; jsonResponse.ErrorMessage = "Event not found."; this.Log().Error(string.Format("Requested event {0} from {1}?{2} - not found", eventId, context.Request.Url, context.Request.QueryString)); } else { var cf = CustomEventFields.FetchObject(); jsonResponse.Success = true; jsonResponse.Title = e.EventTitle; jsonResponse.ExternalLink = e.ExternalLinkToEvent; jsonResponse.Description = context.Server.HtmlDecode(e.HTML); jsonResponse.When = Event.DisplayEventDateTime(e); if (e.BranchID > 0) { string branchName = string.Empty; var codeObject = DAL.Codes.FetchObject(e.BranchID); if (codeObject != null) { jsonResponse.Where = codeObject.Description; } var crosswalk = DAL.LibraryCrosswalk.FetchObjectByLibraryID(e.BranchID); if (crosswalk != null) { if (!string.IsNullOrEmpty(jsonResponse.Where) && !string.IsNullOrEmpty(crosswalk.BranchLink)) { jsonResponse.Where = string.Format(WebTools.BranchLinkStub, crosswalk.BranchLink, jsonResponse.Where); } if (!string.IsNullOrEmpty(jsonResponse.Where) && !string.IsNullOrEmpty(crosswalk.BranchAddress)) { jsonResponse.Where += string.Format(WebTools.BranchMapStub, HttpUtility.UrlEncode(crosswalk.BranchAddress)); } } } if (!string.IsNullOrWhiteSpace(e.Custom1) && !string.IsNullOrWhiteSpace(cf.Label1)) { jsonResponse.CustomLabel1 = cf.Label1; jsonResponse.CustomValue1 = e.Custom1; } if (!string.IsNullOrWhiteSpace(e.Custom2) && !string.IsNullOrWhiteSpace(cf.Label2)) { jsonResponse.CustomLabel2 = cf.Label2; jsonResponse.CustomValue2 = e.Custom2; } if (!string.IsNullOrWhiteSpace(e.Custom3) && !string.IsNullOrWhiteSpace(cf.Label3)) { jsonResponse.CustomLabel3 = cf.Label3; jsonResponse.CustomValue3 = e.Custom3; } } } } context.Response.ContentType = "application/json"; var settings = new JsonSerializerSettings(); settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml; context.Response.Write(JsonConvert.SerializeObject(jsonResponse, settings)); }
protected void Page_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(Request["PID"])) { Session["ProgramID"] = Request["PID"].ToString(); } if (!IsPostBack) { if (Session["ProgramID"] == null) { try { int PID = Programs.GetDefaultProgramID(); Session["ProgramID"] = PID.ToString(); } catch { Response.Redirect("~/Default.aspx"); } } } TranslateStrings(this); if (Request.UrlReferrer == null) { eventBackLink.NavigateUrl = "~/Events/"; } else { eventBackLink.NavigateUrl = Request.UrlReferrer.AbsolutePath; } DAL.Event evnt = null; int eventId = 0; string displayEvent = Request.QueryString["EventId"]; if (!string.IsNullOrEmpty(displayEvent) && int.TryParse(displayEvent.ToString(), out eventId)) { evnt = DAL.Event.GetEvent(eventId); if (evnt != null) { eventTitle.Text = evnt.EventTitle; this.Title = string.Format("'{0}' Event Details", eventTitle.Text); this.MetaDescription = string.Format("Details about the event: {0} - {1}", eventTitle.Text, GetResourceString("system-name")); eventWhen.Text = DAL.Event.DisplayEventDateTime(evnt); if (evnt.BranchID > 0) { var codeObject = DAL.Codes.FetchObject(evnt.BranchID); if (codeObject != null) { eventWhere.Text = codeObject.Description; } } if (string.IsNullOrWhiteSpace(eventWhere.Text)) { eventWhere.Visible = false; atLabel.Visible = false; } else { eventWhere.Visible = true; atLabel.Visible = true; } eventShortDescription.Text = evnt.ShortDescription; eventDescription.Text = evnt.HTML; var cf = DAL.CustomEventFields.FetchObject(); if (!string.IsNullOrWhiteSpace(evnt.Custom1) && !string.IsNullOrWhiteSpace(cf.Label1)) { eventCustom1Panel.Visible = true; eventCustomLabel1.Text = cf.Label1; eventCustomValue1.Text = evnt.Custom1; } else { eventCustom1Panel.Visible = false; } if (!string.IsNullOrWhiteSpace(evnt.Custom2) && !string.IsNullOrWhiteSpace(cf.Label2)) { eventCustom2Panel.Visible = true; eventCustomLabel2.Text = cf.Label2; eventCustomValue2.Text = evnt.Custom2; } else { eventCustom2Panel.Visible = false; } if (!string.IsNullOrWhiteSpace(evnt.Custom3) && !string.IsNullOrWhiteSpace(cf.Label3)) { eventCustom3Panel.Visible = true; eventCustomLabel3.Text = cf.Label3; eventCustomValue3.Text = evnt.Custom3; } else { eventCustom3Panel.Visible = false; } eventDetails.Visible = true; } } if (evnt == null) { eventDetails.Visible = false; var cph = Page.Master.FindControl("HeaderContent") as ContentPlaceHolder; if (cph != null) { cph.Controls.Add(new HtmlMeta { Name = "robots", Content = "noindex" }); } Session[SessionKey.PatronMessage] = "Could not find details on that event."; Session[SessionKey.PatronMessageLevel] = PatronMessageLevels.Warning; Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign"; } }
protected void HandleExcelFile(bool doImport) { int tenantId = (int)HttpContext.Current.Session["TenantID"]; if (ExcelFileUpload.HasFile) { using (var stream = ExcelFileUpload.PostedFile.InputStream) { IExcelDataReader excelReader = null; try { if (ExcelFileUpload.FileName.EndsWith(".xlsx")) { excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); } else if (ExcelFileUpload.FileName.EndsWith(".xls")) { excelReader = ExcelReaderFactory.CreateBinaryReader(stream); } this.Log().Info("Reading uploaded Excel file of events: {0}", ExcelFileUpload.FileName); if (excelReader == null) { throw new Exception("Could not parse Excel file, not .xls or .xlsx"); } excelReader.IsFirstRowAsColumnNames = true; var branchMap = new Dictionary <string, int>(); var codeTypes = DAL.CodeType.GetAll().Tables[0]; var branchCodeTypeId = (int)codeTypes .Select("CodeTypeName = 'Branch'") .First()["CTID"]; var branches = DAL.Codes.GetAlByTypeID(branchCodeTypeId).Tables[0]; foreach (DataRow branchRow in branches.Rows) { branchMap.Add( ((string)branchRow["Code"]).ToLower(), (int)branchRow["CID"] ); } int?recordCount = null; var problems = new List <string>(); while (excelReader.Read()) { // skip column headings if (recordCount == null) { recordCount = 0; continue; } try { string name = null; DateTime?date = null; string description = null; // can't be null for business rule validation string secretCode = null; int? pointsEarned = null; string link = null; bool hiddenFromPublic = false; int? branchId = null; try { name = excelReader.GetString(0); if (string.IsNullOrWhiteSpace(name)) { throw new Exception(); } } catch (Exception) { problems.Add(string.Format("Not inserting - empty event name on row {0}", recordCount + 1)); continue; } try { date = excelReader.GetDateTime(1); } catch (Exception) { problems.Add(string.Format("Not inserting - invalid event date and time for event: {0}", name)); continue; } try { description = excelReader.GetString(2); if (string.IsNullOrWhiteSpace(description)) { throw new Exception(); } } catch (Exception) { problems.Add(string.Format("Not inserting - missing description for event: {0}", name)); continue; } if (excelReader.FieldCount >= 4) { try { secretCode = excelReader.GetString(3); var lookupEvent = DAL.Event.GetEventByEventCode(secretCode.Trim()); if (lookupEvent.Tables.Count != 0 && lookupEvent.Tables[0].Rows.Count != 0) { problems.Add(string.Format("Skipping code - secret code {0} provided for event {1} is already in use.", secretCode, name)); } } catch (Exception) { } } if (excelReader.FieldCount >= 5) { try { var pointsEarnedString = excelReader.GetString(4); if (!string.IsNullOrWhiteSpace(pointsEarnedString)) { int pointsInt; if (!int.TryParse(pointsEarnedString, out pointsInt)) { problems.Add(string.Format("Skipping points earned - couldn't convert points earned to a number for: {0}", name)); } else { pointsEarned = pointsInt; } } } catch (Exception) { } } if (excelReader.FieldCount >= 6) { try { link = excelReader.GetString(5); } catch (Exception) { } } if (excelReader.FieldCount >= 7) { try { var hiddenFromString = excelReader.GetString(6); string compareString = hiddenFromString.ToLower(); hiddenFromPublic = compareString.Contains("true") || compareString.Contains("yes") || compareString.Contains("1"); } catch (Exception) { } } if (excelReader.FieldCount >= 8) { try { var branchString = excelReader.GetString(7); if (branchString != null && branchString.Length > 0) { if (branchMap.ContainsKey(branchString.ToLower())) { branchId = branchMap[branchString.ToLower()]; } else { problems.Add(string.Format("Skipping branch - couldn't find branch {0} specified for event {1}", branchString, name)); } } } catch (Exception) { } } var newEvent = new DAL.Event { EventTitle = name, EventDate = (DateTime)date, HTML = description, SecretCode = secretCode ?? string.Empty, NumberPoints = pointsEarned ?? 0, ExternalLinkToEvent = link ?? string.Empty, HiddenFromPublic = hiddenFromPublic, BranchID = branchId ?? 0 }; if (doImport) { DAL.Event.Insert(newEvent); } else { if (!newEvent.IsValid(BusinessRulesValidationMode.INSERT)) { foreach (var errorCode in newEvent.ErrorCodes) { problems.Add(string.Format("Issue with event {0}: {1} {2}", name, errorCode.FieldName, errorCode.ErrorMessage)); } } } recordCount++; } catch (Exception ex) { // couldn't import this record string problem = string.Format("Unable to import row {0}: {1}", recordCount + 1, ex.Message); this.Log().Info(problem); problems.Add(problem); } } var result = new StringBuilder(string.Format("Read {0} records and encountered {1} errors in: {2}", recordCount, problems.Count, ExcelFileUpload.FileName)); this.Log().Info(result.ToString()); if (problems != null && problems.Count > 0) { result.Append("<p>Problems with spreadsheet:<p><ul>"); foreach (var problem in problems) { result.Append("<li>"); result.Append(problem); result.AppendLine("</li>"); } result.AppendLine("</ul>"); } PageMessage = result.ToString(); } catch (Exception ex) { string result = string.Format("Error reading Excel file for event import: {0} - {1}", ex.Message, ex.StackTrace); this.Log().Error(result); PageError = result; } finally { if (excelReader != null) { if (!excelReader.IsClosed) { excelReader.Close(); } excelReader.Dispose(); } } } } }
public void ProcessRequest(HttpContext context) { var jsonResponse = new JsonEvent(); if (context.Request.QueryString["EventId"] == null) { jsonResponse.Success = false; jsonResponse.ErrorMessage = "No event id provided."; this.Log().Error(string.Format("Event requested from {0}?{1} with no id.", context.Request.Url, context.Request.QueryString)); } else { int eventId = 0; if (!int.TryParse(context.Request["EventId"].ToString(), out eventId)) { jsonResponse.Success = false; jsonResponse.ErrorMessage = "Invalid event id provided."; this.Log().Error(string.Format("Requested event {0} from {1}?{2} - invalid id", context.Request["EventId"].ToString(), context.Request.Url, context.Request.QueryString)); } else { DAL.Event e = new DAL.Event().FetchObject(eventId); if (e == null) { jsonResponse.Success = false; jsonResponse.ErrorMessage = "Event not found."; this.Log().Error(string.Format("Requested event {0} from {1}?{2} - not found", eventId, context.Request.Url, context.Request.QueryString)); } else { var cf = CustomEventFields.FetchObject(); jsonResponse.Success = true; jsonResponse.Title = e.EventTitle; jsonResponse.ShortDescription = e.ShortDescription; jsonResponse.Description = e.HTML; jsonResponse.When = Event.DisplayEventDateTime(e); if (e.BranchID > 0) { var codeObject = DAL.Codes.FetchObject(e.BranchID); if (codeObject != null) { jsonResponse.Where = codeObject.Description; } } if (!string.IsNullOrWhiteSpace(e.Custom1) && !string.IsNullOrWhiteSpace(cf.Label1)) { jsonResponse.CustomLabel1 = cf.Label1; jsonResponse.CustomValue1 = e.Custom1; } if (!string.IsNullOrWhiteSpace(e.Custom2) && !string.IsNullOrWhiteSpace(cf.Label2)) { jsonResponse.CustomLabel2 = cf.Label2; jsonResponse.CustomValue2 = e.Custom2; } if (!string.IsNullOrWhiteSpace(e.Custom3) && !string.IsNullOrWhiteSpace(cf.Label3)) { jsonResponse.CustomLabel3 = cf.Label3; jsonResponse.CustomValue3 = e.Custom3; } } } } context.Response.ContentType = "application/json"; var settings = new JsonSerializerSettings(); settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml; context.Response.Write(JsonConvert.SerializeObject(jsonResponse, settings)); }
protected void Page_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(Request["PID"])) { Session["ProgramID"] = Request["PID"].ToString(); } if (!IsPostBack) { if (Session["ProgramID"] == null) { try { int PID = Programs.GetDefaultProgramID(); Session["ProgramID"] = PID.ToString(); } catch { Response.Redirect("~/Default.aspx"); } } } TranslateStrings(this); eventBackLink.NavigateUrl = "~/Events/"; DAL.Event evnt = null; int eventId = 0; string displayEvent = Request.QueryString["EventId"]; if (!string.IsNullOrEmpty(displayEvent) && int.TryParse(displayEvent.ToString(), out eventId)) { evnt = DAL.Event.GetEvent(eventId); if (evnt != null && evnt.HiddenFromPublic) { evnt = null; } if (evnt != null) { SchemaOrgLibrary mdLib = new SchemaOrgLibrary(); SchemaOrgEvent mvEvt = new SchemaOrgEvent { Name = evnt.EventTitle, StartDate = evnt.EventDate }; eventTitle.Text = evnt.EventTitle; this.Title = string.Format("Event Details: {0}", eventTitle.Text); eventWhen.Text = DAL.Event.DisplayEventDateTime(evnt); eventWhere.Visible = false; eventWhereLink.Visible = false; atLabel.Visible = false; if (evnt.BranchID > 0) { var codeObject = DAL.Codes.FetchObject(evnt.BranchID); if (codeObject != null) { eventWhere.Text = mdLib.Name = codeObject.Description; eventWhereLink.Text = string.Format("{0} <span class=\"glyphicon glyphicon-new-window hidden-print\"></span>", codeObject.Description); eventWhere.Visible = true; atLabel.Visible = true; eventWhereLink.Visible = false; } var crosswalk = DAL.LibraryCrosswalk.FetchObjectByLibraryID(evnt.BranchID); if (crosswalk != null) { if (!string.IsNullOrEmpty(eventWhere.Text) && !string.IsNullOrEmpty(crosswalk.BranchAddress)) { eventWhereMapLink.Visible = true; eventWhereMapLink.NavigateUrl = string.Format(WebTools.BranchMapLinkStub, crosswalk.BranchAddress); } if (!string.IsNullOrEmpty(eventWhere.Text) && !string.IsNullOrEmpty(crosswalk.BranchLink)) { eventWhereLink.NavigateUrl = crosswalk.BranchLink; eventWhere.Visible = false; eventWhereLink.Visible = true; atLabel.Visible = true; } mdLib.Address = crosswalk.BranchAddress; mdLib.Telephone = crosswalk.BranchTelephone; mdLib.Url = crosswalk.BranchLink; } } if (string.IsNullOrEmpty(mdLib.Name)) { this.MetaDescription = string.Format("Details about the event: {0} - {1}", mdLib.Name, GetResourceString("system-name")); } else { this.MetaDescription = string.Format("Details about the event: {0} at {1} - {2}", eventTitle.Text, eventWhere.Text, GetResourceString("system-name")); } if (!string.IsNullOrWhiteSpace(evnt.ExternalLinkToEvent)) { eventLinkPanel.Visible = true; ExternalLink.NavigateUrl = evnt.ExternalLinkToEvent; ExternalLink.Text = string.Format(eventTitle.Text); } else { eventLinkPanel.Visible = false; } eventDescription.Text = Server.HtmlDecode(evnt.HTML); var cf = DAL.CustomEventFields.FetchObject(); if (!string.IsNullOrWhiteSpace(evnt.Custom1) && !string.IsNullOrWhiteSpace(cf.Label1)) { eventCustom1Panel.Visible = true; eventCustomLabel1.Text = cf.Label1; eventCustomValue1.Text = evnt.Custom1; } else { eventCustom1Panel.Visible = false; } if (!string.IsNullOrWhiteSpace(evnt.Custom2) && !string.IsNullOrWhiteSpace(cf.Label2)) { eventCustom2Panel.Visible = true; eventCustomLabel2.Text = cf.Label2; eventCustomValue2.Text = evnt.Custom2; } else { eventCustom2Panel.Visible = false; } if (!string.IsNullOrWhiteSpace(evnt.Custom3) && !string.IsNullOrWhiteSpace(cf.Label3)) { eventCustom3Panel.Visible = true; eventCustomLabel3.Text = cf.Label3; eventCustomValue3.Text = evnt.Custom3; } else { eventCustom3Panel.Visible = false; } eventDetails.Visible = true; mvEvt.Location = mdLib; try { Microdata.Text = new WebTools().BuildEventJsonld(mvEvt); } catch (Exception ex) { this.Log().Error("Problem creating microdata in event detail for {0}: {1} - {2}", evnt.EID, ex.Message, ex.StackTrace); } // begin social var wt = new WebTools(); var systemName = StringResources.getStringOrNull("system-name"); var fbDescription = StringResources.getStringOrNull("facebook-description"); var hashtags = StringResources.getStringOrNull("socialmedia-hashtags"); var title = string.Format("{0} event: {1}", systemName, evnt.EventTitle); string description = string.Format("I'm thinking about attending this {0} event: {1}!", systemName, evnt.EventTitle); string twitDescrip = string.Format("Check out this {0} event: {1}!", systemName, evnt.EventTitle); if (twitDescrip.Length > 118) { // if it's longer than this it won't fit with the url, shorten it twitDescrip = string.Format("Check this out: {0}!", evnt.EventTitle); } var baseUrl = WebTools.GetBaseUrl(Request); var eventDetailsUrl = string.Format("{0}/Events/Details.aspx?EventId={1}", baseUrl, evnt.EID); string bannerPath = new GRA.Logic.Banner().FullMetadataBannerPath(baseUrl, Session, Server); wt.AddOgMetadata(Metadata, title, wt.BuildFacebookDescription(description, hashtags, fbDescription), bannerPath, eventDetailsUrl, facebookApp: GetResourceString("facebook-appid")); wt.AddTwitterMetadata(Metadata, title, description, bannerPath, twitterUsername: GetResourceString("twitter-username")); TwitterShare.NavigateUrl = wt.GetTwitterLink(twitDescrip, Server.UrlEncode(eventDetailsUrl), hashtags); TwitterShare.Visible = true; FacebookShare.NavigateUrl = wt.GetFacebookLink(Server.UrlEncode(eventDetailsUrl)); FacebookShare.Visible = true; //end social } } if (evnt == null) { eventDetails.Visible = false; var cph = Page.Master.FindControl("HeaderContent") as ContentPlaceHolder; if (cph != null) { cph.Controls.Add(new HtmlMeta { Name = "robots", Content = "noindex" }); } Session[SessionKey.PatronMessage] = "Could not find details on that event."; Session[SessionKey.PatronMessageLevel] = PatronMessageLevels.Warning; Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign"; } }
protected void HandleExcelFile(bool doImport) { int tenantId = (int)HttpContext.Current.Session["TenantID"]; if (ExcelFileUpload.HasFile) { using (var stream = ExcelFileUpload.PostedFile.InputStream) { IExcelDataReader excelReader = null; try { if (ExcelFileUpload.FileName.EndsWith(".xlsx")) { excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); } else if (ExcelFileUpload.FileName.EndsWith(".xls")) { excelReader = ExcelReaderFactory.CreateBinaryReader(stream); } this.Log().Info("Reading uploaded Excel file of events: {0}", ExcelFileUpload.FileName); if (excelReader == null) { throw new Exception("Could not parse Excel file, not .xls or .xlsx"); } excelReader.IsFirstRowAsColumnNames = true; var branchMap = new Dictionary<string, int>(); var codeTypes = DAL.CodeType.GetAll().Tables[0]; var branchCodeTypeId = (int)codeTypes .Select("CodeTypeName = 'Branch'") .First()["CTID"]; var branches = DAL.Codes.GetAlByTypeID(branchCodeTypeId).Tables[0]; foreach (DataRow branchRow in branches.Rows) { branchMap.Add( ((string)branchRow["Code"]).ToLower(), (int)branchRow["CID"] ); } int? recordCount = null; var problems = new List<string>(); while (excelReader.Read()) { // skip column headings if (recordCount == null) { recordCount = 0; continue; } try { string name = null; DateTime? date = null; string description = null; // can't be null for business rule validation string secretCode = null; int? pointsEarned = null; string link = null; bool hiddenFromPublic = false; int? branchId = null; try { name = excelReader.GetString(0); if (string.IsNullOrWhiteSpace(name)) { throw new Exception(); } } catch (Exception) { problems.Add(string.Format("Not inserting - empty event name on row {0}", recordCount + 1)); continue; } try { date = excelReader.GetDateTime(1); } catch (Exception) { problems.Add(string.Format("Not inserting - invalid event date and time for event: {0}", name)); continue; } try { description = excelReader.GetString(2); if (string.IsNullOrWhiteSpace(description)) { throw new Exception(); } } catch (Exception) { problems.Add(string.Format("Not inserting - missing description for event: {0}", name)); continue; } if (excelReader.FieldCount >= 4) { try { secretCode = excelReader.GetString(3); var lookupEvent = DAL.Event.GetEventByEventCode(secretCode.Trim()); if (lookupEvent.Tables.Count != 0 && lookupEvent.Tables[0].Rows.Count != 0) { problems.Add(string.Format("Skipping code - secret code {0} provided for event {1} is already in use.", secretCode, name)); } } catch (Exception) { } } if (excelReader.FieldCount >= 5) { try { var pointsEarnedString = excelReader.GetString(4); if (!string.IsNullOrWhiteSpace(pointsEarnedString)) { int pointsInt; if (!int.TryParse(pointsEarnedString, out pointsInt)) { problems.Add(string.Format("Skipping points earned - couldn't convert points earned to a number for: {0}", name)); } else { pointsEarned = pointsInt; } } } catch (Exception) { } } if (excelReader.FieldCount >= 6) { try { link = excelReader.GetString(5); } catch (Exception) { } } if (excelReader.FieldCount >= 7) { try { var hiddenFromString = excelReader.GetString(6); string compareString = hiddenFromString.ToLower(); hiddenFromPublic = compareString.Contains("true") || compareString.Contains("yes") || compareString.Contains("1"); } catch (Exception) { } } if (excelReader.FieldCount >= 8) { try { var branchString = excelReader.GetString(7); if (branchString != null && branchString.Length > 0) { if (branchMap.ContainsKey(branchString.ToLower())) { branchId = branchMap[branchString.ToLower()]; } else { problems.Add(string.Format("Skipping branch - couldn't find branch {0} specified for event {1}", branchString, name)); } } } catch (Exception) { } } var newEvent = new DAL.Event { EventTitle = name, EventDate = (DateTime)date, HTML = description, SecretCode = secretCode ?? string.Empty, NumberPoints = pointsEarned ?? 0, ExternalLinkToEvent = link ?? string.Empty, HiddenFromPublic = hiddenFromPublic, BranchID = branchId ?? 0 }; if (doImport) { DAL.Event.Insert(newEvent); } else { if (!newEvent.IsValid(BusinessRulesValidationMode.INSERT)) { foreach (var errorCode in newEvent.ErrorCodes) { problems.Add(string.Format("Issue with event {0}: {1} {2}", name, errorCode.FieldName, errorCode.ErrorMessage)); } } } recordCount++; } catch (Exception ex) { // couldn't import this record string problem = string.Format("Unable to import row {0}: {1}", recordCount + 1, ex.Message); this.Log().Info(problem); problems.Add(problem); } } var result = new StringBuilder(string.Format("Read {0} records and encountered {1} errors in: {2}", recordCount, problems.Count, ExcelFileUpload.FileName)); this.Log().Info(result.ToString()); if (problems != null && problems.Count > 0) { result.Append("<p>Problems with spreadsheet:<p><ul>"); foreach (var problem in problems) { result.Append("<li>"); result.Append(problem); result.AppendLine("</li>"); } result.AppendLine("</ul>"); } PageMessage = result.ToString(); } catch (Exception ex) { string result = string.Format("Error reading Excel file for event import: {0} - {1}", ex.Message, ex.StackTrace); this.Log().Error(result); PageError = result; } finally { if (excelReader != null) { if (!excelReader.IsClosed) { excelReader.Close(); } excelReader.Dispose(); } } } } }