public static Guid UpdateEventReOcurring(Guid calId, Guid reoccurringEventId, DateTime startDate, DateTime endDate, Guid locationId, string eventName, string link, string notes, bool AllowSelfCheckIn, FrequencyTypeEnum repeatFrequencySelected, bool sunday, bool monday, bool tuesday, bool wednesday, bool thursday, bool friday, bool saturday, EndsWhenReoccuringEnum endsWhen, DateTime endsOnDateReoccuring, long selectedEventTypeId, int monthlyIntervalId, string hexColor, bool isEventPublic, List<long> groupIds, Guid memId)
        {
            bool editColorsOfAllEvents = false;
            bool editGroupsOfAllEvents = false;
            bool editAllEventDates = false;
            ManagementContext dc = new ManagementContext();
            var ev = dc.CalendarEventsReocurring.Where(x => x.CalendarItemId == reoccurringEventId && x.Calendar.CalendarId == calId).FirstOrDefault();
            if (ev != null)
            {
                ev.IsPublic = isEventPublic;
                ev.LastDateEventsWereCreated = startDate.AddDays(-1);
                try
                {
                    int daysOfWeek = 0;
                    if (sunday)
                        daysOfWeek += (int)DayOfWeekEnum.Sun;
                    if (monday)
                        daysOfWeek += (int)DayOfWeekEnum.Mon;
                    if (tuesday)
                        daysOfWeek += (int)DayOfWeekEnum.Tue;
                    if (wednesday)
                        daysOfWeek += (int)DayOfWeekEnum.Wed;
                    if (thursday)
                        daysOfWeek += (int)DayOfWeekEnum.Thu;
                    if (friday)
                        daysOfWeek += (int)DayOfWeekEnum.Fri;
                    if (saturday)
                        daysOfWeek += (int)DayOfWeekEnum.Sat;

                    ScheduleWidget.ScheduledEvents.Event aEvent = null;
                    if (repeatFrequencySelected == FrequencyTypeEnum.Monthly)
                    {
                        aEvent = new ScheduleWidget.ScheduledEvents.Event()
                        {
                            Title = eventName,
                            FrequencyTypeOptions = repeatFrequencySelected,
                            DaysOfWeek = daysOfWeek,
                            MonthlyInterval = monthlyIntervalId
                        };
                    }
                    else
                    {
                        aEvent = new ScheduleWidget.ScheduledEvents.Event()
                        {
                            Title = eventName,
                            FrequencyTypeOptions = repeatFrequencySelected,
                            DaysOfWeek = daysOfWeek
                        };
                    }


                    if (endsWhen == EndsWhenReoccuringEnum.Never)
                    {
                        ev.EndReocurring = DateTime.UtcNow.AddYears(1);
                    }
                    else if (endsWhen == EndsWhenReoccuringEnum.On)
                    {
                        if (endsOnDateReoccuring != new DateTime())
                            ev.EndReocurring = endsOnDateReoccuring;
                        else
                        {
                            //if this breaks, then the if statement above is wrong... Must change to match
                            //1/1/0001 12:00:00 AM
                            ErrorDatabaseManager.AddException(new Exception("NewDateTime" + new DateTime()), new Exception().GetType(), additionalInformation: startDate + " " + endDate + " " + endsOnDateReoccuring + " " + endsWhen.ToString());
                            ev.EndReocurring = null;
                        }
                    }
                    // we delete all the events if the reoccuring event is modified.
                    //so that we have a fresh date.
                    if (ev.DaysOfWeekReocurring != aEvent.DaysOfWeek)
                        editAllEventDates = true;
                    ev.DaysOfWeekReocurring = aEvent.DaysOfWeek;

                    if (ev.FrequencyReocurring != aEvent.Frequency)
                        editAllEventDates = true;
                    ev.FrequencyReocurring = aEvent.Frequency;

                    if (ev.MonthlyIntervalReocurring != aEvent.MonthlyInterval)
                        editAllEventDates = true;
                    ev.MonthlyIntervalReocurring = aEvent.MonthlyInterval;

                    if (ev.StartReocurring != startDate)
                        editAllEventDates = true;
                    ev.StartReocurring = startDate;
                    ev.Calendar = dc.Calendar.Where(x => x.CalendarId == calId).FirstOrDefault();

                    if (ev.EndDate != endDate)
                        editAllEventDates = true;


                    DateTimeOffset dtOffEnd = new DateTimeOffset(endDate.Ticks, new TimeSpan(ev.Calendar.TimeZone, 0, 0));
                    DateTimeOffset dtOffStart = new DateTimeOffset(startDate.Ticks, new TimeSpan(ev.Calendar.TimeZone, 0, 0));

                    ev.StartDate = dtOffStart.UtcDateTime;
                    ev.EndDate = dtOffEnd.UtcDateTime;
                    ev.IsInUTCTime = true;

                    if (!String.IsNullOrEmpty(hexColor))
                    {
                        Color cc = ColorTranslator.FromHtml(hexColor);
                        int arb = cc.ToArgb();

                        var color = dc.Colors.Where(x => x.ColorIdCSharp == arb).FirstOrDefault();
                        if (ev.Color != color)
                            editColorsOfAllEvents = true;
                        ev.Color = color;
                    }
                    else
                    {
                        if (ev.Color != null)
                            editColorsOfAllEvents = true;
                        ev.Color = null;
                    }
                    if (ev.AllowSelfCheckIn != AllowSelfCheckIn)
                        editAllEventDates = true;
                    ev.AllowSelfCheckIn = AllowSelfCheckIn;
                    ev.Location = dc.Locations.Include("Contact").Include("Contact.Addresses").Include("Contact.Communications").Where(x => x.LocationId == locationId).FirstOrDefault();
                    ev.Name = eventName;
                    ev.Notes = notes;
                    ev.Link = link;

                    //removes any groups not in list.
                    var tempGroups = ev.Groups.ToList();
                    foreach (var group in tempGroups)
                    {
                        if (!groupIds.Contains(group.Group.Id))
                        {
                            ev.Groups.Remove(group);
                            editGroupsOfAllEvents = true;
                        }
                    }

                    //adds any groups not in list.
                    foreach (var id in groupIds)
                    {
                        var group = dc.LeagueGroups.Where(x => x.Id == id).FirstOrDefault();
                        if (group != null)
                        {
                            if (ev.Groups.Where(x => x.Group.Id == id).FirstOrDefault() == null)
                            {
                                RDN.Library.DataModels.Calendar.CalendarEventReoccuringGroup newGroup = new RDN.Library.DataModels.Calendar.CalendarEventReoccuringGroup();
                                newGroup.Group = group;
                                newGroup.Event = ev;
                                ev.Groups.Add(newGroup);
                                editGroupsOfAllEvents = true;
                            }
                        }
                    }

                    ev.EventType = dc.CalendarEventTypes.Where(x => x.CalendarEventTypeId == selectedEventTypeId).FirstOrDefault();





                    if (editColorsOfAllEvents)
                    {
                        foreach (var eventReoccure in ev.ReoccuringEvents.Where(x => x.IsRemovedFromCalendar == false))
                        {
                            eventReoccure.Color = ev.Color;
                        }
                    }
                    if (editGroupsOfAllEvents)
                    {
                        foreach (var eventReoccure in ev.ReoccuringEvents.Where(x => x.IsRemovedFromCalendar == false))
                        {
                            UpdateGroupsOfEvent(groupIds, dc, eventReoccure);
                        }
                    }

                    int c = dc.SaveChanges();

                    if (editAllEventDates)
                    {
                        var eventsReoccur = ev.ReoccuringEvents.Where(x => x.Attendees.Count == 0 && x.IsRemovedFromCalendar == false).ToList();
                        foreach (var eve in eventsReoccur)
                        {
                            eve.IsRemovedFromCalendar = true;
                        }

                        var schedule = new Schedule(aEvent);
                        var range = new DateRange()
                        {
                            StartDateTime = ev.StartReocurring
                        };
                        //date is null if the event is never ending.
                        if (ev.EndReocurring.HasValue)
                            range.EndDateTime = ev.EndReocurring.Value;
                        else
                            range.EndDateTime = endDate.AddMonths(1);

                        foreach (var date in schedule.Occurrences(range))
                        {

                            DateTime endDateEv = new DateTime();
                            DateTime startDateEv = new DateTime();

                            if (!ev.IsInUTCTime)
                            {
                                startDateEv = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second);
                                endDateEv = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second);
                            }
                            else
                            {
                                //we have to create a temp dates so we can add the timezone information without going back a day
                                //if the time being used is on the border.
                                //without the tempdates 1/4/2013 7pm turned into 1/3/2013 7pm because the timezones didn't account for the 
                                //fact the dates were already in utc.
                                var startTempDate = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                                var endTempDate = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                                startDateEv = new DateTime(date.Year, date.Month, date.Day, startTempDate.Hour, startTempDate.Minute, startTempDate.Second);
                                endDateEv = new DateTime(date.Year, date.Month, date.Day, endTempDate.Hour, endTempDate.Minute, endTempDate.Second);
                            }

                            //only add more dates to dates in the future.  No need to go back in time.
                            if (startDateEv > DateTime.UtcNow)
                                CalendarEventFactory.CreateNewEvent(ev.Calendar.CalendarId, startDateEv, endDateEv, locationId, ev.Name, ev.Link, ev.Notes, ev.AllowSelfCheckIn, ev.IsPublic, true, ev.CalendarItemId, ev.EventType.CalendarEventTypeId, false, ev.TicketUrl, hexColor, new List<long>(), memId);

                        }
                    }
                    c = dc.SaveChanges();

                }
                catch (Exception exception)
                {
                    ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: startDate + " " + endDate + " " + endsOnDateReoccuring + " " + endsWhen.ToString());
                }
            }
            return reoccurringEventId;
        }
        public static Guid CreateNewEventReOcurring(Guid calId, DateTime startDate, DateTime endDate, Guid locationId, string eventName, string link, string notes, bool AllowSelfCheckIn, FrequencyTypeEnum repeatFrequencySelected, bool sunday, bool monday, bool tuesday, bool wednesday, bool thursday, bool friday, bool saturday, EndsWhenReoccuringEnum endsWhen, int endsOnOcurrences, DateTime endsOnDateReoccuring, long selectedEventTypeId, bool broadcastEvent, bool isEventPublic, int monthlyIntervalId, string ticketUrl, string hexColor, List<long> groupIds, Guid memberId)
        {
            DataModels.Calendar.CalendarEventReoccuring ev = new DataModels.Calendar.CalendarEventReoccuring();

            try
            {

                //need to know how many days so we can know when to end the reoccuring event in the calendar
                int howManyDays = 0;
                int daysOfWeek = 0;
                if (sunday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Sun;
                }
                if (monday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Mon;
                }
                if (tuesday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Tue;
                }
                if (wednesday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Wed;
                }
                if (thursday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Thu;
                }
                if (friday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Fri;
                }
                if (saturday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Sat;
                }
                ScheduleWidget.ScheduledEvents.Event aEvent = null;
                if (repeatFrequencySelected == FrequencyTypeEnum.Monthly)
                {
                    aEvent = new ScheduleWidget.ScheduledEvents.Event()
                   {
                       Title = eventName,
                       FrequencyTypeOptions = repeatFrequencySelected,
                       DaysOfWeek = daysOfWeek,
                       MonthlyInterval = monthlyIntervalId
                   };
                }
                else
                {
                    aEvent = new ScheduleWidget.ScheduledEvents.Event()
                   {
                       Title = eventName,
                       FrequencyTypeOptions = repeatFrequencySelected,
                       DaysOfWeek = daysOfWeek
                   };
                }

                var dc = new ManagementContext();
                if (endsWhen == EndsWhenReoccuringEnum.Never)
                {
                    ev.EndReocurring = DateTime.UtcNow.AddYears(2);
                }
                else if (endsWhen == EndsWhenReoccuringEnum.After)
                {
                    if (aEvent.FrequencyTypeOptions == FrequencyTypeEnum.Daily)
                        ev.EndReocurring = startDate.AddDays(endsOnOcurrences);
                    else if (aEvent.FrequencyTypeOptions == FrequencyTypeEnum.Monthly)
                        ev.EndReocurring = startDate.AddMonths(endsOnOcurrences);
                    else if (aEvent.FrequencyTypeOptions == FrequencyTypeEnum.Weekly)
                    {
                        int daysToAdd = (endsOnOcurrences / howManyDays) * 7;
                        ev.EndReocurring = startDate.AddDays(daysToAdd);
                    }
                }
                else if (endsWhen == EndsWhenReoccuringEnum.On)
                {
                    ev.EndReocurring = endsOnDateReoccuring;
                }
                if (!String.IsNullOrEmpty(hexColor))
                {
                    Color c = ColorTranslator.FromHtml(hexColor);
                    int arb = c.ToArgb();
                    ev.Color = dc.Colors.Where(x => x.ColorIdCSharp == arb).FirstOrDefault();
                }
                else
                    ev.Color = null;

                ev.DaysOfWeekReocurring = aEvent.DaysOfWeek;
                ev.FrequencyReocurring = aEvent.Frequency;
                ev.MonthlyIntervalReocurring = aEvent.MonthlyInterval;
                ev.StartReocurring = startDate;
                ev.Calendar = dc.Calendar.Where(x => x.CalendarId == calId).FirstOrDefault();
                if (ev.Calendar.IsCalendarInUTC)
                {
                    DateTimeOffset dtOffEnd = new DateTimeOffset(endDate.Ticks, new TimeSpan(ev.Calendar.TimeZone, 0, 0));
                    DateTimeOffset dtOffStart = new DateTimeOffset(startDate.Ticks, new TimeSpan(ev.Calendar.TimeZone, 0, 0));

                    ev.EndDate = dtOffEnd.UtcDateTime;
                    ev.StartDate = dtOffStart.UtcDateTime;
                    ev.IsInUTCTime = true;
                }
                else
                {
                    ev.EndDate = endDate;
                    ev.StartDate = startDate;
                }
                //keep under isrecocuring question.
                foreach (var id in groupIds)
                {
                    var group = dc.LeagueGroups.Where(x => x.Id == id).FirstOrDefault();
                    if (group != null)
                    {
                        RDN.Library.DataModels.Calendar.CalendarEventReoccuringGroup newGroup = new RDN.Library.DataModels.Calendar.CalendarEventReoccuringGroup();
                        newGroup.Group = group;
                        newGroup.Event = ev;
                        if (ev.Groups.Where(x => x.Group.Id == id).FirstOrDefault() == null)
                            ev.Groups.Add(newGroup);
                    }
                }

                ev.AllowSelfCheckIn = AllowSelfCheckIn;
                ev.Location = dc.Locations.Include("Contact").Include("Contact.Addresses").Include("Contact.Communications").Where(x => x.LocationId == locationId).FirstOrDefault();
                ev.Name = eventName;
                ev.Notes = notes;
                ev.TicketUrl = ticketUrl;
                ev.Link = link;
                ev.IsPublic = isEventPublic;
                ev.LastDateEventsWereCreated = DateTime.UtcNow.AddMonths(-3);
                ev.EventType = dc.CalendarEventTypes.Where(x => x.CalendarEventTypeId == selectedEventTypeId).FirstOrDefault();
                dc.CalendarEventsReocurring.Add(ev);
                ev.Calendar.CalendarEventsReocurring.Add(ev);
                int cc = dc.SaveChanges();

                var schedule = new Schedule(aEvent);
                var range = new DateRange()
                {
                    StartDateTime = ev.StartReocurring
                };
                //date is null if the event is never ending.
                if (ev.EndReocurring.HasValue)
                    range.EndDateTime = ev.EndReocurring.Value;
                else
                    range.EndDateTime = endDate.AddMonths(1);

                foreach (var date in schedule.Occurrences(range))
                {


                    DateTime endDateEv = new DateTime();
                    DateTime startDateEv = new DateTime();

                    if (!ev.IsInUTCTime)
                    {
                        startDateEv = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second);
                        endDateEv = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second);
                    }
                    else
                    {
                        //we have to create a temp dates so we can add the timezone information without going back a day
                        //if the time being used is on the border.
                        //without the tempdates 1/4/2013 7pm turned into 1/3/2013 7pm because the timezones didn't account for the 
                        //fact the dates were already in utc.
                        var startTempDate = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                        var endTempDate = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                        startDateEv = new DateTime(date.Year, date.Month, date.Day, startTempDate.Hour, startTempDate.Minute, startTempDate.Second);
                        endDateEv = new DateTime(date.Year, date.Month, date.Day, endTempDate.Hour, endTempDate.Minute, endTempDate.Second);
                    }


                    Guid calItemId = CalendarEventFactory.CreateNewEvent(ev.Calendar.CalendarId, startDateEv, endDateEv, locationId, ev.Name, ev.Link, ev.Notes, ev.AllowSelfCheckIn, ev.IsPublic, true, ev.CalendarItemId, ev.EventType.CalendarEventTypeId, false, ev.TicketUrl, hexColor, new List<long>(), memberId);

                }

                if (broadcastEvent)
                {
                    List<Guid> memIds = new List<Guid>();
                    var memberCreated = MemberCache.GetMemberDisplay(memberId);
                    if (ev.Groups.Count == 0)
                    {
                        //sends broadcast to all league members
                        var members = MemberCache.GetCurrentLeagueMembers(memberId);
                        foreach (var mem in members)
                        {
                            SendEmailAboutNewEvent(calId, null, ev, memberCreated.DerbyName, mem.UserId, mem.DerbyName, startDate, endDate);
                            memIds.Add(mem.MemberId);
                        }
                    }
                    else
                    {
                        //gets all the members of the groups selected and sends an email broadcast to those members.
                        List<MemberDisplay> memsToSend = new List<MemberDisplay>();
                        var groups = MemberCache.GetLeagueGroupsOfMember(memberId);
                        foreach (var group in ev.Groups)
                        {
                            var g = groups.Where(x => x.Id == group.Group.Id).FirstOrDefault();
                            if (g != null)
                            {
                                foreach (var temp in g.GroupMembers)
                                {
                                    MemberDisplay mtemp = new MemberDisplay();
                                    mtemp.DerbyName = temp.DerbyName;
                                    mtemp.UserId = temp.UserId;
                                    if (memsToSend.Where(x => x.UserId == mtemp.UserId).FirstOrDefault() == null)
                                        memsToSend.Add(mtemp);
                                }
                            }
                        }
                        var members = MemberCache.GetCurrentLeagueMembers(memberId);
                        foreach (var mem in memsToSend)
                        {
                            SendEmailAboutNewEvent(calId, null, ev, memberCreated.DerbyName, mem.UserId, mem.DerbyName, startDate, endDate);
                            memIds.Add(mem.MemberId);
                        }
                    }
                    var fact = new MobileNotificationFactory()
                       .Initialize("New Event Created:", ev.Name, Mobile.Enums.NotificationTypeEnum.NewCalendarEventBroadcast)
                       .AddCalendarEvent(ev.CalendarItemId, calId, ev.Name)
                       .AddMembers(memIds)
                       .SendNotifications();
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return ev.CalendarItemId;
        }