コード例 #1
0
        public static void SendPollReminder(Guid leagueId, long pollId)
        {
            try
            {
                var memId = RDN.Library.Classes.Account.User.GetMemberId();
                var member = MemberCache.GetMemberDisplay(memId);
                var poll = GetPollV2(leagueId, pollId, memId);

                var mems = poll.Voters;

                foreach (var mem in mems)
                {
                    SendEmailAboutNewPoll(leagueId.ToString(), pollId, member.DerbyName, mem.DerbyName, mem.UserId);
                }

                List<Guid> memIds = poll.Voters.Select(x => x.MemberId).ToList();
                var fact = new MobileNotificationFactory()
                    .Initialize("New Poll Created:", poll.Title, Mobile.Enums.NotificationTypeEnum.NewPollCreated)
                    .AddId(pollId)
                    .AddMembers(memIds)
                    .SendNotifications();


            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }

        }
コード例 #2
0
        public static VotingClass AddPoll(VotingClass poll, Guid memberId)
        {
            try
            {
                var member = MemberCache.GetMemberDisplay(memberId);
                var dc = new ManagementContext();
                RDN.Library.DataModels.Controls.Voting.VotingV2 voting = new DataModels.Controls.Voting.VotingV2();
                voting.IsDeleted = false;
                voting.IsPublic = poll.IsPublic;
                voting.IsPollAnonymous = poll.IsPollAnonymous;

                voting.LeagueOwner = dc.Leagues.Where(x => x.LeagueId == member.CurrentLeagueId).FirstOrDefault();
                voting.Description = poll.Description;
                voting.Title = poll.Title;
                voting.IsOpenToLeague = poll.IsOpenToLeague;

                for (int i = 0; i < poll.Questions.Count; i++)
                {
                    VotingQuestion question = new VotingQuestion();
                    question.Question = poll.Questions[i].Question;
                    question.QuestionSortId = i;
                    question.QuestionType = (int)poll.Questions[i].QuestionType;

                    for (int j = 0; j < poll.Questions[i].Answers.Count; j++)
                    {
                        if (!String.IsNullOrEmpty(poll.Questions[i].Answers[j].Answer))
                        {
                            VotingAnswer answer = new VotingAnswer();
                            answer.Answer = poll.Questions[i].Answers[j].Answer;
                            answer.Question = question;
                            question.Answers.Add(answer);
                        }
                    }

                    voting.Questions.Add(question);
                }
                //List<Guid> listOfGuids = new List<Guid>();

                foreach (var mem in poll.Voters)
                {
                    voting.Voters.Add(new VotingVoters() { HasVoted = false, Member = dc.Members.Where(x => x.MemberId == mem.MemberId).FirstOrDefault() });
                }

                dc.VotingV2.Add(voting);

                int c = dc.SaveChanges();
                poll.VotingId = voting.VotingId;
                if (poll.BroadcastPoll)
                {
                    var mems = MemberCache.GetLeagueMembers(memberId, member.CurrentLeagueId);
                    for (int j = 0; j < poll.Voters.Count; j++)
                    {
                        if (memberId != poll.Voters[j].MemberId)
                        {
                            var m = mems.Where(x => x.MemberId == poll.Voters[j].MemberId).FirstOrDefault();
                            SendEmailAboutNewPoll(poll.LeagueId, poll.VotingId, member.DerbyName, m.DerbyName, m.UserId);
                        }
                    }
                }
                List<Guid> memIds = poll.Voters.Select(x => x.MemberId).ToList();
                var fact = new MobileNotificationFactory()
                    .Initialize("New Poll Created:", poll.Title, Mobile.Enums.NotificationTypeEnum.NewPollCreated)
                    .AddId(poll.VotingId)
                    .AddMembers(memIds)
                    .SendNotifications();

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: poll.ToMemberIds);
            }
            return poll;
        }
コード例 #3
0
        public static bool CreateNewMessageForGroup(ConversationModel con)
        {
            try
            {
                string conversationLink = ServerConfig.VIEW_MESSAGE_CONVERSATION;
                var dc = new ManagementContext();
                DataModels.Messages.Message m = new DataModels.Messages.Message();
                m.FromUser = dc.Members.Where(x => x.MemberId == con.MemberId).FirstOrDefault();
                m.MessageText = con.Message;
                dc.Message.Add(m);
                dc.SaveChanges();

                string ownerName = String.Empty;
                string messageId = String.Empty;

                if (m.FromUser != null)
                    ownerName = m.FromUser.DerbyName;

                DataModels.Messages.GroupMessage group = new DataModels.Messages.GroupMessage();
                group.Messages.Add(m);
                group.TitleOfMessage = con.Title;
                group.GroupOwnerId = con.FromId;
                group.LastModified = DateTime.UtcNow;
                var fed = dc.Federations.Where(x => x.FederationId == con.FromId).FirstOrDefault();
                if (fed != null)
                    ownerName = fed.Name;
                else
                {
                    var leag = dc.Leagues.Where(x => x.LeagueId == con.FromId).FirstOrDefault();
                    if (leag != null)
                        ownerName = leag.Name;
                }
                dc.GroupMessages.Add(group);
                dc.SaveChanges();
                messageId = group.GroupId.ToString();
                var tempGroups = MemberCache.GetLeagueGroupsOfMember(con.FromId);
                //add all members of the groups
                foreach (var g in con.GroupIds)
                {
                    var tempG = tempGroups.Where(x => x.Id == g).FirstOrDefault();
                    if (tempG != null)
                    {
                        foreach (var mTemp in tempG.GroupMembers)
                        {
                            if (con.Recipients.Where(x => x.MemberId == mTemp.MemberId).FirstOrDefault() == null)
                                con.Recipients.Add(new MemberDisplayMessage() { MemberId = mTemp.MemberId });
                        }
                    }
                }
                foreach (var mem in con.Recipients)
                {
                    try
                    {
                        DataModels.Messages.MessageInbox inbox = new DataModels.Messages.MessageInbox();
                        inbox.Message = m;
                        inbox.ToUser = dc.Members.Where(x => x.MemberId == mem.MemberId).FirstOrDefault();
                        inbox.MessageReadDateTime = DateTime.UtcNow;
                        inbox.NotifiedEmailDateTime = DateTime.UtcNow;
                        if (inbox.ToUser.MemberId == m.FromUser.MemberId)
                            inbox.IsRead = true;
                        else
                            MemberCache.AddMessageCountToCache(+1, mem.MemberId);

                        DataModels.Messages.MessageRecipient recipient = new DataModels.Messages.MessageRecipient();
                        recipient.Group = group;
                        recipient.Recipient = inbox.ToUser;
                        group.Recipients.Add(recipient);

                        if (con.SendEmailForMessage && inbox.ToUser.AspNetUserId != new Guid())
                        {

                            var emailData = new Dictionary<string, string>
                                        {
                                            { "derbyname", inbox.ToUser.DerbyName }, 
                                            { "FromUserName", ownerName }, 
                                            { "messageBody", HtmlSanitize.ReplaceCarriageReturnsWithBreaks( m.MessageText )},
                                            { "viewConversationLink", conversationLink +  messageId}
                                        };

                            var user = System.Web.Security.Membership.GetUser((object)inbox.ToUser.AspNetUserId);
                            if (user != null)
                            {
                                inbox.UserNotifiedViaEmail = true;
                                EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL_MESSAGES, ServerConfig.DEFAULT_EMAIL_FROM_NAME, user.UserName, EmailServer.EmailServer.DEFAULT_SUBJECT + " New Message From " + ownerName, emailData, EmailServer.EmailServerLayoutsEnum.SendMessageToUserFromOtherUser);
                            }

                        }
                        dc.MessageInbox.Add(inbox);
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                int c = dc.SaveChanges();

                MobileNotificationFactory fact = new MobileNotificationFactory();
                fact.Initialize("New Message", m.MessageText, Mobile.Enums.NotificationTypeEnum.Message)
                    .AddId(group.GroupId)
                    .AddMembers(con.Recipients.Select(x => x.MemberId).ToList())
                    .SendNotifications();

                return c > 0;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return false;
        }
コード例 #4
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="invoice"></param>
        /// <param name="reportInformation"></param>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public static bool HandleDuesPayments(DisplayInvoice invoice, string reportInformation, string customerId = null)
        {
            try
            {
                var duesItem = invoice.DuesItems.FirstOrDefault();
                bool success = Dues.DuesFactory.PayDuesAmount(duesItem.DuesItemId, duesItem.DuesId, (double)duesItem.BasePrice, duesItem.MemberPaidId, "Paid Via Paypal, Invoice:" + invoice.InvoiceId.ToString().Replace("-", ""));
                PaymentGateway pg = new PaymentGateway();
                pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Payment_Successful, customerId);
                if (success)
                {
                    //email people.
                    WebClient client = new WebClient();
                    WebClient client1 = new WebClient();
                    client.DownloadStringAsync(new Uri(ServerConfig.URL_TO_CLEAR_MEMBER_CACHE + duesItem.MemberPaidId));
                    client1.DownloadStringAsync(new Uri(ServerConfig.URL_TO_CLEAR_MEMBER_CACHE_API + duesItem.MemberPaidId));

                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Dues Payment Made", reportInformation);
                    var member = MemberCache.GetMemberDisplay(duesItem.MemberPaidId);
                    var league = MemberCache.GetLeagueOfMember(duesItem.MemberPaidId);
                    var settings = Dues.DuesFactory.GetDuesSettings(duesItem.DuesId);
                    if (settings != null && member != null)
                    {
                        var emailData = new Dictionary<string, string>
                                        {
                                            { "memberName",  member.DerbyName },
                                            { "leagueName", settings.LeagueOwnerName   },
                                            { "invoiceId", invoice.InvoiceId.ToString().Replace("-","")},
                                            { "amountPaid", duesItem.PriceAfterFees.ToString("N2") },
                                            { "baseAmountPaid",duesItem.BasePrice.ToString("N2")  },
                                            { "monthOfDuesPayment",duesItem.PaidForDate.ToShortDateString()},
                                            { "emailForPaypal", settings.PayPalEmailAddress},
                                            { "statusOfPayment",RDN.Portable.Util.Enums.EnumExt.ToFreindlyName( InvoiceStatus.Pending_Payment_From_Paypal)}
                                          };

                        //sends email to user for their payment.
                        if (!String.IsNullOrEmpty(member.UserName))
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, member.UserName, EmailServer.EmailServer.DEFAULT_SUBJECT + " Dues Payment Receipt", emailData, EmailServer.EmailServerLayoutsEnum.DuesPaymentMadeForUser);
                        else if (!String.IsNullOrEmpty(member.Email))
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, member.Email, EmailServer.EmailServer.DEFAULT_SUBJECT + " Dues Payment Receipt", emailData, EmailServer.EmailServerLayoutsEnum.DuesPaymentMadeForUser);

                        if (league != null && !String.IsNullOrEmpty(league.Email))
                        {
                            //sends email to league for notification of their payment.
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, league.Email, EmailServer.EmailServer.DEFAULT_SUBJECT + " Dues Payment Made", emailData, EmailServer.EmailServerLayoutsEnum.DuesPaymentMadeForLeague);
                        }

                        MobileNotificationFactory mnf = new MobileNotificationFactory();
                        mnf.Initialize("Dues Payment Made", "Receipt For Payment", NotificationTypeEnum.DuesPaymentReceipt)
                            .AddId(invoice.InvoiceId)
                            .AddMember(duesItem.MemberPaidId)
                            .SendNotifications();
                    }
                    else
                    {
                        throw new Exception("Settings or Member was null.  Can't send Receipts." + invoice.InvoiceId);
                    }
                }
                else
                {
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Dues Updates Were not successful", reportInformation);
                }
                return true;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: reportInformation);
            }
            return false;
        }
コード例 #5
0
        /// <summary>
        /// creates a new forum topic and post.
        /// </summary>
        /// <param name="forumId"></param>
        /// <param name="forumType"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public static long CreateNewForumTopicAndPost(Guid forumId, ForumOwnerTypeEnum forumType, string subject, string message, Guid memberId, long groupId, bool emailGroupAboutPost, bool pinMessage, bool lockMessage, long chosenCategory)
        {
            try
            {
                var dc = new ManagementContext();
                var forum = dc.Forums.Where(x => x.ForumId == forumId).FirstOrDefault();
                if (forum != null)
                {
                    var member = dc.Members.Where(x => x.MemberId == memberId).FirstOrDefault();
                    member.TotalForumPosts = member.TotalForumPosts + 1;
                    DataModels.Forum.ForumMessage mess = new DataModels.Forum.ForumMessage();
                    mess.Member = member;
                    if (!String.IsNullOrEmpty(message))
                    {
                        message = message.Replace(Environment.NewLine, "<br/>");
                        message = message.Replace("\r", "<br/>");
                    }
                    mess.MessageHTML = message;
                    if (!String.IsNullOrEmpty(message))
                        mess.MessagePlain = _htmlRegex.Replace(message, " ");
                    else
                        mess.MessagePlain = message;
                    mess.LastModified = DateTime.UtcNow;

                    RDN.Library.DataModels.Forum.ForumTopic topic = new DataModels.Forum.ForumTopic();
                    topic.CreatedByMember = member;
                    topic.LastPostDateTime = DateTime.UtcNow;
                    topic.LastPostByMember = member;
                    if (groupId > 0)
                        topic.GroupId = groupId;
                    topic.Forum = forum;
                    topic.Messages.Add(mess);
                    topic.TopicTitle = subject;
                    topic.LastModified = DateTime.UtcNow;
                    topic.IsSticky = pinMessage;
                    topic.IsLocked = lockMessage;
                    if (chosenCategory > 0)
                        topic.Category = forum.Categories.Where(x => x.CategoryId == chosenCategory).FirstOrDefault();

                    forum.Topics.Add(topic);
                    int c = dc.SaveChanges();
                    UpdateForumInbox(dc, topic, memberId);

                    string groupName = "Forum";
                    if (topic.Forum.LeagueOwner != null)
                        groupName = topic.Forum.LeagueOwner.Name;
                    if (topic.GroupId > 0)
                    {
                        try
                        {
                            var group = SiteCache.GetAllGroups().Where(x => x != null && x.Id == topic.GroupId).FirstOrDefault();
                            if (group != null)
                                groupName = group.GroupName;
                        }
                        catch (Exception exception)
                        {
                            ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: forumId.ToString() + ":" + forumType + ":" + subject + ":" + message + ":" + memberId.ToString() + ":" + groupId + ":" + emailGroupAboutPost + ":" + pinMessage + ":" + lockMessage + ":" + chosenCategory);
                        }
                    }
                    if (topic.Forum.LeagueOwner != null)
                    {
                        var notify = new ForumNotificationFactory(forumId, topic.Forum.LeagueOwner.LeagueId, true, emailGroupAboutPost, topic.GroupId, topic.TopicId, groupName, topic.TopicTitle, mess.MessageHTML, member.MemberId, member.DerbyName)
                        .LeagueEmailAboutForumPost()
                        .EmailMembersOnWatchList();

                        //notify.MembersSent.Add(new MemberDisplayBasic() { MemberId = member.MemberId, UserId = member.AspNetUserId });
                        var fact = new MobileNotificationFactory()
                            .Initialize("Forum Post:", topic.TopicTitle, Mobile.Enums.NotificationTypeEnum.Forum)
                            .AddId(topic.TopicId)
                            .AddMembers(notify.membersAlreadyEmailed)
                            .SendNotifications();


                    }
                    return topic.TopicId;
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: forumId.ToString() + ":" + forumType + ":" + subject + ":" + message + ":" + memberId.ToString() + ":" + groupId + ":" + emailGroupAboutPost + ":" + pinMessage + ":" + lockMessage + ":" + chosenCategory);
            }
            return 0;
        }
コード例 #6
0
        public static void ReplyToPost(Guid forumId, long topicId, string message, Guid memberId, bool emailGroupAboutPost)
        {
            try
            {

                var dc = new ManagementContext();
                var topic = dc.ForumTopics.Where(x => x.Forum.ForumId == forumId).Where(x => x.TopicId == topicId).FirstOrDefault();
                if (topic != null)
                {
                    var member = dc.Members.Where(x => x.MemberId == memberId).FirstOrDefault();
                    member.TotalForumPosts = member.TotalForumPosts + 1;
                    DataModels.Forum.ForumMessage mess = new DataModels.Forum.ForumMessage();
                    mess.Member = member;
                    if (!String.IsNullOrEmpty(message))
                    {
                        message = message.Replace(Environment.NewLine, "<br/>");
                        message = message.Replace("\r", "<br/>");
                    }
                    mess.MessageHTML = message;
                    if (!String.IsNullOrEmpty(message))
                        mess.MessagePlain = _htmlRegex.Replace(message, " ");
                    mess.Topic = topic;
                    topic.Forum = topic.Forum;
                    mess.LastModified = DateTime.UtcNow;
                    topic.LastModified = DateTime.UtcNow;
                    dc.Entry(topic).Reference(c => c.LastPostByMember).Load();
                    topic.LastPostByMember = member;
                    topic.LastPostDateTime = DateTime.UtcNow;
                    topic.CreatedByMember = topic.CreatedByMember;
                    dc.ForumMessages.Add(mess);
                    int ch = dc.SaveChanges();

                    UpdateForumInbox(dc, topic, memberId);
                    string groupName = "Forum";
                    if (topic.Forum.LeagueOwner != null)
                        groupName = topic.Forum.LeagueOwner.Name;
                    if (topic.GroupId > 0)
                    {
                        try
                        {
                            var group = SiteCache.GetAllGroups().Where(x => x != null && x.Id == topic.GroupId).FirstOrDefault();
                            if (group != null)
                                groupName = group.GroupName;
                        }
                        catch (Exception exception)
                        {
                            ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: forumId + ":" + topicId + ":" + message + ":" + memberId + ":" + emailGroupAboutPost + ":" + topic.GroupId);
                        }
                    }
                    Guid ownerId = new Guid();
                    if (topic.Forum.LeagueOwner != null)
                        ownerId = topic.Forum.LeagueOwner.LeagueId;
                    var notify = new ForumNotificationFactory(forumId, ownerId, false, emailGroupAboutPost, topic.GroupId, topic.TopicId, groupName, topic.TopicTitle, message, member.MemberId, member.DerbyName)
                    .LeagueEmailAboutForumPost()
                    .EmailMembersOnWatchList();

                    var fact = new MobileNotificationFactory()
                           .Initialize("Forum Reply:", topic.TopicTitle, Mobile.Enums.NotificationTypeEnum.Forum)
                           .AddId(topic.TopicId)
                           .AddMembers(notify.membersAlreadyEmailed)
                           .SendNotifications();
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: forumId + ":" + topicId + ":" + message + ":" + memberId + ":" + emailGroupAboutPost);
            }
        }
コード例 #7
0
        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;
        }
コード例 #8
0
        public static Guid CreateNewEvent(Guid calId, DateTime startDate, DateTime endDate, Guid locationId, string eventName, string link, string notes, bool AllowSelfCheckIn, bool isPublicEvent, bool isReocurring, Guid reocurringEventId, long selectedEventTypeId, bool broadcastEvent, string ticketUrl, string hexColor, List<long> groupIds, Guid memId)
        {
            DataModels.Calendar.CalendarEvent ev = new DataModels.Calendar.CalendarEvent();
            try
            {
                var dc = new ManagementContext();
                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;
                }
                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;
                ev.IsPublicEvent = isPublicEvent;
                ev.TicketUrl = ticketUrl;
                if (ev.EndDate < DateTime.UtcNow.AddYears(-1))
                    ev.EndDate = ev.StartDate;


                if (!String.IsNullOrEmpty(hexColor))
                {
                    Color cc = ColorTranslator.FromHtml(hexColor);
                    int arb = cc.ToArgb();
                    ev.Color = dc.Colors.Where(x => x.ColorIdCSharp == arb).FirstOrDefault();
                }
                else
                    ev.Color = null;
                ev.EventType = dc.CalendarEventTypes.Where(x => x.CalendarEventTypeId == selectedEventTypeId).FirstOrDefault();

                //we create a event.  Gotta check if its already in the db.
                //we had an instance where a league deleted an old reoccuring event
                //and they used the same name.  So we had to check if the event had the same reoccuring event
                //id.  
                DataModels.Calendar.CalendarEvent checkEventExists = null;
                if (isReocurring)
                {
                    ev.ReocurringEvent = dc.CalendarEventsReocurring.Where(x => x.CalendarItemId == reocurringEventId).FirstOrDefault();
                    //taking the groups from the reoccurence and adding them to the list of groups.
                    foreach (var g in ev.ReocurringEvent.Groups)
                        groupIds.Add(g.Group.Id);

                    checkEventExists = ev.Calendar.CalendarEvents.Where(x => x.EndDate == endDate && x.StartDate == startDate && x.Name == eventName && x.ReocurringEvent != null && x.ReocurringEvent.CalendarItemId == reocurringEventId).FirstOrDefault();
                }

                //keep under isrecocuring question.
                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.CalendarEventGroup newGroup = new RDN.Library.DataModels.Calendar.CalendarEventGroup();
                            newGroup.Group = group;
                            newGroup.Event = ev;
                            ev.Groups.Add(newGroup);
                        }
                    }
                }


                if (checkEventExists == null)
                    dc.CalendarEvents.Add(ev);
                else
                    ev.CalendarItemId = checkEventExists.CalendarItemId;
                int c = dc.SaveChanges();

                if (broadcastEvent)
                {
                    List<Guid> memIds = new List<Guid>();
                    var memberCreated = MemberCache.GetMemberDisplay(memId);
                    if (ev.Groups.Count == 0)
                    {
                        //sends broadcast to all league members
                        var members = MemberCache.GetCurrentLeagueMembers(memId);
                        foreach (var mem in members)
                        {
                            SendEmailAboutNewEvent(calId, ev, null, 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(memId);
                        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(memId);
                        foreach (var mem in memsToSend)
                        {
                            SendEmailAboutNewEvent(calId, ev, null, 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(), additionalInformation: endDate + ":" + startDate);
            }
            return ev.CalendarItemId;
        }