public ActionResult Create(Timeline timeline)
        {
            if (!Authorization.GetAccess(table, HttpContext.User.Identity.Name, write))
                return RedirectToAction("Index", "Home");

            if (!ModelState.IsValid)
            {
                populateListsWithSelection(timeline);
                return View(timeline);
            }

            Timeline parentTimeline = db.Timelines.Where(t => t.ID == timeline.ParentTimelineID).FirstOrDefault();
            TimeUnit fromTimeUnit = db.TimeUnits.Where(t => t.ID == timeline.FromTimeUnit).FirstOrDefault();
            TimeUnit toTimeUnit = db.TimeUnits.Where(t => t.ID == timeline.ToTimeUnit).FirstOrDefault();

            if (isInBounds(timeline, parentTimeline, fromTimeUnit, toTimeUnit))
            {
                timeline.ID = Guid.NewGuid();
                timeline.CreatedBy = Guid.Parse(Session["userid"].ToString());
                timeline.CreatedOn = DateTime.Now;
                db.Timelines.AddObject(timeline);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            populateListsWithSelection(timeline);
            return View(timeline);
        }
 /// <summary>
 /// Create a new Timeline object.
 /// </summary>
 /// <param name="id">Initial value of the ID property.</param>
 /// <param name="title">Initial value of the Title property.</param>
 /// <param name="thresholdID">Initial value of the ThresholdID property.</param>
 /// <param name="regimeID">Initial value of the RegimeID property.</param>
 /// <param name="fromContentYear">Initial value of the FromContentYear property.</param>
 /// <param name="toContentYear">Initial value of the ToContentYear property.</param>
 /// <param name="fromTimeUnit">Initial value of the FromTimeUnit property.</param>
 /// <param name="toTimeUnit">Initial value of the ToTimeUnit property.</param>
 /// <param name="uniqueID">Initial value of the UniqueID property.</param>
 public static Timeline CreateTimeline(global::System.Guid id, global::System.String title, global::System.Guid thresholdID, global::System.Guid regimeID, global::System.Decimal fromContentYear, global::System.Decimal toContentYear, global::System.Guid fromTimeUnit, global::System.Guid toTimeUnit, global::System.Int32 uniqueID)
 {
     Timeline timeline = new Timeline();
     timeline.ID = id;
     timeline.Title = title;
     timeline.ThresholdID = thresholdID;
     timeline.RegimeID = regimeID;
     timeline.FromContentYear = fromContentYear;
     timeline.ToContentYear = toContentYear;
     timeline.FromTimeUnit = fromTimeUnit;
     timeline.ToTimeUnit = toTimeUnit;
     timeline.UniqueID = uniqueID;
     return timeline;
 }
 /// <summary>
 /// Deprecated Method for adding a new object to the Timelines EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToTimelines(Timeline timeline)
 {
     base.AddObject("Timelines", timeline);
 }
        public ActionResult UploadTimeline(HttpPostedFileBase excelFile)
        {
            if (excelFile != null)
            {
                //Error records
                ViewBag.ExcelUploadError = string.Empty;

                //Save the uploaded file to blob.
                CheckContainer("ExcelDataContainerName");
                string uniqueBlobExcelName = string.Format(containerName + "/Timeline_{0}{1}", Guid.NewGuid().ToString(), Path.GetFileName(excelFile.FileName));
                CloudBlockBlob blob = blobStorageClient.GetBlockBlobReference(uniqueBlobExcelName);
                blob.Properties.ContentType = excelFile.ContentType;
                byte[] fileData = new byte[excelFile.ContentLength];
                excelFile.InputStream.Read(fileData, 0, excelFile.ContentLength);
                blob.UploadByteArray(fileData);

                LocalResource myConfigStorage = RoleEnvironment.GetLocalResource("ExcelStorage");
                string localFile = myConfigStorage.RootPath + Path.GetFileName(excelFile.FileName);
                blob.DownloadToFile(localFile);
                using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Open(localFile, false))
                {
                    Worksheet sheet = excelDoc.WorkbookPart.WorksheetParts.First().Worksheet;
                    SheetData wsheet = sheet.GetFirstChild<SheetData>();
                    foreach (Row row in wsheet.Elements())
                    {
                        if (row.RowIndex == 1)
                            continue; //header row
                        string tempData;
                        try
                        {
                            Timeline newTimeline = new Timeline();
                            Cell cell = GetCell(sheet, row, "A");
                            if (cell != null && cell.CellValue != null)
                            {
                                newTimeline.Title = GetSharedStringItemById(excelDoc.WorkbookPart, Convert.ToInt32(cell.CellValue.Text)).Text.Text; //Title
                            }
                            cell = GetCell(sheet, row, "B");
                            if (cell != null && cell.CellValue != null)
                            {
                                tempData = GetSharedStringItemById(excelDoc.WorkbookPart, Convert.ToInt32(cell.CellValue.Text)).Text.Text; //Threshold
                                newTimeline.ThresholdID = (from threshold in db.Thresholds
                                                           where threshold.Threshold1 == tempData
                                                           select threshold.ID).FirstOrDefault();
                            }
                            cell = GetCell(sheet, row, "C");
                            if (cell != null && cell.CellValue != null)
                            {

                                tempData = GetSharedStringItemById(excelDoc.WorkbookPart, Convert.ToInt32(cell.CellValue.Text)).Text.Text; //Regime
                                newTimeline.RegimeID = (from regime in db.Regimes
                                                        where regime.Regime1 == tempData
                                                        select regime.ID).FirstOrDefault();
                            }
                            cell = GetCell(sheet, row, "D");
                            if (cell != null && cell.CellValue != null)
                            {
                                newTimeline.FromContentYear = Convert.ToDecimal(cell.CellValue.Text); //FromContentYear
                            }
                            cell = GetCell(sheet, row, "E");
                            if (cell != null && cell.CellValue != null)
                            {
                                tempData = GetSharedStringItemById(excelDoc.WorkbookPart, Convert.ToInt32(cell.CellValue.Text)).Text.Text; //FromTimeUnit
                                newTimeline.FromTimeUnit = (from timeunit in db.TimeUnits
                                                            where timeunit.TimeUnit1 == tempData
                                                            select timeunit.ID).FirstOrDefault();
                            }
                            cell = GetCell(sheet, row, "F");
                            if (cell != null && cell.CellValue != null)
                            {

                                newTimeline.ToContentYear = Convert.ToDecimal(cell.CellValue.Text); //ToContentYear
                            }
                            cell = GetCell(sheet, row, "G");
                            if (cell != null && cell.CellValue != null)
                            {
                                tempData = GetSharedStringItemById(excelDoc.WorkbookPart, Convert.ToInt32(cell.CellValue.Text)).Text.Text; //ToTimeUnit
                                newTimeline.ToTimeUnit = (from timeunit in db.TimeUnits
                                                          where timeunit.TimeUnit1 == tempData
                                                          select timeunit.ID).FirstOrDefault();
                            }
                            cell = GetCell(sheet, row, "H");
                            if (cell != null && cell.CellValue != null)
                            {
                                tempData = GetSharedStringItemById(excelDoc.WorkbookPart, Convert.ToInt32(cell.CellValue.Text)).Text.Text; //Timeline2
                                int count = (from timeline in db.Timelines
                                             where timeline.Title == tempData
                                             select timeline.ID).Count();
                                if (count > 0)
                                {
                                    newTimeline.ParentTimelineID = (from timeline in db.Timelines
                                                                    where timeline.Title == tempData
                                                                    select timeline.ID).FirstOrDefault();
                                }
                            }
                            cell = GetCell(sheet, row, "I");
                            if (cell != null && cell.CellValue != null)
                            {
                                tempData = GetSharedStringItemById(excelDoc.WorkbookPart, Convert.ToInt32(cell.CellValue.Text)).Text.Text;
                                if (tempData != null) //IsVisible
                                {
                                    newTimeline.IsVisible = tempData.Trim().ToLower() == "true" ? true : false;
                                }
                            }
                            cell = GetCell(sheet, row, "J");
                            if (cell != null && cell.CellValue != null)
                            {
                                newTimeline.Attribution = GetSharedStringItemById(excelDoc.WorkbookPart, Convert.ToInt32(cell.CellValue.Text)).Text.Text; //Attribution
                            }
                            cell = GetCell(sheet, row, "K");
                            if (cell != null && cell.CellValue != null)
                            {
                                newTimeline.SourceURL = GetSharedStringItemById(excelDoc.WorkbookPart, Convert.ToInt32(cell.CellValue.Text)).Text.Text; //SourceUrl
                            }
                            if (ModelState.IsValid)
                            {
                                newTimeline.ID = Guid.NewGuid();
                                newTimeline.CreatedBy = Guid.Parse(Session["userid"].ToString());
                                newTimeline.CreatedOn = DateTime.Now;
                                db.Timelines.AddObject(newTimeline);
                            }
                        }
                        catch (Exception ex)
                        {
                            ViewBag.ExcelUploadError += "Row " + (row.RowIndex) + ": Error message: " + ex.Message + "\n";
                        }

                    }
                    db.SaveChanges();
                }
            }

            return RedirectToAction("Index", "Timeline");
        }
 private void populateListsWithSelection(Timeline timeline)
 {
     ViewBag.RegimeID = new SelectList(db.Regimes.Where(r => r.IsDeleted == null || r.IsDeleted == false).OrderBy(r => r.Regime1), "ID", "Regime1", timeline.RegimeID);
     ViewBag.ThresholdID = new SelectList(db.Thresholds.Where(r => r.IsDeleted == null || r.IsDeleted == false).OrderBy(t => t.Threshold1), "ID", "Threshold1", timeline.ThresholdID);
     ViewBag.FromTimeUnit = new SelectList(db.TimeUnits.Where(tu => tu.IsDeleted == null || tu.IsDeleted == false), "ID", "TimeUnit1", timeline.FromTimeUnit);
     ViewBag.ToTimeUnit = new SelectList(db.TimeUnits.Where(tu => tu.IsDeleted == null || tu.IsDeleted == false), "ID", "TimeUnit1", timeline.ToTimeUnit);
     ViewBag.ParentTimelineID = new SelectList(db.Timelines.Where(r => r.IsDeleted == null || r.IsDeleted == false).OrderBy(t => t.Title), "ID", "Title", timeline.ParentTimelineID);
     ViewBag.CreatedBy = new SelectList(db.Users, "ID", "UserName", timeline.CreatedBy);
     ViewBag.ModifiedBy = new SelectList(db.Users, "ID", "UserName", timeline.ModifiedBy);
 }
        private bool isInBoundsWithParent(Timeline timeline, Timeline parentTimeline, TimeUnit fromTimeUnit, TimeUnit toTimeUnit)
        {
            bool isYearValid = true;
            decimal parentTime = 0, childTime = 0;
            string parentFromTimeUnit = parentTimeline.TimeUnit.TimeUnit1.ToUpper();
            string childFromTimeUnit = fromTimeUnit.TimeUnit1.ToUpper();
            string parentToTimeUnit = parentTimeline.TimeUnit1.TimeUnit1.ToUpper();
            string childToTimeUnit = toTimeUnit.TimeUnit1.ToUpper();

            parentTime = parentTimeline.FromContentYear * determineFactor(parentFromTimeUnit);
            childTime = timeline.FromContentYear * determineFactor(childFromTimeUnit);

            if (childTime < parentTime)
            {
                isYearValid = false;
            }

            if (!isYearValid)
            {
                ModelState.AddModelError("FromContentYear", "Child timeline must be within the bounds of the parent timeline");
                return false;
            }

            if (!(parentTimeline.ToContentYear == 0 && (parentToTimeUnit == "GA" || parentToTimeUnit == "MA" || parentToTimeUnit == "KA"))) //if 0 then its today
            {
                parentTime = parentTimeline.ToContentYear * determineFactor(parentToTimeUnit);
                childTime = timeline.ToContentYear * determineFactor(childToTimeUnit);

                if (childTime > parentTime)
                {
                    isYearValid = false;
                }
            }

            if (!isYearValid)
            {
                ModelState.AddModelError("ToContentYear", "Child timeline must be within the bounds of the parent timeline");
                return false;
            }

            return true;
        }
        private bool isInBounds(Timeline timeline, Timeline parentTimeline, TimeUnit fromTimeUnit, TimeUnit toTimeUnit)
        {
            decimal fromTime = 0, toTime = 0;
            string toTimeUnitValue = toTimeUnit.TimeUnit1.ToUpper();
            string fromTimeUnitValue = fromTimeUnit.TimeUnit1.ToUpper();

            if (timeline.ToContentYear == 0 && (toTimeUnitValue == "GA" || toTimeUnitValue == "MA" || toTimeUnitValue == "KA"))
                return true;

            if (timeline.FromContentYear == 0)
            {
                ModelState.AddModelError("FromContentYear", "From content year cannot be 0.");
                return false;
            }

            //Validate Toyear and timeunit
            if (timeline.ToContentYear == 0 && (toTimeUnitValue == "CE" || toTimeUnitValue == "BCE"))
            {
                ModelState.AddModelError("ToContentYear", "To content year cannot be 0 for timeunits CE and BCE.");
                return false;
            }

            if (!checkLimits(timeline.FromContentYear, fromTimeUnitValue))
            {
                ModelState.AddModelError("FromContentYear", "From content year must be within the range of the selected timeunit.");
                return false;
            }
            if (!checkLimits(timeline.ToContentYear, toTimeUnitValue))
            {
                ModelState.AddModelError("ToContentYear", "To content year must be within the range of the selected timeunit.");
                return false;
            }

            if (!checkTimeunits(fromTimeUnitValue, toTimeUnitValue))
            {
                ModelState.AddModelError("ToTimeUnit", "ToTimeUnit must be within the bounds of the FromTimeUnit.");
                return false;
            }

            fromTime = timeline.FromContentYear * determineFactor(fromTimeUnitValue);
            toTime = timeline.ToContentYear * determineFactor(toTimeUnitValue);

            if (toTime < fromTime)
            {
                ModelState.AddModelError("ToContentYear", "ToContent year must be greater than the fromContent year.");
                return false;
            }

            if (parentTimeline != null)
            {
                return isInBoundsWithParent(timeline, parentTimeline, fromTimeUnit, toTimeUnit);
            }

            return true;
        }
        private bool isValid(Timeline timeline, Exhibit exhibit)
        {
            if (timeline == null)
            {
                ModelState.AddModelError("TimelineID", "Timeline is required.");
                return false;
            }

            if (exhibit == null)
            {
                ModelState.AddModelError("ExhibitID", "Exhibit is required.");
                return false;
            }

            return isInBoundsWithParent(exhibit, timeline);
        }
        private bool isInBoundsWithParent(Exhibit exhibit, Timeline timeline)
        {
            bool isYearValid = true;
            string childTimeUnit = exhibit.TimeUnit.TimeUnit1.ToUpper();
            string parentFromTimeUnit = timeline.TimeUnit.TimeUnit1.ToUpper();
            string parentToTimeUnit = timeline.TimeUnit1.TimeUnit1.ToUpper();

            decimal parentTime = timeline.FromContentYear * determineFactor(parentFromTimeUnit);
            decimal childTime = exhibit.ContentYear.Value * determineFactor(childTimeUnit);

            //if both the timeunits are CE then the totime must be greater than the from time. Otherwise its vice versa
            if (parentFromTimeUnit == "CE" && childTimeUnit == "CE")
            {
                if (childTime < parentTime)
                    isYearValid = false;
            }
            else
            {
                if (childTime > parentTime)
                    isYearValid = false;
            }

            if (!isYearValid)
            {
                ModelState.AddModelError("ExhibitID", "Exhibit ContentYear and Timeunit must be within the bounds of the timeline");
                return false;
            }

            if (!(timeline.ToContentYear == 0 && (parentToTimeUnit == "GA" || parentToTimeUnit == "MA" || parentToTimeUnit  == "KA"))) //if 0 then its today
            {
                parentTime = timeline.ToContentYear * determineFactor(parentToTimeUnit);
                if (parentToTimeUnit == "CE" && parentToTimeUnit == "CE")
                {
                    if (childTime > parentTime)
                        isYearValid = false;
                }
                else
                {
                    if (childTime < parentTime)
                        isYearValid = false;
                }
            }

            if (!isYearValid)
            {
                ModelState.AddModelError("ExhibitID", "Exhibit ContentYear and Timeunit must be within the bounds of the timeline");
                return false;
            }

            return true;
        }