protected void btn_Upload_Click(object sender, EventArgs e) { try { BCCityAdmin cityContent = new BCCityAdmin(); DateTime cityStartDate = new DateTime(); DataTable _dtTrkpts = new DataTable(); string FileName = fu_UploadGpx.PostedFile.FileName; string NewFile = ""; string NewFileName = ""; DataTable studInfo = objStudent.GetMyProfileInfo(Convert.ToInt32(Session["UserId"])); string FilePath = Server.MapPath("../GPXFiles/" + studInfo.Rows[0]["SchoolId"].ToString() + "/" + studInfo.Rows[0]["ClassId"].ToString() + "/" + Session["UserId"].ToString() + "/").ToString(); string extension = System.IO.Path.GetExtension(FileName).ToLower(); if ((extension == ".gpx") | (extension == ".GPX")) { if (IsFileUploaded(FilePath + FileName)) { string popupScript = "alert('" + (string)GetLocalResourceObject("MsgFileAlredyUploaded") + "');";//File already uploaded! ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); } else { #region Save file on server for evaluation System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(FilePath); if (!(dir.Exists)) { System.IO.Directory.CreateDirectory(FilePath); } fu_UploadGpx.SaveAs(FilePath + FileName.Replace(".gpx", ".xml")); DataTable dt = cityContent.GetCityContent(Convert.ToInt32(studInfo.Rows[0]["CityId"]), 0); try { string TimeStamp = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ""; NewFileName = Session["UserRoleId"].ToString() + "_" + Session["UserId"].ToString() + "_" + TimeStamp + ".xml"; File.Move(FilePath + FileName.Replace(".gpx", ".xml"), FilePath + NewFileName); // Try to move NewFile = FilePath + NewFileName; } catch (IOException ex) { NewFile = FilePath + FileName; NewFileName = FileName; } #endregion DataTable dtNew = new DataTable(); dtNew = LoadGPXWaypoints(NewFile); DateTime DateOfFile = DateTime.MinValue; try { if (dt != null && dt.Rows.Count > 0 && dtNew != null && dtNew.Rows.Count > 0) { cityStartDate = Convert.ToDateTime(dt.Rows[0]["CityStartDate"]); DateOfFile = Convert.ToDateTime(dtNew.Rows[0]["time"]); } if (cityStartDate != new DateTime() && DateOfFile <= cityStartDate) { File.Delete(NewFile); string popupScript = "alert('" + (string)GetLocalResourceObject("MsgFileNotForPriorDate") + "');"; ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); return; } if (DateOfFile < DateTime.Parse(ConfigurationManager.AppSettings["BatchStartDate"])) { File.Delete(NewFile); string popupScript = "alert('" + (string)GetLocalResourceObject("MsgFileNotForCurrentBatch") + "');"; ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); return; } } catch (Exception ex) { string popupScript = "alert('" + (string)GetLocalResourceObject("MsgFileNoHaveTimeStamp") + "');"; ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); return; } _dtTrkpts = dtNew; int trackCount = (dtNew.Rows.Count / 5) + 1; double highestSpeed = 0; DataTable dtNewRows = CheckPreviousGPXTrackPointsNew (Convert.ToInt32(Session["UserId"]), Convert.ToInt32(studInfo.Rows[0]["SchoolId"].ToString()), Convert.ToInt32(studInfo.Rows[0]["ClassId"].ToString()), dtNew); if (dtNewRows != null && dtNewRows.Rows.Count > 0) { double distance = CalculateTotalDistance(dtNewRows); double time = CalculateTotalTime(dtNewRows); double timeAvg = CalculateAvgTime(dtNewRows); #region Calculate Average Speed if (timeAvg > 0) { time = timeAvg; } double avgSpeed = 0.0; if (time > 0) { avgSpeed = distance / time; } #endregion int speedLimit = 15; if (ConfigurationManager.AppSettings["SpeedLimit"].ToString() != "") { speedLimit = Convert.ToInt32(ConfigurationManager.AppSettings["SpeedLimit"]); } // bool IsFileCopied = checkGPXWayPoints(dtNew); if (avgSpeed == 0) { string popupScript = "alert('" + (string)GetLocalResourceObject("MsgAvgSpeedIsLow") + "');"; ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); File.Delete(NewFile); } else { highestSpeed = GetHighestSpeedInGPX(dtNewRows); string avgMsg = IsAvgSpeedExceed(avgSpeed, out avgSpeedLimit); //if (!string.IsNullOrEmpty(avgMsg)) //{ // ClientScript.RegisterStartupScript(Page.GetType(), "script", avgMsg, true); // return; //} string highMsg = IsHighSpeedExceed(highestSpeed, out highSpeedLimit); //if (!string.IsNullOrEmpty(highMsg)) //{ // ClientScript.RegisterStartupScript(Page.GetType(), "script", highMsg, true); // return; //} #region Check ongoing stage information int stagePlanId = 0; double stageDistance = 0; double distCovered = 0; DataSet _dtStage = objStudent.GetCurrentStageInfo(Convert.ToInt32(Session["UserId"]), Convert.ToInt32(Session["UserRoleId"]), Convert.ToInt32(studInfo.Rows[0]["ClassId"])); if (_dtStage.Tables[0].Rows.Count > 0) { stagePlanId = Convert.ToInt32(_dtStage.Tables[0].Rows[0]["StagePlanId"]); stageDistance = Convert.ToDouble(_dtStage.Tables[0].Rows[0]["Distance"]); distCovered = double.Parse(_dtStage.Tables[0].Rows[0]["Distance_Covered"].ToString(), System.Globalization.CultureInfo.InvariantCulture); //Convert.ToDouble(_dtStage.Tables[0].Rows[0]["Distance_Covered"]); } else { string popupScript = "alert('No active stage plan!');"; ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); } #endregion bool isApproved = true; if (avgSpeed <= avgSpeedLimit && highestSpeed <= highSpeedLimit) { isApproved = true; } if (highestSpeed >= 40 && highestSpeed <= highSpeedLimit) { isApproved = false; } if (isApproved) { //Save data in Student Uploads #region Save data in Student Uploads // Check for similar track points int res = objStudent.StudentsUpload(0, Convert.ToInt32(Session["UserId"]), stagePlanId, stageDistance, distCovered, (NewFile), NewFileName, DateTime.Now, distance, time, Convert.ToInt32(studInfo.Rows[0]["ClassId"]), 1, trackCount); if (res > 0) { _SaveTrackPoints(_dtTrkpts, res); string popupScript = "alert('" + (string)GetLocalResourceObject("MsgFileUploaded") + "');";//File uploaded successfully! ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); } else { string popupScript = "alert('" + (string)GetLocalResourceObject("MsgUploadException") + "');";//File already uploaded! ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); File.Delete(NewFile); } grd_Uploads.DataBind(); #endregion } else // Upload file out of speed limit. No change in stage distance. { #region Save data in Student Uploads int res = objStudent.StudentsUploadExtraSpeed(0, Convert.ToInt32(Session["UserId"]), stagePlanId, stageDistance, distCovered, (NewFile), NewFileName, DateTime.Now, distance, time, Convert.ToInt32(studInfo.Rows[0]["ClassId"]), 0, trackCount); if (res > 0) { _SaveTrackPoints(_dtTrkpts, res); #region Send email to Class Admin & City Admin for speed limit if (avgSpeed > avgSpeedLimit || highestSpeed > highSpeedLimit) { try { string ClassAdminEmail = studInfo.Rows[0]["ClassAdminEmail"].ToString(); string CityAdminEmail = studInfo.Rows[0]["CityAdminEmail"].ToString(); StringBuilder sb = new StringBuilder(); sb.Append("<p>Dear " + studInfo.Rows[0]["ClassAdminName"].ToString() + ",</p>"); sb.Append("<p><b>" + Session["UserName"].ToString() + " (Student in " + studInfo.Rows[0]["School"].ToString() + ", " + studInfo.Rows[0]["Class"].ToString() + ")</b> have uploaded a GPX file (" + NewFileName + ") with speed <b>" + avgSpeed.ToString() + " Kmph and heighest speed being " + highestSpeed + "</b>.</p>"); sb.Append("<p>Kindly approve or reject file manually.</p>"); Helper.sendMailMoreThanAvgSpeed("BikeTour - Speed Limit Crossed!", ClassAdminEmail, sb.ToString()); StringBuilder sb2 = new StringBuilder(); sb2.Append("<p>Dear " + studInfo.Rows[0]["CityAdminName"].ToString() + ",</p>"); sb.Append("<p><b>" + Session["UserName"].ToString() + " (Student in " + studInfo.Rows[0]["School"].ToString() + ", " + studInfo.Rows[0]["Class"].ToString() + ")</b> have uploaded a GPX file (" + NewFileName + ") with speed <b>" + avgSpeed.ToString() + "Kmph and heighest speed being " + highestSpeed + "</b>.</p>"); sb.Append("<p>Kindly approve or reject file manually.</p>"); Helper.sendMailMoreThanAvgSpeed("BikeTour - Speed Limit Crossed!", ClassAdminEmail, sb2.ToString()); } catch (Exception ex) { string popupScript = "alert('" + (string)GetLocalResourceObject("MsgUploadException") + "');";//File already uploaded! ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); } } #endregion string popupScripts = "alert('" + (string)GetLocalResourceObject("MsgFileUploaded") + "');";//File uploaded successfully! ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScripts, true); } else { string popupScript = "alert('" + (string)GetLocalResourceObject("MsgUploadException") + "');";//File already uploaded! ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); File.Delete(NewFile); } grd_Uploads.DataBind(); #endregion } } } else { string popupScript = "alert('" + (string)GetLocalResourceObject("MsgFileAlredyUploaded") + "');";//File already uploaded! ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); } } } else { string popupScript = "alert('" + (string)GetLocalResourceObject("MsgSelectGPX") + "');";//Select GPX file! ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); } } catch (Exception) { string popupScript = "alert('" + (string)GetLocalResourceObject("MsgUploadException") + "');";//Select GPX file! ClientScript.RegisterStartupScript(Page.GetType(), "script", popupScript, true); } }
protected void Upload(UploadFile PostedFile, UploadResponseMessage response, string filePath) { string FileName = string.Empty; try { BCCityAdmin cityContent = new BCCityAdmin(); DateTime cityStartDate = new DateTime(); DataTable _dtTrkpts = new DataTable(); DataTable studInfo = null; FileName = PostedFile.FileName; string NewFile = ""; string NewFileName = ""; string FilePath = string.Empty; studInfo = objStudent.GetMyProfileInfo(studentId); schoolId = Convert.ToInt32(studInfo.Rows[0]["SchoolId"]); classId = Convert.ToInt32(studInfo.Rows[0]["ClassId"]); FilePath = filePath + schoolId + @"\" + classId + @"\" + studentId.ToString() + @"\".ToString(); System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(FilePath); if (!(dir.Exists)) { System.IO.Directory.CreateDirectory(FilePath); } //string extension = System.IO.Path.GetExtension(FileName).ToLower(); string[] extention = FileName.Split('.'); if (extention != null && extention.Count() > 0) { FileName = extention[0]; } //if ((extension == ".gpx") | (extension == ".GPX")) //{ if (IsFileUploaded(FilePath + FileName + ".xml")) { ErrorLogManager.WriteLog(response, FileName, "008", "File already uploaded!"); } else { #region Save file on server for evaluation File.WriteAllBytes(FilePath + FileName + ".xml", PostedFile.FileData); DataTable dt = cityContent.GetCityContent(Convert.ToInt32(studInfo.Rows[0]["CityId"]), 0); try { string TimeStamp = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ""; NewFileName = UserRoleId.ToString() + "_" + UserId.ToString() + "_" + TimeStamp + ".xml"; File.Move(FilePath + FileName + ".xml", FilePath + NewFileName); // Try to move NewFile = FilePath + NewFileName; } catch (IOException ex) { NewFile = FilePath + FileName; NewFileName = FileName; } //File.WriteAllBytes(FilePath + FileName + ".xml", PostedFile.FileData); ////fu_UploadGpx.SaveAs(FilePath + FileName.Replace(".gpx", ".xml")); //DataTable dt = cityContent.GetCityContent(cityId, 0); //XElement root = null; //DateTime DateOfFile = new DateTime(); //try //{ // root = XElement.Load(FilePath + FileName + ".xml"); // DateOfFile = DateTime.Parse(root.Elements().Skip(1).Take(1).Elements().Take(1).ToList()[0].Value); //} //catch (Exception ex) //{ // ErrorLogManager.WriteLog(response,FileName, "009", "Uploaded File does not have Time Information, Please check the file and re-upload"); // return; //} //if (dt != null && dt.Rows.Count > 0) //{ // cityStartDate = (dt.Rows[0]["CityStartDate"] != DBNull.Value ? Convert.ToDateTime(dt.Rows[0]["CityStartDate"]) : new DateTime()); // if (cityStartDate != new DateTime() && // DateOfFile != new DateTime() && // DateOfFile.Date <= cityStartDate.Date) // { // ErrorLogManager.WriteLog(response,FileName, "010", "File can not be uploaded prior to Batch Start Date."); // return; // } //} //try //{ // string TimeStamp = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + // DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ""; // NewFileName = UserRoleId.ToString() + "_" + UserId.ToString() + "_" + TimeStamp + ".xml"; // File.Move(FilePath + FileName + ".xml", FilePath + NewFileName); // Try to move // NewFile = FilePath + NewFileName; //} //catch (IOException ex) //{ // NewFile = FilePath + FileName + ".xml"; // NewFileName = FileName; //} #endregion DataTable dtNew = new DataTable(); dtNew = LoadGPXWaypoints(NewFile); DateTime DateOfFile = DateTime.MinValue;; if (dt != null && dt.Rows.Count > 0 && dtNew != null && dtNew.Rows.Count > 0) { cityStartDate = Convert.ToDateTime(dt.Rows[0]["CityStartDate"]); DateOfFile = Convert.ToDateTime(dtNew.Rows[0]["time"]); } if ((cityStartDate != new DateTime() && DateOfFile <= cityStartDate) || (DateOfFile < DateTime.Parse(ConfigurationManager.AppSettings["BatchStartDate"]))) { ErrorLogManager.WriteLog(response, FileName, "010", "File can not be uploaded prior to Batch Start Date."); return; } _dtTrkpts = dtNew; int trackCount = dtNew.Rows.Count; //(dtNew.Rows.Count / 5) + 1; double highestSpeed = 0; DataTable dtNewRows = CheckPreviousGPXTrackPointsNew(UserId, schoolId, classId, dtNew); if (dtNewRows != null && dtNewRows.Rows.Count > 0) { double distance = CalculateTotalDistance(dtNewRows); double time = CalculateTotalTime(dtNewRows); double timeAvg = CalculateAvgTime(dtNewRows); #region Calculate Average Speed if (timeAvg > 0) { time = timeAvg; } double avgSpeed = 0.0; if (time > 0) { avgSpeed = distance / time; } #endregion int speedLimit = 15; if (ConfigurationManager.AppSettings["SpeedLimit"].ToString() != "") { speedLimit = Convert.ToInt32(ConfigurationManager.AppSettings["SpeedLimit"]); } if (avgSpeed == 0) { ErrorLogManager.WriteLog(response, FileName, "011", "Invalid file!"); File.Delete(NewFile); } else { highestSpeed = GetHighestSpeedInGPX(dtNewRows); #region Check ongoing stage information int stagePlanId = 0; double stageDistance = 0; double distCovered = 0; DataSet _dtStage = objStudent.GetCurrentStageInfo((studentId > 0 ? studentId : UserId), UserRoleId, classId); if (_dtStage.Tables[0].Rows.Count > 0) { stagePlanId = Convert.ToInt32(_dtStage.Tables[0].Rows[0]["StagePlanId"]); stageDistance = Convert.ToDouble(_dtStage.Tables[0].Rows[0]["Distance"]); distCovered = double.Parse(_dtStage.Tables[0].Rows[0]["Distance_Covered"].ToString(), System.Globalization.CultureInfo.InvariantCulture); //Convert.ToDouble(_dtStage.Tables[0].Rows[0]["Distance_Covered"]); } #endregion //if (avgSpeed > speedLimit) //{ // ErrorLogManager.WriteLog(response, FileName, "016", "Speed Limit Crossed!"); //} //else if (avgSpeed <= speedLimit && highestSpeed <= speedLimit) { //Save data in Student Uploads #region Save data in Student Uploads // Check for similar track points int res = objStudent.StudentsUpload( UserRoleId, UserId, 0, studentId, stagePlanId, stageDistance, distCovered, (NewFile), NewFileName, DateTime.Now, distance, time, classId, 1, trackCount); if (res > 0) { _SaveTrackPoints(_dtTrkpts, res); ErrorLogManager.WriteLog(response, FileName, "012", "File uploaded successfully!", false); } else { ErrorLogManager.WriteLog(response, FileName, "008", "File already uploaded!"); File.Delete(NewFile); } #endregion } else // Upload file out of speed limit. No change in stage distance. { #region Save data in Student Uploads int res = objStudent.StudentsUploadExtraSpeed( UserRoleId, UserId, 0, studentId, stagePlanId, stageDistance, distCovered, (NewFile), NewFileName, DateTime.Now, distance, time, classId, 0, trackCount); if (res > 0) { _SaveTrackPoints(_dtTrkpts, res); #region Send email to Class Admin & City Admin for speed limit if (avgSpeed > speedLimit || highestSpeed > speedLimit) { try { string ClassAdminEmail = studInfo.Rows[0]["ClassAdminEmail"].ToString(); string CityAdminEmail = studInfo.Rows[0]["CityAdminEmail"].ToString(); StringBuilder sb = new StringBuilder(); sb.Append("<p>Dear " + studInfo.Rows[0]["ClassAdminName"].ToString() + ",</p>"); sb.Append("<p><b>" + UserName + " (Student in " + studInfo.Rows[0]["School"].ToString() + ", " + studInfo.Rows[0]["Class"].ToString() + ")</b> have uploaded a GPX file (" + NewFileName + ") with speed <b>" + avgSpeed.ToString() + " Kmph and heighest speed being " + highestSpeed + "</b>.</p>"); sb.Append("<p>Kindly approve or reject file manually.</p>"); Helper.sendMailMoreThanAvgSpeed("BikeTour - Speed Limit Crossed!", ClassAdminEmail, sb.ToString()); StringBuilder sb2 = new StringBuilder(); sb2.Append("<p>Dear " + studInfo.Rows[0]["CityAdminName"].ToString() + ",</p>"); sb.Append("<p><b>" + UserName + " (Student in " + studInfo.Rows[0]["School"].ToString() + ", " + studInfo.Rows[0]["Class"].ToString() + ")</b> have uploaded a GPX file (" + NewFileName + ") with speed <b>" + avgSpeed.ToString() + "Kmph and heighest speed being " + highestSpeed + "</b>.</p>"); sb.Append("<p>Kindly approve or reject file manually.</p>"); Helper.sendMailMoreThanAvgSpeed("BikeTour - Speed Limit Crossed!", ClassAdminEmail, sb2.ToString()); } catch (Exception ex) { } } #endregion ErrorLogManager.WriteLog(response, FileName, "012", "File uploaded successfully!", false); } else { ErrorLogManager.WriteLog(response, FileName, "008", "File already uploaded!"); File.Delete(NewFile); } #endregion } } } else { ErrorLogManager.WriteLog(response, FileName, "008", "File already uploaded!"); } } } catch (Exception ex) { ErrorLogManager.WriteLog(response, FileName, "013", "Select GPX file!" + ex.Message); } }