示例#1
0
        /// <summary>
        /// Notifies about expiring payments.
        /// </summary>
        public static void NotifyAboutExpiringPayments()
        {
            DateTime dtCheck = DateTime.UtcNow.AddMonths(-1).AddDays(2), prevDay = dtCheck.AddDays(-1),
                     dtCheckYear = DateTime.UtcNow.AddYears(-1).AddDays(14), prevDayYear = dtCheckYear.AddDays(-1),
                     dtStart     = new DateTime(prevDay.Year, prevDay.Month, prevDay.Day, 23, 59, 59, DateTimeKind.Utc),
                     dtEnd       = new DateTime(dtCheck.Year, dtCheck.Month, dtCheck.Day, 23, 59, 59, DateTimeKind.Utc),
                     dtStartYear = new DateTime(prevDayYear.Year, prevDayYear.Month, prevDayYear.Day, 23, 59, 59, DateTimeKind.Utc),
                     dtEndYear   = new DateTime(dtCheckYear.Year, dtCheckYear.Month, dtCheckYear.Day, 23, 59, 59, DateTimeKind.Utc);

            Func <string, string> valueOrDefault = v => !string.IsNullOrWhiteSpace(v) ? v : "-";

            if (!_isNotifying)
            {
                _isNotifying = true;

                try
                {
                    using (var repository = new Storage.Repositories.RavenRepository <User>())
                    {
                        foreach (var u in repository.Query().Where(u => u.Email != null &&
                                                                   u.Subscription != null &&
                                                                   u.Subscription.RenewedToDuration == SubscriptionDuration.OneMonth &&
                                                                   (
                                                                       u.Subscription.RenewedTo != SubscriptionType.Basic &&
                                                                       u.Subscription.Renewed >= dtStart &&
                                                                       u.Subscription.Renewed <= dtEnd
                                                                   ) ||
                                                                   u.Subscription.RenewedToDuration == SubscriptionDuration.OneYear &&
                                                                   (
                                                                       u.Subscription.RenewedTo != SubscriptionType.Basic &&
                                                                       u.Subscription.Renewed >= dtStartYear &&
                                                                       u.Subscription.Renewed <= dtEndYear
                                                                   )
                                                                   ))
                        {
                            if (!string.IsNullOrEmpty(u.Email) && u.Email.IndexOf('@') > 0)
                            {
                                MessageQueueManager.Current.GetQueue(MessageQueueType.Email).AddMessages(new Message[] { new Message()
                                                                                                                         {
                                                                                                                             Id      = Guid.NewGuid().ToString(),
                                                                                                                             Subject = Ifly.Resources.Frontpage.Email_SubscriptionExpiring_Subject,
                                                                                                                             Body    = new GenericMessageBody
                                                                                                                                       (
                                                                                                                                 new Tuple <string, string>("Recipient", u.Email),
                                                                                                                                 new Tuple <string, string>("Body", string.Format(Ifly.Resources.Frontpage.Email_SubscriptionExpiring_Body,
                                                                                                                                                                                  string.Format("{0} ({1})", valueOrDefault(u.Name), valueOrDefault(u.Email))))
                                                                                                                                       ).ToString()
                                                                                                                         } });
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.Error("Failed to notify about expiring subscriptions.", ex);
                }

                _isNotifying = false;
            }
        }
示例#2
0
        /// <summary>
        /// Populates help topics.
        /// </summary>
        public static void PopulateHelpTopics()
        {
            HelpTopic        topic                     = null;
            int              totalAddedTopics          = 0;
            string           topicMarkdown             = null;
            List <HelpTopic> topics                    = null;
            int              mediaItemsMarkerIndex     = -1;
            ResourceSet      allResourceItems          = null;
            string           titlePattern              = @"^#\s+([^\n]+)$";
            string           mediaItemsMarkdown        = string.Empty;
            string           mediaItemsMarker          = "Related images and videos:";
            Dictionary <string, HelpTopicScore> scores = new Dictionary <string, HelpTopicScore>();

            if (!_isPopulating)
            {
                _isPopulating = true;

                try
                {
                    using (var repository = new Storage.Repositories.RavenRepository <HelpTopic>())
                    {
                        // Deleting all topics.
                        while ((topics = repository.Query().Take(10).ToList()).Count > 0)
                        {
                            try
                            {
                                _log.Info(string.Format("Deleting next {0} topics...", topics.Count));

                                topics.ForEach(t =>
                                {
                                    // Remembering the score.
                                    if (!scores.ContainsKey(t.ReferenceKey))
                                    {
                                        scores.Add(t.ReferenceKey, t.Score);
                                    }

                                    repository.Delete(t);
                                });

                                System.Threading.Thread.Sleep(50);
                            }
                            catch { }
                        }

                        // Reading all items from "Topics.resx" file.
                        allResourceItems = Topics.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);

                        foreach (DictionaryEntry entry in allResourceItems)
                        {
                            topicMarkdown = entry.Value.ToString().Trim();

                            if (!string.IsNullOrWhiteSpace(topicMarkdown) && topicMarkdown.Length > 0)
                            {
                                topic = new HelpTopic();

                                topic.ReferenceKey = entry.Key.ToString().Replace('_', '.').ToLowerInvariant();
                                topic.Title        = Regex.Match(topicMarkdown, titlePattern, RegexOptions.Multiline).Groups[1].Value.Trim();

                                // Removing the title.
                                topicMarkdown = Regex.Replace(topicMarkdown, titlePattern, string.Empty, RegexOptions.Multiline).Trim();

                                mediaItemsMarkerIndex = topicMarkdown.IndexOf(mediaItemsMarker, StringComparison.OrdinalIgnoreCase);

                                if (mediaItemsMarkerIndex >= 0)
                                {
                                    // Extracting and stripping media items list.
                                    mediaItemsMarkdown = topicMarkdown.Substring(mediaItemsMarkerIndex + mediaItemsMarker.Length).Trim();
                                    topicMarkdown      = topicMarkdown.Substring(0, mediaItemsMarkerIndex).Trim();

                                    // Getting list items and separating them into its own collection (displayed as a gallery).
                                    topic.MediaItems = mediaItemsMarkdown.Split(new string[] { "- " }, StringSplitOptions.None)
                                                       .Select(item => item.Trim()).Where(item => !string.IsNullOrWhiteSpace(item) && item.Length > 0)
                                                       .Select(item => item.IndexOf('/') < 0 ? string.Format("/Assets/img/help/{0}/{1}", entry.Key, item) : item).ToList();
                                }

                                topic.Body = topicMarkdown;

                                if (scores.ContainsKey(topic.ReferenceKey))
                                {
                                    topic.Score = scores[topic.ReferenceKey];
                                }

                                _log.Info(string.Format("Adding new topic: {0}...", topic.ReferenceKey));

                                // Inserting new topic.
                                repository.Update(topic);

                                totalAddedTopics++;
                            }
                        }
                    }

                    _log.Info(string.Format("Done adding topics (total: {0}).", totalAddedTopics));
                }
                catch (Exception ex)
                {
                    _log.Error("Failed to populate help topics.", ex);
                }

                _isPopulating = false;
            }
        }
示例#3
0
        /// <summary>
        /// Collects queued impressions.
        /// </summary>
        public static void CollectQueuedImpressions()
        {
            Presentation           p                = null;
            IMessageQueue          queue            = null;
            GenericMessageBody     body             = null;
            IEnumerable <Message>  messages         = null;
            IDictionary <int, int> addedImpressions = null;
            List <Tuple <GenericMessageBody, Message> > dispatchedMessages = null;

            if (!_isCollecting)
            {
                _isCollecting = true;

                queue              = MessageQueueManager.Current.GetQueue(MessageQueueType.Impressions);
                messages           = queue.GetMessages().ToList();
                dispatchedMessages = new List <Tuple <GenericMessageBody, Message> >();

                if (messages != null && messages.Any())
                {
                    try
                    {
                        using (var repository = new Storage.Repositories.NHibernateRepository <Impression>())
                        {
                            foreach (var m in messages)
                            {
                                try
                                {
                                    body = GenericMessageBody.FromString(m.Body);

                                    if (body != null)
                                    {
                                        repository.Update(new Impression()
                                        {
                                            PresentationId     = body.GetParameter <int>("PresentationId"),
                                            PresentationUserId = body.GetParameter <int>("PresentationUserId"),
                                            Timestamp          = m.Created
                                        });

                                        dispatchedMessages.Add(new Tuple <GenericMessageBody, Message>(body, m));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _log.Error(string.Format("Failed to collect message with Id '{0}'", m.Id), ex);
                                }
                            }
                        }

                        queue.RemoveMessages(dispatchedMessages.Select(m => m.Item2));
                        addedImpressions = dispatchedMessages.GroupBy(t => t.Item1.GetParameter <int>("PresentationId")).ToDictionary(g => g.Key, g => g.Count());

                        using (var repository = new Storage.Repositories.RavenRepository <Presentation>())
                        {
                            foreach (var imp in addedImpressions)
                            {
                                try
                                {
                                    p = repository.Select(imp.Key);

                                    if (p != null && p.TotalImpressions < 10000)
                                    {
                                        p.TotalImpressions += imp.Value;
                                        repository.Update(p);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _log.Error(string.Format("Failed to update total impressions for infographic with Id '{0}'", imp.Key), ex);
                                }
                            }
                        }

                        if (addedImpressions != null && addedImpressions.Any())
                        {
                            CollectSocialImpacts(addedImpressions.Keys);
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Error(string.Format("Failed to collect {0} impression(s).", messages.Count()), ex);
                    }
                }

                _isCollecting = false;
            }
        }