public static IList<EmployeeDirectoryModel> All()
        {
            var result = HttpContext.Current.Session["EmployeeDirectory"] as IList<EmployeeDirectoryModel>;

            if (result == null || UpdateDatabase)
            {
                using (var db = new SampleEntities())
                {
                    result = db.EmployeeDirectory.ToList().Select(employee => new EmployeeDirectoryModel
                    {
                        EmployeeId = employee.EmployeeID,
                        ReportsTo = employee.ReportsTo,
                        FirstName = employee.FirstName,
                        LastName = employee.LastName,
                        HireDate = employee.HireDate,
                        BirthDate = employee.BirthDate,
                        Phone = employee.Phone,
                        Extension = employee.Extension,
                        Address = employee.Address,
                        City = employee.City,
                        Country = employee.Country,
                        Position = employee.Position
                    }).ToList();
                }

                HttpContext.Current.Session["EmployeeDirectory"] = result;
            }

            return result;
        }
        public static IList<GanttTaskModel> All()
        {
            var result = HttpContext.Current.Session["GanttTasks"] as IList<GanttTaskModel>;

            if (result == null || UpdateDatabase)
            {
                using (SampleEntities context = new SampleEntities())
                {
                    result = context.GanttTasks.ToList()
                        .Select(p => new GanttTaskModel
                        {
                            ID = p.ID,
                            Title = p.Title,
                            OrderID = p.OrderID,
                            ParentID = p.ParentID,
                            Start = p.Start,
                            End = p.End,
                            PercentComplete = p.PercentComplete,
                            Summary = p.Summary,
                            Expanded = p.Expanded
                        })
                        .ToList();
                }

                HttpContext.Current.Session["GanttTasks"] = result;
            }

            return result;
        }
        public static void Insert(GanttResourceAssignmentModel assignment)
        {
            if (!UpdateDatabase)
            {
                var first = All().OrderByDescending(a => a.ID).FirstOrDefault();
                var id = 0;

                if (first != null)
                {
                    id = first.ID;
                }

                assignment.ID = id + 1;

                All().Add(assignment);
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = assignment.ToEntity();

                    db.GanttResourceAssignments.AddObject(entity);

                    db.SaveChanges();
                }
            }
        }
        public static void Insert(GanttTaskModel task)
        {
            if (!UpdateDatabase)
            {
                var first = All().OrderByDescending(e => e.ID).FirstOrDefault();

                var id = 0;

                if (first != null)
                {
                    id = first.ID;
                }

                task.ID = id + 1;

                All().Insert(0, task);
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = task.ToEntity();

                    db.GanttTasks.AddObject(entity);

                    db.SaveChanges();

                    task.ID = entity.ID;
                }
            }
        }
        public static IList<MeetingViewModel> All()
        {
            var result = HttpContext.Current.Session["Meetings"] as IList<MeetingViewModel>;

            if (result == null || UpdateDatabase)
            {
                using (var db = new SampleEntities())
                {
                    result = db.Meetings.ToList().Select(meeting => new MeetingViewModel
                    {
                        MeetingID = meeting.MeetingID,
                        Title = meeting.Title,
                        Start = DateTime.SpecifyKind(meeting.Start, DateTimeKind.Utc),
                        End = DateTime.SpecifyKind(meeting.End, DateTimeKind.Utc),
                        StartTimezone = meeting.StartTimezone,
                        EndTimezone = meeting.EndTimezone,
                        Description = meeting.Description,
                        IsAllDay = meeting.IsAllDay,
                        RoomID = meeting.RoomID,
                        RecurrenceRule = meeting.RecurrenceRule,
                        RecurrenceException = meeting.RecurrenceException,
                        RecurrenceID = meeting.RecurrenceID,
                        Attendees = meeting.MeetingAttendees.Select(m => m.AttendeeID).ToArray()
                    }).ToList();
                }

                HttpContext.Current.Session["Meetings"] = result;
            }

            return result;
        }
        public static void Insert(EmployeeDirectoryModel employee)
        {
            if (!UpdateDatabase)
            {
                var first = All().OrderByDescending(e => e.EmployeeId).FirstOrDefault();

                var id = 0;

                if (first != null)
                {
                    id = first.EmployeeId;
                }

                employee.EmployeeId = id + 1;

                All().Insert(0, employee);
            }
            else
            {
                using (var db = new SampleEntities())
                {                    
                    var entity = employee.ToEntity();

                    db.EmployeeDirectory.AddObject(entity);
                    db.SaveChanges();

                    employee.EmployeeId = entity.EmployeeID;
                }
            }
        }
        public static void Insert(OrgChartShape shape)
        {
            if (!UpdateDatabase)
            {
                var first = All().OrderByDescending(e => e.Id).FirstOrDefault();

                var id = 0;

                if (first != null)
                {
                    id = first.Id;
                }

                shape.Id = id + 1;

                All().Insert(0, shape);
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    db.OrgChartShapes.AddObject(shape);
                    db.SaveChanges();
                }
            }
        }
        public static IList<TaskViewModel> All()
        {
            var result = HttpContext.Current.Session["Tasks"] as IList<TaskViewModel>;

            if (result == null || UpdateDatabase)
            {
                using (var db = new SampleEntities())
                {
                    result = db.Tasks.ToList().Select(task => new TaskViewModel
                    {
                        TaskID = task.TaskID,
                        Title = task.Title,
                        Start = DateTime.SpecifyKind(task.Start, DateTimeKind.Utc),
                        End = DateTime.SpecifyKind(task.End, DateTimeKind.Utc),
                        StartTimezone = task.StartTimezone,
                        EndTimezone = task.EndTimezone,
                        Description = task.Description,
                        IsAllDay = task.IsAllDay,
                        RecurrenceRule = task.RecurrenceRule,
                        RecurrenceException = task.RecurrenceException,
                        RecurrenceID = task.RecurrenceID,
                        OwnerID = task.OwnerID
                    }).ToList();
                }

                HttpContext.Current.Session["Tasks"] = result;
            }

            return result;
        }
        public static IList<OrgChartShape> All()
        {
            var result = HttpContext.Current.Session["OrgChartShapes"] as IList<OrgChartShape>;

            if (result == null || UpdateDatabase)
            {
                using (SampleEntities context = new SampleEntities())
                {
                    result = context.OrgChartShapes.ToList();
                }

                HttpContext.Current.Session["OrgChartShapes"] = result;
            }

            return result;
        }
        public ActionResult Index()
        {
            var dateFrom = MIN_DATE;
            var dateTo = DateTime.Now;
            var baseUnit = DEFAULT_UNIT;
            IEnumerable<StockDataPoint> result;

            using (var db = new SampleEntities())
            {
                var filter = this.DeserializeObject<DataFilter>("filter");
                if (filter != null && filter.Filters != null)
                {
                    dateFrom = DateTime.Parse(filter.Filters[0].Value.ToString());
                    dateTo = DateTime.Parse(filter.Filters[1].Value.ToString());
                    baseUnit = GetBaseUnit(dateFrom, dateTo);
                }

                var groupedData =
                    from s in db.Intraday
                    where s.Date >= dateFrom && s.Date <= dateTo
                    group s by new
                    {
                        Year = s.Date.Year,
                        Month = baseUnit >= BaseUnit.Months ? s.Date.Month : 1,
                        Day = baseUnit >= BaseUnit.Weeks ? s.Date.Day : 1,
                        Hour = baseUnit >= BaseUnit.Hours ? s.Date.Hour : 0,
                        Minute = baseUnit >= BaseUnit.Minutes ? s.Date.Minute : 0
                    } into g
                    select g;

                var points =
                    from g in groupedData.ToList()
                    select new StockDataPoint
                    {
                        Date = new DateTime(g.Key.Year, g.Key.Month, g.Key.Day, g.Key.Hour, g.Key.Minute, 0),
                        Open = g.Max(s => s.Open),
                        High = g.Max(s => s.High),
                        Low = g.Min(s => s.Low),
                        Close = g.Max(s => s.Close),
                        Volume = g.Sum(s => s.Volume)
                    };

                result = points.ToList();
            }

            return this.Jsonp(result);
        }
        public IEnumerable<MeetingSignalR> Read()
        {
            var meetings = HttpContext.Current.Cache["meetings"] as IEnumerable<MeetingSignalR>;

            if (meetings == null)
            {
                using (var context = new SampleEntities())
                {
                    var createdAt = DateTime.Now;

                    meetings = context.Meetings
                                      .ToList() // Execute the query because Linq to SQL doesn't get Guid.NewGuid()
                                      .Select(meeting => new MeetingSignalR
                                      {
                                            ID = Guid.NewGuid(),
                                            Title = meeting.Title,
                                            Start = DateTime.SpecifyKind(meeting.Start, DateTimeKind.Utc),
                                            End = DateTime.SpecifyKind(meeting.End, DateTimeKind.Utc),
                                            StartTimezone = meeting.StartTimezone,
                                            EndTimezone = meeting.EndTimezone,
                                            Description = meeting.Description,
                                            IsAllDay = meeting.IsAllDay,
                                            RoomID = meeting.RoomID,
                                            RecurrenceRule = meeting.RecurrenceRule,
                                            RecurrenceException = meeting.RecurrenceException,
                                            RecurrenceID = meeting.RecurrenceID,
                                            Attendees = meeting.MeetingAttendees.Select(m => m.AttendeeID).ToArray(),
                                            CreatedAt = createdAt = createdAt.AddMilliseconds(1)
                                      })
                                      .ToList();
                }

                HttpContext.Current.Cache.Add("meetings",
                    meetings,
                    null,
                    Cache.NoAbsoluteExpiration,
                    TimeSpan.FromMinutes(30),
                    System.Web.Caching.CacheItemPriority.Normal,
                    null
                );
            }

            return meetings;
        }
        public static IList<GanttDependencyModel> GetDependencies()
        {
            IList<GanttDependencyModel> result;

            using (SampleEntities context = new SampleEntities())
            {
                result = context.GanttDependencies.ToList()
                    .Select(p => new GanttDependencyModel
                    {
                        ID = p.ID,
                        PredecessorID = p.PredecessorID,
                        SuccessorID = p.SuccessorID,
                        Type = p.Type
                    })
                    .ToList();
            }

            return result;
        }
        public static void Insert(MeetingViewModel meeting)
        {
            if (!UpdateDatabase)
            {
                var first = All().OrderByDescending(e => e.MeetingID).FirstOrDefault();

                var id = 0;

                if (first != null)
                {
                    id = first.MeetingID;
                }                               

                meeting.MeetingID = id + 1;                

                All().Insert(0, meeting);
            } 
            else 
            {
                using (var db = new SampleEntities())
                {
                    if (meeting.Attendees == null)
                    {
                        meeting.Attendees = new int[0];
                    }                    

                    var entity = meeting.ToEntity();

                    foreach (var attendeeId in meeting.Attendees)
                    {
                        entity.MeetingAttendees.Add(new MeetingAttendee
                        {
                            AttendeeID = attendeeId
                        });
                    }

                    db.Meetings.AddObject(entity);
                    db.SaveChanges();

                    meeting.MeetingID = entity.MeetingID;
                }
            }
        }        
        public static IList<GanttResourceModel> All()
        {
            var result = HttpContext.Current.Session["GanttResources"] as IList<GanttResourceModel>;

            if (result == null)
            {
                using (SampleEntities context = new SampleEntities())
                {
                    result = context.GanttResources.ToList()
                        .Select(r => new GanttResourceModel
                        {
                            ID = r.ID   ,
                            Name = r.Name,
                            Color = r.Color
                        })
                        .ToList();
                }

                HttpContext.Current.Session["GanttResources"] = result;
            }

            return result;
        }
        public static IList<GanttResourceAssignmentModel> All()
        {
            var result = HttpContext.Current.Session["GanttAssignments"] as IList<GanttResourceAssignmentModel>;

            if (result == null || UpdateDatabase)
            {
                using (SampleEntities context = new SampleEntities())
                {
                    result = context.GanttResourceAssignments.ToList()
                        .Select(a => new GanttResourceAssignmentModel
                        {
                            ID = a.ID,
                            TaskID = a.TaskID,
                            ResourceID = a.ResourceID,
                            Units = a.Units
                        })
                        .ToList();
                }

                HttpContext.Current.Session["GanttAssignments"] = result;
            }

            return result;
        }
        public static IList<GanttDependencyModel> All()
        {
            var result = HttpContext.Current.Session["GanttDependencies"] as IList<GanttDependencyModel>;

            if (result == null || UpdateDatabase)
            {
                using (SampleEntities context = new SampleEntities())
                {
                    result = context.GanttDependencies.ToList()
                        .Select(p => new GanttDependencyModel
                        {
                            ID = p.ID,
                            PredecessorID = p.PredecessorID,
                            SuccessorID = p.SuccessorID,
                            Type = p.Type
                        })
                        .ToList();
                }

                HttpContext.Current.Session["GanttDependencies"] = result;
            }

            return result;
        }
        public static void Delete(GanttTaskModel task)
        {
            if (!UpdateDatabase)
            {
                var target = One(p => p.ID == task.ID);
                if (target != null)
                {
                    All().Remove(target);
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = task.ToEntity();
                    db.GanttTasks.Attach(entity);

                    db.GanttTasks.DeleteObject(entity);

                    db.SaveChanges();
                }
            }
        }
        public static void Update(OrgChartConnection connection)
        {
            if (!UpdateDatabase)
            {
                var target = One(e => e.Id == connection.Id);

                if (target != null)
                {
                    target.FromShapeId = connection.FromShapeId;
                    target.ToShapeId = connection.ToShapeId;
                    target.Text = connection.Text;
                    target.FromPointX = connection.FromPointX;
                    target.FromPointY = connection.FromPointY;
                    target.ToPointX = connection.ToPointX;
                    target.ToPointY = connection.ToPointY;
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    db.OrgChartConnections.Attach(connection);
                    db.ObjectStateManager.ChangeObjectState(connection, EntityState.Modified);
                    db.SaveChanges();
                }
            }
        }
        public static void Update(MeetingViewModel meeting)
        {
            if (!UpdateDatabase)
            {
                var target = One(e => e.MeetingID == meeting.MeetingID);

                if (target != null)
                {
                    target.Title = meeting.Title;
                    target.Start = meeting.Start;
                    target.End = meeting.End;
                    target.StartTimezone = meeting.StartTimezone;
                    target.EndTimezone = meeting.EndTimezone;
                    target.Description = meeting.Description;
                    target.IsAllDay = meeting.IsAllDay;
                    target.RecurrenceRule = meeting.RecurrenceRule;
                    target.RoomID = meeting.RoomID;
                    target.RecurrenceException = meeting.RecurrenceException;
                    target.RecurrenceID = meeting.RecurrenceID;
                    target.Attendees = meeting.Attendees;
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    if (meeting.Attendees == null)
                    {
                        meeting.Attendees = new int[0];
                    }
                    
                    var entity = meeting.ToEntity();

                    db.Meetings.Attach(entity);

                    var attendees = meeting.Attendees.Select(attendee => new MeetingAttendee
                    {
                        AttendeeID = attendee
                    });

                    foreach (var attendee in attendees)
                    {
                        db.MeetingAttendees.Attach(attendee);
                    }

                    entity.MeetingAttendees.Clear();

                    foreach (var attendee in attendees)
                    {
                        entity.MeetingAttendees.Add(attendee);
                    }

                    db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
                    db.SaveChanges();
                }
            }
        }
        public static void Delete(MeetingViewModel meeting)
        {
            if (!UpdateDatabase)
            {
                var target = One(p => p.MeetingID == meeting.MeetingID);
                if (target != null)
                {
                    All().Remove(target);

                    var recurrenceExceptions = All().Where(m => m.RecurrenceID == meeting.MeetingID).ToList();

                    foreach (var recurrenceException in recurrenceExceptions)
                    {
                        All().Remove(recurrenceException);
                    }
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    if (meeting.Attendees == null)
                    {
                        meeting.Attendees = new int[0];
                    }

                    var entity = meeting.ToEntity();

                    db.Meetings.Attach(entity);

                    var attendees = meeting.Attendees.Select(attendee => new MeetingAttendee
                    {
                        AttendeeID = attendee
                    });

                    foreach (var attendee in attendees)
                    {
                        db.MeetingAttendees.Attach(attendee);
                    }

                    entity.MeetingAttendees.Clear();

                    var recurrenceExceptions = db.Meetings.Where(m => m.RecurrenceID == entity.MeetingID);

                    foreach (var recurrenceException in recurrenceExceptions)
                    {
                        db.Meetings.DeleteObject(recurrenceException);
                    }

                    db.Meetings.DeleteObject(entity);
                    db.SaveChanges();
                }
            }
        }
        public static void Update(EmployeeDirectoryModel employee)
        {
            if (!UpdateDatabase)
            {
                var target = One(e => e.EmployeeId == employee.EmployeeId);

                if (target != null)
                {
                    target.FirstName = employee.FirstName;
                    target.LastName = employee.LastName;
                    target.Address = employee.Address;
                    target.City = employee.City;
                    target.Country = employee.Country;
                    target.Phone = employee.Phone;
                    target.Extension = employee.Extension;
                    target.BirthDate = employee.BirthDate;
                    target.HireDate = employee.HireDate;
                    target.Position = employee.Position;
                    target.ReportsTo = employee.ReportsTo;
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = employee.ToEntity();
                    db.EmployeeDirectory.Attach(entity);
                    db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
                    db.SaveChanges();
                }
            }
        }
        public static void Update(GanttTaskModel task)
        {
            if (!UpdateDatabase)
            {
                var target = One(e => e.ID == task.ID);

                if (target != null)
                {
                    target.Title = task.Title;
                    target.Start = task.Start;
                    target.End = task.End;
                    target.PercentComplete = task.PercentComplete;
                    target.OrderID = task.OrderID;
                    target.ParentID = task.ParentID;
                    target.Summary = task.Summary;
                    target.Expanded = task.Expanded;
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = task.ToEntity();

                    db.GanttTasks.Attach(entity);
                    db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);

                    db.SaveChanges();
                }
            }
        }
        public static void Update(GanttDependencyModel dependency)
        {
            if (!UpdateDatabase)
            {
                var target = One(e => e.ID == dependency.ID);

                if (target != null)
                {
                    target.Type = dependency.Type;
                    target.PredecessorID = dependency.PredecessorID;
                    target.SuccessorID = dependency.SuccessorID;
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = dependency.ToEntity();

                    db.GanttDependencies.Attach(entity);
                    db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);

                    db.SaveChanges();
                }
            }
        }
 public static void Delete(OrgChartShape shape)
 {
     if (!UpdateDatabase)
     {
         var target = One(p => p.Id == shape.Id);
         if (target != null)
         {
             All().Remove(target);
         }
     }
     else
     {
         using (var db = new SampleEntities())
         {
             db.OrgChartShapes.Attach(shape);
             db.OrgChartShapes.DeleteObject(shape);
             db.SaveChanges();
         }
     }
 }
        public static void Update(GanttResourceAssignmentModel assigment)
        {
            if (!UpdateDatabase)
            {
                var target = One(a => a.ID == assigment.ID);

                if (target != null)
                {
                    target.Units = assigment.Units;
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = assigment.ToEntity();

                    db.GanttResourceAssignments.Attach(entity);
                    db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);

                    db.SaveChanges();
                }
            }
        }
        public static void Delete(TaskViewModel task)
        {
            if (!UpdateDatabase)
            {
                var target = One(p => p.TaskID == task.TaskID);
                if (target != null)
                {
                    All().Remove(target);

                    var recurrenceExceptions = All().Where(m => m.RecurrenceID == task.TaskID).ToList();

                    foreach (var recurrenceException in recurrenceExceptions)
                    {
                        All().Remove(recurrenceException);
                    }
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = task.ToEntity();
                    db.Tasks.Attach(entity);

                    var recurrenceExceptions = db.Tasks.Where(t => t.RecurrenceID == task.TaskID);

                    foreach (var recurrenceException in recurrenceExceptions)
                    {
                        db.Tasks.DeleteObject(recurrenceException);
                    }

                    db.Tasks.DeleteObject(entity);
                    db.SaveChanges();
                }
            }
        }
        public static void Update(TaskViewModel task)
        {
            if (!UpdateDatabase)
            {
                var target = One(e => e.TaskID == task.TaskID);

                if (target != null)
                {
                    target.Title = task.Title;
                    target.Description = task.Description;
                    target.IsAllDay = task.IsAllDay;
                    target.RecurrenceRule = task.RecurrenceRule;
                    target.RecurrenceException = task.RecurrenceException;
                    target.RecurrenceID = task.RecurrenceID;
                    target.OwnerID = task.OwnerID;
                    target.StartTimezone = task.StartTimezone;
                    target.EndTimezone = task.EndTimezone;
                    target.Start = task.Start;
                    target.End = task.End;
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = task.ToEntity();
                    db.Tasks.Attach(entity);
                    db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
                    db.SaveChanges();
                }
            }
        }
        public static void Delete(GanttResourceAssignmentModel assigment)
        {
            if (!UpdateDatabase)
            {
                var target = One(a => a.ID == assigment.ID);
                if (target != null)
                {
                    All().Remove(target);
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = assigment.ToEntity();
                    db.GanttResourceAssignments.Attach(entity);

                    db.GanttResourceAssignments.DeleteObject(entity);

                    db.SaveChanges();
                }
            }
        }
        public static void Update(OrgChartShape shape)
        {
            if (!UpdateDatabase)
            {
                var target = One(e => e.Id == shape.Id);

                if (target != null)
                {
                    target.JobTitle = shape.JobTitle;
                    target.Color = shape.Color;
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    db.OrgChartShapes.Attach(shape);
                    db.ObjectStateManager.ChangeObjectState(shape, EntityState.Modified);
                    db.SaveChanges();
                }
            }
        }
        public static void Delete(EmployeeDirectoryModel employee)
        {
            if (!UpdateDatabase)
            {
                var target = One(p => p.EmployeeId == employee.EmployeeId);
                if (target != null)
                {
                    All().Remove(target);

                    var employees = All().Where(m => m.ReportsTo == employee.EmployeeId).ToList();

                    foreach (var subordinate in employees)
                    {
                        Delete(subordinate);
                    }
                }
            }
            else
            {
                using (var db = new SampleEntities())
                {
                    var entity = employee.ToEntity();
                    db.EmployeeDirectory.Attach(entity);

                    var employees = db.EmployeeDirectory.Where(t => t.ReportsTo == employee.EmployeeId);

                    foreach (var subordinate in employees)
                    {
                        Delete(new EmployeeDirectoryModel { EmployeeId = subordinate.EmployeeID });
                    }

                    db.EmployeeDirectory.DeleteObject(entity);
                    db.SaveChanges();
                }
            }
        }