Example #1
0
        /// <summary>
        /// Tries to get a subreddit from the web by the display name.
        /// </summary>
        /// <returns>Returns null if the subreddit get fails.</returns>
        public async Task <Subreddit> GetSubredditFromWebByDisplayName(string displayName)
        {
            Subreddit foundSubreddit = null;

            try
            {
                // Make the call
                string jsonResponse = await m_baconMan.NetworkMan.MakeRedditGetRequestAsString($"/r/{displayName}/about/.json");

                // Parse the new subreddit
                foundSubreddit = await MiscellaneousHelper.ParseOutRedditDataElement <Subreddit>(m_baconMan, jsonResponse);
            }
            catch (Exception e)
            {
                m_baconMan.TelemetryMan.ReportUnexpectedEvent(this, "failed to get subreddit", e);
                m_baconMan.MessageMan.DebugDia("failed to get subreddit", e);
            }

            // If we found it add it to the cache.
            if (foundSubreddit != null)
            {
                lock (m_tempSubredditCache)
                {
                    m_tempSubredditCache.Add(foundSubreddit);
                }
            }

            return(foundSubreddit);
        }
Example #2
0
        private void MarkdownText_OnMarkdownLinkTapped(object sender, UniversalMarkdown.OnMarkdownLinkTappedArgs e)
        {
            try
            {
                // See if what we have is a reddit link
                RedditContentContainer redditContent = MiscellaneousHelper.TryToFindRedditContentInLink(e.Link);

                if (redditContent != null && redditContent.Type != RedditContentType.Website)
                {
                    // If we are opening a reddit link show the content and hide hide the message.
                    App.BaconMan.ShowGlobalContent(redditContent);

                    // Hide the box
                    Close_OnIconTapped(null, null);
                }
                else
                {
                    // If we have a link show it but don't close the message.
                    App.BaconMan.ShowGlobalContent(e.Link);
                }
            }
            catch (Exception ex)
            {
                App.BaconMan.TelemetryMan.ReportUnexpectedEvent(this, "MOTDLinkFailedToOpen", ex);
                App.BaconMan.MessageMan.DebugDia("MOTDLinkFailedToOpen", ex);
            }
        }
Example #3
0
        /// <summary>
        /// Called when the send button is tapped.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Send_OnIconTapped(object sender, EventArgs e)
        {
            string comment = ui_textBox.Text;

            if (String.IsNullOrWhiteSpace(comment))
            {
                App.BaconMan.MessageMan.ShowMessageSimple("\"Silence is a source of great strength.\" - Lao Tzu", "Except on reddit. Go on, say something.");
                return;
            }

            // Show loading
            ui_sendingOverlayProgress.IsActive = true;
            VisualStateManager.GoToState(this, "ShowOverlay", true);

            // Try to send the comment
            string response = await Task.Run(() => MiscellaneousHelper.SendRedditComment(App.BaconMan, m_itemRedditId, comment));

            // If we have a post send the status to the collector
            bool wasSuccess = false;

            if (m_parentPost != null)
            {
                // Get the comment collector for this post.
                CommentCollector collector = CommentCollector.GetCollector(m_parentPost, App.BaconMan);

                // Tell the collector of the change, this will show any message boxes needed.
                wasSuccess = await Task.Run(() => collector.AddNewUserComment(response, m_itemRedditId));
            }
            else
            {
                // If we are here we are a message. Validate for ourselves.
                // #todo, make this validation better, add capta support. Both responses to messages and post replies will have "author"
                if (!String.IsNullOrWhiteSpace(response) && response.Contains("author"))
                {
                    wasSuccess = true;
                }
                else
                {
                    wasSuccess = false;
                    App.BaconMan.MessageMan.ShowMessageSimple("That's Not Right", "We can't send this message right now, check your Internet connection");
                }
            }


            if (wasSuccess)
            {
                // Clear the reddit id so we won't open back up with the
                // same text
                m_itemRedditId = "";

                // Hide the comment box.
                HideBox();
            }
            else
            {
                // Hide the overlay
                VisualStateManager.GoToState(this, "HideOverlay", true);
            }
        }
Example #4
0
        /// <summary>
        /// Fired when we should load the content.
        /// </summary>
        public async void OnPrepareContent()
        {
            // Defer so we give the UI time to work.
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                var headerText = "";
                var minorText  = "";

                if (_contentPanelBase.Source.IsSelf)
                {
                    headerText = "There's no content here!";
                    minorText  = "Scroll down to view the discussion.";
                }
                else
                {
                    _content = MiscellaneousHelper.TryToFindRedditContentInLink(_contentPanelBase.Source.Url);

                    switch (_content.Type)
                    {
                    case RedditContentType.Subreddit:
                        headerText = "This post links to a subreddit";
                        minorText  = $"Tap anywhere to view /r/{_content.Subreddit}";
                        break;

                    case RedditContentType.Comment:
                        headerText = "This post links to a comment thread";
                        minorText  = "Tap anywhere to view it";
                        break;

                    case RedditContentType.Post:
                        headerText = "This post links to a reddit post";
                        minorText  = $"Tap anywhere to view it";
                        break;

                    case RedditContentType.User:
                        headerText = "This post links to a reddit user page";
                        minorText  = $"Tap anywhere to view {_content.User}";
                        break;

                    case RedditContentType.Website:
                        // This shouldn't happen
                        App.BaconMan.MessageMan.DebugDia("Got website back when prepare on reddit content control");
                        TelemetryManager.ReportUnexpectedEvent(this, "GotWebsiteOnPrepareRedditContent");
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                ui_headerText.Text = headerText;
                ui_minorText.Text  = minorText;

                // Hide loading
                _contentPanelBase.FireOnLoading(false);
            });
        }
Example #5
0
        /// <summary>
        /// Called by the consumer when a post should be saved or hidden
        /// </summary>
        /// <param name="post">The post to be marked as read</param>
        /// <param name="postPosition">A hint to the position of the post</param>
        public async void SaveOrHidePost(Post post, bool?save, bool?hide, int postPosition = 0)
        {
            // Using the post and suggested index, find the real post and index
            Post collectionPost = post;

            FindPostInCurrentCollection(ref collectionPost, ref postPosition);

            if (collectionPost == null)
            {
                // We didn't find it.
                return;
            }

            // Change the UI now
            if (save.HasValue)
            {
                collectionPost.IsSaved = save.Value;
            }
            else if (hide.HasValue)
            {
                collectionPost.IsHidden = hide.Value;
            }
            else
            {
                return;
            }

            // Make the call to save or hide the post
            bool success = await MiscellaneousHelper.SaveOrHideRedditItem(m_baconMan, "t3_" + collectionPost.Id, save, hide);

            if (!success)
            {
                // We failed, revert the UI.
                if (save.HasValue)
                {
                    collectionPost.IsSaved = save.Value;
                }
                else if (hide.HasValue)
                {
                    collectionPost.IsHidden = hide.Value;
                }
                else
                {
                    return;
                }
            }
            else
            {
                // Fire off that a update happened.
                FireCollectionUpdated(postPosition, new List <Post>()
                {
                    collectionPost
                }, false, false);
            }
        }
        /// <summary>
        /// Fired when we should load the content.
        /// </summary>
        /// <param name="source"></param>
        public async void OnPrepareContent()
        {
            // Defer so we give the UI time to work.
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                string headerText = "";
                string minorText  = "";

                if (m_base.Source.IsSelf)
                {
                    headerText = "There's no content here!";
                    minorText  = "Scroll down to view the discussion.";
                }
                else
                {
                    m_content = MiscellaneousHelper.TryToFindRedditContentInLink(m_base.Source.Url);

                    switch (m_content.Type)
                    {
                    case RedditContentType.Subreddit:
                        headerText = "This post links to a subreddit";
                        minorText  = $"Tap anywhere to view /r/{m_content.Subreddit}";
                        break;

                    case RedditContentType.Comment:
                        headerText = "This post links to a comment thread";
                        minorText  = "Tap anywhere to view it";
                        break;

                    case RedditContentType.Post:
                        headerText = "This post links to a reddit post";
                        minorText  = $"Tap anywhere to view it";
                        break;

                    case RedditContentType.User:
                        headerText = "This post links to a reddit user page";
                        minorText  = $"Tap anywhere to view {m_content.User}";
                        break;

                    case RedditContentType.Website:
                        // This shouldn't happen
                        App.BaconMan.MessageMan.DebugDia("Got website back when prepare on reddit content control");
                        break;
                    }
                }

                ui_headerText.Text = headerText;
                ui_minorText.Text  = minorText;

                // Hide loading
                m_base.FireOnLoading(false);
            });
        }
Example #7
0
        /// <summary>
        /// Called when we should delete a post from this user.
        /// </summary>
        public async void DeletePost(Post post)
        {
            // Try to delete it.
            bool success = await Task.Run(() => MiscellaneousHelper.DeletePost(m_baconMan, post.Id));

            if (success)
            {
                m_baconMan.MessageMan.ShowMessageSimple("Bye Bye", "Your post has been deleted.");
            }
            else
            {
                m_baconMan.MessageMan.ShowMessageSimple("That's not right", "We can't edit your post right now, check your Internet connection.");
            }
        }
Example #8
0
        /// <summary>
        /// Fired when someone wants to show the global content presenter
        /// </summary>
        /// <param name="link">What to show</param>
        public void ShowGlobalContent(string link)
        {
            // Validate that the link can't be opened by the subreddit viewer
            RedditContentContainer container = MiscellaneousHelper.TryToFindRedditContentInLink(link);

            if (container != null)
            {
                ShowGlobalContent(container);
            }
            else
            {
                ui_globalContentPresenter.ShowContent(link);
            }
        }
Example #9
0
        public static async void OnSaveTapped(Comment comment)
        {
            // Update the UI now
            comment.IsSaved = !comment.IsSaved;

            // Make the call
            var success = await MiscellaneousHelper.SaveOrHideRedditItem(App.BaconMan, "t1_" + comment.Id, comment.IsSaved, null);

            // If we failed revert
            if (!success)
            {
                comment.IsSaved = !comment.IsSaved;
            }
        }
Example #10
0
        /// <summary>
        /// Called by the host when it queries if we can handle a post.
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        static public bool CanHandlePost(Post post)
        {
            // If this is a self post with no text we will handle this.
            if (post.IsSelf && String.IsNullOrWhiteSpace(post.Selftext))
            {
                return(true);
            }

            // Check if this is a reddit content post, if so this is us
            if (!String.IsNullOrWhiteSpace(post.Url))
            {
                return(MiscellaneousHelper.TryToFindRedditContentInLink(post.Url) != null);
            }
            return(false);
        }
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
    if (intent.Action.Equals(PlaybackConsts.Start))
    {
        var notification =
            new Notification.Builder(this)
            .SetContentTitle(Resources.GetString(Resource.String.ApplicationName))
            .SetContentText("HELLO WORLD")
            .SetOngoing(true)
            .Build();
        StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
    }
    if (intent.Action.Equals(PlaybackConsts.Start))
    {
        var uri     = Android.Net.Uri.Parse(intent.GetStringExtra("uri"));
        var content = MiscellaneousHelper.GetTextFromStream(ContentResolver.OpenInputStream(uri));
        Dictionary = DictionaryFactory.Get(content);
        Playing    = true;
        Task.Factory.StartNew(async() =>
        {
            await PlayDictionary();
        });
    }
    if (intent.Action.Equals(PlaybackConsts.PlayPause))
    {
        bool isChecked = intent.GetBooleanExtra("isChecked", false);
        PlayPause(isChecked);
    }
    if (intent.Action.Equals(PlaybackConsts.NextEntry))
    {
        NextEntry();
    }
    if (intent.Action.Equals(PlaybackConsts.PrevEntry))
    {
        PrevEntry();
    }
    if (intent.Action.Equals(PlaybackConsts.Stop))
    {
        Task.Factory.StartNew(async() =>
        {
            await Stop();
        });

        StopForeground(true);
        StopSelf();
    }
    return(StartCommandResult.Sticky);
}
Example #12
0
        /// <summary>
        /// Called when the send button is tapped.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            // Make sure we have a string unless we are editing a post selftext, then we can have an empty comment.
            string comment = ui_textBox.Text;

            if (String.IsNullOrWhiteSpace(comment) && !m_itemRedditId.StartsWith("t3_") && !m_isEdit)
            {
                App.BaconMan.MessageMan.ShowMessageSimple("\"Silence is a source of great strength.\" - Lao Tzu", "Except on reddit. Go on, say something.");
                return;
            }

            // Show loading
            ui_sendingOverlayProgress.IsActive = true;
            VisualStateManager.GoToState(this, "ShowOverlay", true);

            // Try to send the comment
            string response = await Task.Run(() => MiscellaneousHelper.SendRedditComment(App.BaconMan, m_itemRedditId, comment, m_isEdit));

            if (response != null)
            {
                // Now fire the event that a comment was submitted.
                try
                {
                    OnCommentSubmittedArgs args = new OnCommentSubmittedArgs()
                    {
                        Response = response,
                        IsEdit   = m_isEdit,
                        RedditId = m_itemRedditId,
                        Context  = m_context,
                    };
                    m_onCommentSubmitted.Raise(this, args);
                }
                catch (Exception ex)
                {
                    App.BaconMan.MessageMan.DebugDia("failed to fire OnCommentSubmitted", ex);
                    App.BaconMan.TelemetryMan.ReportUnexpectedEvent(this, "OnCommentSubmittedFireFailed", ex);
                }
            }
            else
            {
                // The network call failed.
                App.BaconMan.MessageMan.ShowMessageSimple("Can't Submit", "We can't seem to submit this right now, check your internet connection.");
                HideLoadingOverlay();
            }
        }
        /// <summary>
        /// Called when we should show the content
        /// </summary>
        /// <param name="post"></param>
        public void OnPrepareContent(Post post)
        {
            string headerText = "";
            string minorText  = "";

            if (post.IsSelf)
            {
                headerText = "There's no content here!";
                minorText  = "Scroll down to view the discussion.";
            }
            else
            {
                m_content = MiscellaneousHelper.TryToFindRedditContentInLink(post.Url);

                switch (m_content.Type)
                {
                case RedditContentType.Subreddit:
                    headerText = "This post links to a subreddit";
                    minorText  = $"Tap anywhere to view /r/{m_content.Subreddit}";
                    break;

                case RedditContentType.Comment:
                    headerText = "This post links to a comment thread";
                    minorText  = "Tap anywhere to view it";
                    break;

                case RedditContentType.Post:
                    headerText = "This post links to a reddit post";
                    minorText  = $"Tap anywhere to view it";
                    break;

                case RedditContentType.Website:
                    // This shouldn't happen
                    App.BaconMan.MessageMan.DebugDia("Got website back when prepare on reddit content control");
                    App.BaconMan.TelemetryMan.ReportUnExpectedEvent(this, "GotWebsiteOnPrepareRedditContent");
                    break;
                }
            }

            ui_headerText.Text = headerText;
            ui_minorText.Text  = minorText;
        }
Example #14
0
        /// <summary>
        /// Called by the host when it queries if we can handle a post.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool CanHandlePost(ContentPanelSource source)
        {
            // If this is a self post with no text we will handle this.
            if (source.IsSelf && string.IsNullOrWhiteSpace(source.SelfText))
            {
                return(true);
            }

            // Check if this is a reddit content post, if so this is us
            if (string.IsNullOrWhiteSpace(source.Url))
            {
                return(false);
            }

            // Check the content
            var container = MiscellaneousHelper.TryToFindRedditContentInLink(source.Url);

            // If we got a container and it isn't a web site return it.
            return(container != null && container.Type != RedditContentType.Website);
        }
Example #15
0
        /// <summary>
        /// Fired when someone wants to show the global content presenter
        /// </summary>
        /// <param name="link">What to show</param>
        public async void ShowGlobalContent(string link)
        {
            // Validate that the link can't be opened by the subreddit viewer
            RedditContentContainer container = MiscellaneousHelper.TryToFindRedditContentInLink(link);

            // If this is our special rate link, show rate and review.
            if (!String.IsNullOrWhiteSpace(link) && link.ToLower().Equals("ratebaconit"))
            {
                // Open the store
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    try
                    {
                        await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-windows-store://review/?ProductId=9wzdncrfj0bc"));
                    }
                    catch (Exception) { }
                });

                // Show a dialog. This will only work on devices that can show many windows.
                // So also set the time and if we restore fast enough we will show the dialog also
                App.BaconMan.MessageMan.ShowMessageSimple("Thanks ❤", "Thank you for reviewing Baconit, we really appreciate your support of the app!");
                m_reviewLeaveTime = DateTime.Now;
                return;
            }

            // Make sure we got a response and it isn't a website
            if (container != null && container.Type != RedditContentType.Website)
            {
                ShowGlobalContent(container);
            }
            else
            {
                if (container != null && container.Type == RedditContentType.Website)
                {
                    // We have a link from the reddit presenter, overwrite the link
                    link = container.Website;
                }

                ui_globalContentPresenter.ShowContent(link);
            }
        }
Example #16
0
        /// <summary>
        /// Fired when someone wants to show the global content presenter
        /// </summary>
        /// <param name="link">What to show</param>
        public void ShowGlobalContent(string link)
        {
            // Validate that the link can't be opened by the subreddit viewer
            RedditContentContainer container = MiscellaneousHelper.TryToFindRedditContentInLink(link);

            // Make sure we got a response and it isn't a website
            if (container != null && container.Type != RedditContentType.Website)
            {
                ShowGlobalContent(container);
            }
            else
            {
                if (container != null && container.Type == RedditContentType.Website)
                {
                    // We have a link from the reddit presenter, overwrite the link
                    link = container.Website;
                }

                ui_globalContentPresenter.ShowContent(link);
            }
        }
        public async Task <IHttpActionResult> SaveRepositoryInfo([FromBody] List <Repository> lstSearch)
        {
            HttpResponseMessage response = new HttpResponseMessage();
            DataTable           dt       = new DataTable();

            try
            {
                dt = MiscellaneousHelper.ConvertToDataTableForRepostory(lstSearch, UserID, BPID);
                await Task.Run(() => _fhFileService.SaveRepositoryInfo(dt, BPID));

                return(Ok());
            }
            catch (Exception ex)
            {
                response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
                return(ResponseMessage(response));
            }
            finally
            {
            }
        }
Example #18
0
        /// <summary>
        ///     Called when the user added a comment or edit an existing comment.
        /// </summary>
        /// <returns></returns>
        public bool CommentAddedOrEdited(string parentOrOrgionalId, string serverResponse, bool isEdit)
        {
            // Assume if we can find author we are successful. Not sure if that is safe or not... :)
            if (!string.IsNullOrWhiteSpace(serverResponse) && serverResponse.Contains("\"author\""))
            {
                // Do the next part in a try catch so if we fail we will still report success since the
                // message was sent to reddit.
                try
                {
                    // Parse the new comment
                    var newComment = MiscellaneousHelper.ParseOutRedditDataElement <Comment>(_baconMan, serverResponse)
                                     .Result;

                    if (isEdit)
                    {
                        UpdateComment(newComment);
                    }
                    else
                    {
                        // Inject the new comment
                        InjectComment(parentOrOrgionalId, newComment);
                    }
                }
                catch (Exception e)
                {
                    // We f****d up adding the comment to the UI.
                    _baconMan.MessageMan.DebugDia("Failed injecting comment", e);
                    TelemetryManager.ReportUnexpectedEvent(this, "AddCommentSuccessButAddUiFailed");
                }

                // If we get to adding to the UI return true because reddit has the comment.
                return(true);
            }

            // Reddit returned something wrong
            _baconMan.MessageMan.ShowMessageSimple("That's not right",
                                                   "Sorry we can't post your comment right now, reddit returned and unexpected message.");
            TelemetryManager.ReportUnexpectedEvent(this, "CommentPostReturnedUnexpectedMessage");
            return(false);
        }
        /// <summary>
        /// Called by the host when it queries if we can handle a post.
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        static public bool CanHandlePost(Post post)
        {
            // If this is a self post with no text we will handle this.
            if (post.IsSelf && String.IsNullOrWhiteSpace(post.Selftext))
            {
                return(true);
            }

            // Check if this is a reddit content post, if so this is us
            if (!String.IsNullOrWhiteSpace(post.Url))
            {
                // Check the content
                RedditContentContainer container = MiscellaneousHelper.TryToFindRedditContentInLink(post.Url);

                // If we got a container and it isn't a web site return it.
                if (container != null && container.Type != RedditContentType.Website)
                {
                    return(true);
                }
            }
            return(false);
        }
Example #20
0
        /// <summary>
        /// Tries to get a subreddit from the web by the display name.
        /// </summary>
        /// <returns>Returns null if the subreddit get fails.</returns>
        public async Task <Subreddit> GetSubredditFromWebByDisplayName(string displayName)
        {
            Subreddit foundSubreddit = null;

            try
            {
                // Make the call
                string jsonResponse = await m_baconMan.NetworkMan.MakeRedditGetRequestAsString($"/r/{displayName}/about/.json");

                // Try to parse out the subreddit
                string subredditData = MiscellaneousHelper.ParseOutRedditDataElement(jsonResponse);
                if (subredditData == null)
                {
                    throw new Exception("Failed to parse out data object");
                }

                // Parse the new subreddit
                foundSubreddit = await Task.Run(() => JsonConvert.DeserializeObject <Subreddit>(subredditData));
            }
            catch (Exception e)
            {
                m_baconMan.TelemetryMan.ReportUnExpectedEvent(this, "failed to get subreddit", e);
                m_baconMan.MessageMan.DebugDia("failed to get subreddit", e);
            }

            // If we found it add it to the cache.
            if (foundSubreddit != null)
            {
                lock (m_tempSubredditCache)
                {
                    m_tempSubredditCache.Add(foundSubreddit);
                }

                // Format the subreddit
                foundSubreddit.Description = WebUtility.HtmlDecode(foundSubreddit.Description);
            }

            return(foundSubreddit);
        }
Example #21
0
        public JsonResult getAllPropertyImages()
        {
            ErrorModel errorModel = new ErrorModel();

            IEnumerable <PropertyImage> propertyImage;
            List <IEnumerable>          pImageInfo = new List <IEnumerable>();

            try
            {
                using (EasyFindPropertiesEntities dbCtx = new EasyFindPropertiesEntities())
                {
                    UnitOfWork unitOfWork = new UnitOfWork(dbCtx);
                    //checking if the landlord id was saved in the session
                    if (Session["userId"] != null)
                    {
                        var userId = (Guid)Session["userId"];
                        var owner  = unitOfWork.Owner.GetOwnerByUserID(userId);
                        propertyImage = unitOfWork.PropertyImage.GetAllPrimaryPropertyImageByOwnerId(owner.ID);

                        foreach (var image in propertyImage)
                        {
                            //adding properties to dictionary to display image to the user
                            Dictionary <String, String> imageInfo = new Dictionary <string, string>();
                            imageInfo.Add("propertyID", image.PropertyID.ToString());
                            imageInfo.Add("imageURL", image.ImageURL);
                            pImageInfo.Add(imageInfo);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorModel = MiscellaneousHelper.PopulateErrorModel(null);

                return(Json(errorModel, JsonRequestBehavior.AllowGet));
            }

            return(Json(pImageInfo, JsonRequestBehavior.AllowGet));
        }
Example #22
0
        /// <summary>
        /// Called when we should show the content
        /// </summary>
        /// <param name="post"></param>
        public void OnPrepareContent(Post post)
        {
            string headerText = "";
            string minorText  = "";

            if (post.IsSelf)
            {
                headerText = "There's no content here!";
                minorText  = "Scroll down to view the discussion.";
            }
            else
            {
                m_content = MiscellaneousHelper.TryToFindRedditContentInLink(post.Url);

                switch (m_content.Type)
                {
                case RedditContentType.Subreddit:
                    headerText = "This post links to a subreddit";
                    minorText  = $"Tap anywhere to view /r/{m_content.Subreddit}";
                    break;

                case RedditContentType.Comment:
                    headerText = "This post links to a comment thread";
                    minorText  = "Tap anywhere to view it";
                    break;

                case RedditContentType.Post:
                    headerText = "This post links to a reddit post";
                    minorText  = $"Tap anywhere to view it";
                    break;
                }
            }

            ui_headerText.Text = headerText;
            ui_minorText.Text  = minorText;
        }
Example #23
0
        /// <summary>
        /// Creates a new collector and starts a search.
        /// </summary>
        /// <param name="searchTerm"></param>
        private async void DoUserSearch(string searchTerm)
        {
            // Make a request for the user
            var userResult = await MiscellaneousHelper.GetRedditUser(App.BaconMan, searchTerm);

            // Else put it in the list
            lock (_mSearchResultsList)
            {
                // First check that we are still searching for the same thing
                if (!ui_searchBox.Text.Equals(searchTerm))
                {
                    return;
                }

                // Search for the footer of the subreddits if it is there
                var count       = 0;
                var insertIndex = -1;
                foreach (var result in _mSearchResultsList)
                {
                    if (result.ResultType == SearchResultTypes.ShowMore && ((string)result.DataContext).Equals(CSubredditShowMoreHeader))
                    {
                        insertIndex = count;
                        break;
                    }
                    count++;
                }

                // See if we found it, if not insert at the top.
                if (insertIndex == -1)
                {
                    insertIndex = 0;
                }

                // Insert the header
                var header = new SearchResult
                {
                    ResultType = SearchResultTypes.Header,
                    HeaderText = "User Result"
                };
                _mSearchResultsList.Insert(insertIndex, header);
                insertIndex++;

                if (userResult != null)
                {
                    // Insert the User
                    var userItem = new SearchResult
                    {
                        ResultType  = SearchResultTypes.User,
                        MajorText   = userResult.Name,
                        MinorText   = $"link karma {userResult.LinkKarma}; comment karma {userResult.CommentKarma}",
                        DataContext = userResult
                    };
                    if (userResult.IsGold)
                    {
                        userItem.MinorAccentText = "Has Gold";
                    }
                    _mSearchResultsList.Insert(insertIndex, userItem);
                    insertIndex++;
                }
                else
                {
                    // Insert no results
                    var noResults = new SearchResult
                    {
                        ResultType = SearchResultTypes.NoResults
                    };
                    _mSearchResultsList.Insert(insertIndex, noResults);
                    insertIndex++;
                }
            }
        }
Example #24
0
        /// <summary>
        /// Fired when the user taps submit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Submit_Click(object sender, RoutedEventArgs e)
        {
            bool isSelfText = ui_isSelfPostCheckBox.IsChecked.HasValue ? ui_isSelfPostCheckBox.IsChecked.Value : false;

            // Grab local copies of the vars
            string titleText         = ui_postTitleTextBox.Text;
            string urlOrMarkdownText = ui_postUrlTextBox.Text.Trim();
            string subreddit         = ui_subredditSuggestBox.Text;

            // Remove focus from the boxes, yes, this is the only and best way to do this. :(
            ui_postTitleTextBox.IsEnabled    = false;
            ui_postTitleTextBox.IsEnabled    = true;
            ui_postUrlTextBox.IsEnabled      = false;
            ui_postUrlTextBox.IsEnabled      = true;
            ui_subredditSuggestBox.IsEnabled = false;
            ui_subredditSuggestBox.IsEnabled = true;

            // Do some basic validation.
            if (String.IsNullOrWhiteSpace(titleText))
            {
                App.BaconMan.MessageMan.ShowMessageSimple("Say Something...", "You can't submit a post with out a title.");
                return;
            }
            if (String.IsNullOrWhiteSpace(urlOrMarkdownText) && !isSelfText)
            {
                App.BaconMan.MessageMan.ShowMessageSimple("Say Something...", $"You can't submit a post with no link.");
                return;
            }
            if (!isSelfText && urlOrMarkdownText.IndexOf(' ') != -1)
            {
                App.BaconMan.MessageMan.ShowMessageSimple("Hmmmmm", "That URL doesn't look quite right, take a second look.");
                return;
            }
            if (String.IsNullOrWhiteSpace(subreddit))
            {
                App.BaconMan.MessageMan.ShowMessageSimple("Where's It Going?", $"You need to pick a subreddit to submit to.");
                return;
            }

            // Show the overlay
            ui_loadingOverlay.Show(true, "Submitting Post...");

            // Make the request
            SubmitNewPostResponse response = await MiscellaneousHelper.SubmitNewPost(App.BaconMan, titleText, urlOrMarkdownText, subreddit, isSelfText, ui_sendRepliesToInbox.IsChecked.Value);

            // Hide the overlay
            ui_loadingOverlay.Hide();

            if (response.Success && !String.IsNullOrWhiteSpace(response.NewPostLink))
            {
                // Navigate to the new post.
                App.BaconMan.ShowGlobalContent(response.NewPostLink);

                // Clear out all of the text so when we come back we are clean
                ui_postTitleTextBox.Text        = "";
                ui_postUrlTextBox.Text          = "";
                ui_isSelfPostCheckBox.IsChecked = false;
                IsSelfPostCheckBox_Click(null, null);

                // Delete the current draft data
                ClearDraft();
            }
            else
            {
                // Something went wrong, show an error.
                string title = "We Can't Post That";
                string message;

                switch (response.RedditError)
                {
                case SubmitNewPostErrors.ALREADY_SUB:
                    message = "That link has already been submitted";
                    break;

                case SubmitNewPostErrors.BAD_CAPTCHA:
                    message = "You need to provide a CAPTCHA to post. Baconit currently doesn't support CAPTCHA so you will have to post this from your desktop. After a few post try from Baconit again. Sorry about that.";
                    break;

                case SubmitNewPostErrors.DOMAIN_BANNED:
                    message = "The domain of this link has been banned for spam.";
                    break;

                case SubmitNewPostErrors.IN_TIMEOUT:
                case SubmitNewPostErrors.RATELIMIT:
                    message = "You have posted too much recently, please wait a while before posting again.";
                    break;

                case SubmitNewPostErrors.NO_LINKS:
                    message = "This subreddit only allows self text, you can't post links to it.";
                    break;

                case SubmitNewPostErrors.NO_SELFS:
                    message = "This subreddit only allows links, you can't post self text to it.";
                    break;

                case SubmitNewPostErrors.SUBREDDIT_NOEXIST:
                    message = "The subreddit your trying to post to doesn't exist.";
                    break;

                case SubmitNewPostErrors.SUBREDDIT_NOTALLOWED:
                    message = "Your not allowed to post to the subreddit you selected.";
                    break;

                case SubmitNewPostErrors.BAD_URL:
                    message = "Your URL is invalid, please make sure it is correct.";
                    break;

                default:
                case SubmitNewPostErrors.INVALID_OPTION:
                case SubmitNewPostErrors.SUBREDDIT_REQUIRED:
                    title   = "Something Went Wrong";
                    message = "We can't post for you right now, check your Internet connection.";
                    break;
                }
                App.BaconMan.MessageMan.ShowMessageSimple(title, message);
            }
        }
        public JsonResult RequestProperty(PropertyRequisition request, String contactPurpose)
        {
            ErrorModel errorModel = new ErrorModel();

            if (ModelState.IsValid)
            {
                try
                {
                    using (EasyFindPropertiesEntities dbCtx = new EasyFindPropertiesEntities())
                    {
                        if (Session["userId"] != null)
                        {
                            UnitOfWork unitOfWork = new UnitOfWork(dbCtx);

                            Guid userId = (Guid)Session["userId"];

                            if (contactPurpose.Equals("requisition"))
                            {
                                PropertyRequisition requisition = new PropertyRequisition()
                                {
                                    ID           = Guid.NewGuid(),
                                    UserID       = userId,
                                    PropertyID   = request.PropertyID,
                                    Msg          = request.Msg,
                                    IsAccepted   = false,
                                    ExpiryDate   = DateTime.Now.AddDays(7),//requisition should last for a week
                                    DateTCreated = DateTime.Now
                                };

                                unitOfWork.PropertyRequisition.Add(requisition);
                                unitOfWork.save();

                                var userTo = unitOfWork.Property.GetPropertyOwnerByPropID(request.PropertyID).User;
                                //DashboardHub.BroadcastUserMessages(userTo.Email); broadcast requisition
                            }
                            else
                            {
                                var userTo = unitOfWork.Property.GetPropertyOwnerByPropID(request.PropertyID).User;

                                Message message = new Message()
                                {
                                    ID           = Guid.NewGuid(),
                                    To           = userTo.ID,
                                    From         = userId,
                                    Msg          = request.Msg,
                                    Seen         = false,
                                    DateTCreated = DateTime.Now
                                };

                                unitOfWork.Message.Add(message);
                                unitOfWork.save();
                                DashboardHub.BroadcastUserMessages(userTo.Email);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    errorModel = MiscellaneousHelper.PopulateErrorModel(ModelState);
                }
            }
            else
            {
                errorModel = MiscellaneousHelper.PopulateErrorModel(ModelState);
            }

            MvcCaptcha.ResetCaptcha("captcha");//TODO find a way to reload captcha image after returning the response
            return(Json(errorModel));
        }/*
Example #26
0
        public void PanelSetup(IPanelHost host, Dictionary <string, object> arguments)
        {
            _mHost = host;

            if (!arguments.ContainsKey(PanelManager.NavArgsUserName))
            {
                ReportUserLoadFailed();
                return;
            }

            // Get the user
            var userName = (string)arguments[PanelManager.NavArgsUserName];

            ui_userName.Text = userName;

            // Show loading
            ui_loadingOverlay.Show(true, "Finding " + userName);

            // Do the loading on a thread to get off the UI
            Task.Run(async() =>
            {
                // Make the request
                _mUser = await MiscellaneousHelper.GetRedditUser(App.BaconMan, userName);

                // Jump back to the UI thread, we will use low priority so we don't make any animations choppy.
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Check we got it.
                    if (_mUser == null)
                    {
                        ReportUserLoadFailed();
                        return;
                    }

                    // Fill in the UI
                    var origin             = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                    var postTime           = origin.AddSeconds(_mUser.CreatedUtc).ToLocalTime();
                    ui_accountAgeText.Text = $"{TimeToTextHelper.TimeElapseToText(postTime)} old";

                    // Set cake day
                    var elapsed   = DateTime.Now - postTime;
                    var fullYears = Math.Floor((elapsed.TotalDays / 365));
                    var daysUntil = (int)(elapsed.TotalDays - (fullYears * 365));
                    ui_cakeDayHolder.Visibility = daysUntil == 0 ? Visibility.Visible : Visibility.Collapsed;

                    // Set karma
                    ui_linkKarmaText.Text    = $"{_mUser.LinkKarma:N0}";
                    ui_commentKarmaText.Text = $"{_mUser.CommentKarma:N0}";

                    // Set Gold
                    ui_goldHolder.Visibility = _mUser.IsGold ? Visibility.Visible : Visibility.Collapsed;

                    // Hide loading
                    ui_loadingOverlay.Hide();

                    // Kick off the updates
                    GetUserComments();
                    GetUserPosts();
                });
            });
        }