Beispiel #1
0
        public ActionResult _WizardReactionTypeExpectedScreen(RantViewModel viewModel,
                                                              string prevBtn, string nextBtn)
        {
            Rant newRant = GetRantSession();

            if (prevBtn != null)
            {
                if (viewModel.CurrentRant == null)
                {
                    viewModel.CurrentRant = new Rant();
                }

                return(View("Create", viewModel));
            }

            if (nextBtn != null && ModelState.IsValid)
            {
                Rant modelRant = viewModel.CurrentRant;

                if (modelRant == null)
                {
                    return(PartialView(viewModel));
                }

                newRant.ExpectedReactionRequest = viewModel.CurrentRant.ExpectedReactionRequest;

                return(RedirectToAction("_WizardSummary", viewModel));
            }

            return(PartialView(this));
        }
Beispiel #2
0
        public async Task <IActionResult> Edit(int id, [Bind("RantId,Summary,DateCreated,Review")] Rant rant)
        {
            if (id != rant.RantId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    ApplicationUser user = await GetCurrentUserAsync();

                    rant.ApplicationUserId = user.Id;

                    _context.Update(rant);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RantExists(rant.RantId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(rant));
        }
Beispiel #3
0
        private async Task <Rant> SurpriseMe(Func <Rant, bool> acceptor, int tries)
        {
            string url = MakeUrl(Constants.PathRants + "surprise");

            while (tries < MaxTries)
            {
                var response = await client.GetAsync(url);

                var responseText = await response.Content.ReadAsStringAsync();

                JObject obj = JObject.Parse(responseText);

                if (CheckSuccess(obj))
                {
                    Rant r = DataObject.Parse <Rant>(obj["rant"] as JObject);
                    if (acceptor != null)
                    {
                        if (acceptor.Invoke(r)) //Accepted
                        {
                            return(r);
                        }
                        else
                        {
                            tries++;
                        }
                    }
                    else
                    {
                        return(r);
                    }
                }
            }

            throw new Exception("Was not able to find a new rant.");
        }
Beispiel #4
0
        public ActionResult _WizardTellUsMoreScreen(RantViewModel viewModel,
                                                    string prevBtn, string nextBtn)
        {
            Rant newRant = GetRantSession();

            if (prevBtn != null)
            {
                if (viewModel.CurrentRant == null)
                {
                    viewModel.CurrentRant = new Rant();
                }

                TempData["emotionItems"] = viewModel.Emotions.EmotionItems;

                return(View("Create", viewModel));
            }

            if (nextBtn != null && ModelState.IsValid)
            {
                Rant modelRant = viewModel.CurrentRant;

                if (modelRant == null)
                {
                    return(PartialView(viewModel));
                }

                newRant.Description = viewModel.CurrentRant.Description;

                return(PartialView("_WizardReactionTypeExpectedScreen", viewModel));
            }

            return(PartialView(this));
        }
Beispiel #5
0
        /// <summary>
        /// Converting the JSON received into a Rant object which is specified in <see cref="Rant"/>
        /// </summary>
        /// <param name="r">The JSON string received by the API containing the Rant</param>
        /// <returns>A Rant object with the properties received</returns>
        private Rant JSONToRantObject(dynamic r)
        {
            var rant = new Rant
            {
                id              = r.id,
                text            = r.text,
                score           = r.score,
                created_time    = r.created_time,
                num_comments    = r.num_comments,
                tags            = r.tags.ToObject <List <string> >(),
                vote_state      = r.vote_state,
                edited          = r.edited,
                user_id         = r.user_id,
                user_username   = r.user_username,
                user_score      = r.user_score,
                user_avatar_url = r.user_avatar.i
            };

            try
            {
                rant.attachedImageUrl = r.attached_image.url;
            }
            catch { }
            return(rant);
        }
Beispiel #6
0
        public PartialViewResult _WizardTitleScreen(RantViewModel viewModel, string prevBtn, string nextBtn)
        {
            if (nextBtn != null && ModelState.IsValid)
            {
                Rant modelRant = viewModel.CurrentRant;

                if (modelRant == null)
                {
                    return(PartialView(viewModel));
                }

                Rant newRant = GetRantSession();
                newRant.EmotionId = viewModel.Emotions.SelectedItemId;
                viewModel.Emotions.EmotionItems = (List <SelectListItem>)TempData["emotionItems"];

                string emotionType = viewModel.Emotions.EmotionItems.FirstOrDefault(
                    e => e.Value == newRant.EmotionId.ToString()).Text;

                newRant.Title = string.Format("I'm {0} {1}", emotionType, modelRant.Title);

                return(PartialView("_WizardTellUsMoreScreen", viewModel));
            }

            return(PartialView());
        }
Beispiel #7
0
 private Rant GetRantSession()
 {
     if (Session["rant"] == null)
     {
         Session["rant"] = new Rant();
     }
     return((Rant)Session["rant"]);
 }
        public RantViewerViewModel(Window window, Rant rant, IDevRantClient api, Action <string> onScroll)
        {
            Rant          = rant;
            this.api      = api;
            this.window   = window;
            this.onScroll = onScroll;

            Comments = new ObservableCollection <Comment>();
            GetComments();
        }
Beispiel #9
0
        private void GetDataSources(string locale)
        {
            DsName = this._notifier.Flow <Name>(new Name(locale));
            var notifier = this._notifier;
            var date     = new Date("en")
            {
                Locale = locale
            };

            DsDate = notifier.Flow <Date>(date);
            DsRant = notifier.Flow <Rant>(new Rant());
        }
Beispiel #10
0
        public HttpResponseMessage UpdateRant(Rant rant, int Id)
        {
            rant.Id = Id;
            var repository = new RantsRepository();
            var result     = repository.Update(rant);

            if (result)
            {
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Could not update rant information, please try again later."));
        }
        public JsonResult PostRant(PostRequest Rant)
        {
            try
            {
                var rant = new Rant
                {
                    UserId    = CurrentUser.UserId(),
                    Timestamp = DateTime.Now,
                    Text      = Rant.Text.ToUpper()
                };

                if (Rant.Tags == null)
                {
                    return(Json(new ApiResponse(false, "At least one tag is required.")));
                }

                if (Rant.Tags.Any(t => string.IsNullOrWhiteSpace(t)))
                {
                    return(Json(new ApiResponse(false, "You cannot submit an empty tag.")));
                }

                if (string.IsNullOrWhiteSpace(Rant.Text))
                {
                    return(Json(new ApiResponse(false, "You cannot submit an empty rant.")));
                }

                using (var context = new EnrampageEntities())
                {
                    context.Tags.AddRange(
                        Rant.Tags.Except(context.Tags.Where(t => !t.User.Banned).Select(t => t.Text))
                        .Select(t => new Tag {
                        UserId = rant.UserId, Text = t
                    }));
                    context.SaveChanges();

                    foreach (var tag in Rant.Tags)
                    {
                        rant.Tags.Add(context.Tags.First(t => !t.User.Banned && t.Text == tag));
                    }

                    context.Rants.Add(rant);
                    context.SaveChanges();
                }

                return(Json(new ApiResponse(true, "Posted rant successfully.", RantResponse.FromRant(rant, ReportState.Removable))));
            }
            catch (Exception Ex)
            {
                LogHelper.Log(Ex);
                return(Json(new ApiResponse(false, "Failed to post rant.")));
            }
        }
Beispiel #12
0
        internal void AddUpdate(Rant r)
        {
            //TODO: Need someway to check for dups before adding
            foreach (var existing in UpdatesFeed)
            {
                if (existing.ID == r.ID)
                {
                    return;
                }
            }

            UpdatesFeed.Add(r);
        }
Beispiel #13
0
        public RantViewerWindow(Rant rant, IDevRantClient api)
        {
            InitializeComponent();

            vm          = new RantViewerViewModel(this, rant, api, Scroll);
            DataContext = vm;

            scroller = new ScrollHandler(ScrollViewer);

            //TODO: Check if this works
            Top  = 10;
            Left = Utilities.GetLeft(Width);

            //ScrollViewer.Focus();
        }
        public Task <Result <string, Error> > Handle(CreateRantWithIdCommand request, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(request.Content))
            {
                return(Task.FromResult(Result <string, Error> .Error(new InvalidRant())));
            }

            if (rants.ContainsKey(request.Id))
            {
                return(Task.FromResult(Result <string, Error> .Error(new DuplicateId())));
            }

            var rant = new Rant(request.Id, request.Content, request.Tags);

            rants.Add(rant.ID, rant);
            return(Task.FromResult(Result <string, Error> .Success(request.Id)));
        }
Beispiel #15
0
        public async Task <IActionResult> Create([Bind("Summary, ApplicationUserId")] Rant rant)
        {
            ModelState.Remove("DateCreated");
            if (ModelState.IsValid)
            {
                ApplicationUser user = await GetCurrentUserAsync();

                rant.ApplicationUserId = user.Id;
                var Date = DateTime.Now;
                rant.DateCreated = Date;
                _context.Add(rant);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(rant));
        }
Beispiel #16
0
        public bool Update(Rant rant)
        {
            using (var db = GetDb())
            {
                db.Open();

                var updateRant = db.Execute(@"UPDATE [dbo].[Rants]
                                                SET [Title] = @Title,
                                                    [CategoryId] = @CategoryId,
                                                    [Target] = @Target,
                                                    [Body] = @Body,
                                                    [IsFavorite] = @IsFavorite
                                                WHERE Id = @Id", rant);

                return(updateRant == 1);
            }
        }
Beispiel #17
0
        public ActionResult Details(int?id)
        {
            RantViewModel viewModel = new RantViewModel(_rantRepository);

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            if (ModelState.IsValid)
            {
                Rant rant = viewModel.GetRantById((int)id);
                return(View(rant));
            }

            return(RedirectToAction("Index"));
        }
Beispiel #18
0
        private void RantControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                this.item = e.NewValue as FeedItem;

                Rant r = item as Rant;
                if (r != null)
                {
                    if (r.Username == AppManager.Instance.API.User.LoggedInUser)
                    {
                        ByUser = true;
                    }

                    ReplyVisibility = Visibility.Visible;
                    UpdateText      = r.UpdateText;
                }

                TagsVisibility     = Utilities.ConvertToVisibility(r != null && !string.IsNullOrEmpty(r.TagsString));
                CommentsVisibility = Utilities.ConvertToVisibility(r != null);

                Comment comment = item.AsComment();
                if (comment != null)
                {
                    if (comment.Username == AppManager.Instance.API.User.LoggedInUser)
                    {
                        ByUser = true;
                    }

                    ReplyVisibility = Utilities.ConvertToVisibility(!ByUser);
                }

                ModifyVisibility = Utilities.ConvertToVisibility(ByUser);
                DeleteVisibility = ModifyVisibility;

                var hasAvatar = item as Dtos.HasAvatar;
                if (AppManager.Instance.API != null && UsernameVisibility == Visibility.Visible && hasAvatar != null)
                {
                    Avatar = AppManager.Instance.API.GetAvatar(hasAvatar.AvatarImage);
                }
            }
        }
Beispiel #19
0
        private static async Task loadComments(Rant rant)
        {
            var comments = await producer.GetComments(rant);

            Console.ForegroundColor = ConsoleColor.DarkBlue;
            Console.WriteLine("\n\t\tComments:\n");
            for (int i = 0; i < rant.NumComments; i++)
            {
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine("\tUser: "******"\t\t" + comments[i].Content + "\n");
                switch (Console.ReadKey().Key)
                {
                case ConsoleKey.Spacebar:
                    break;

                case ConsoleKey.Q:
                    return;
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// Returns all the rants from the feed at: https://www.devrant.io/feed
        /// </summary>
        /// <param name="type"> Type of sort e.g. Top, Algo or Recent</param>
        /// <param name="limit">The amount of rants to load</param>
        /// <param name="skip">Skips n amount of rants, useful for paging</param>
        /// <returns>A List of Rants which are iterable</returns>
        public async Task <List <Rant> > GetRantsAsync(SortType type, int limit = 30, int skip = 10)
        {
            var req = await MakeRequestAsync($"{Values.AllRants}?sort={type}&limit={limit}&skip={skip}&{Values.AppId}");

            dynamic results = JsonConvert.DeserializeObject <dynamic>(req);

            if (results.success != "true")
            {
                throw new Exception("Something went wrong");
            }

            List <Rant> rants = new List <Rant>();

            for (int i = 0; i < results.rants.Count; i++)
            {
                var  r    = results.rants[i];
                Rant rant = JSONToRantObject(r);

                rants.Add(rant);
            }

            return(rants);
        }
Beispiel #21
0
        /// <summary>
        /// Gets a single rant given the Id of it
        /// </summary>
        /// <param name="id">The Id of the rant that is being queried</param>
        /// <returns>The Rant that is requested as a Rant object</returns>
        public async Task <Rant> GetRantAsync(int id)
        {
            try
            {
                var req = await MakeRequestAsync($"{Values.SingleRant}{id}?{Values.AppId}");

                dynamic results = JsonConvert.DeserializeObject <dynamic>(req);
                var     r       = results.rant;

                Rant rant = JSONToRantObject(r);

                for (var i = 0; i < results.comments.Count; i++)
                {
                    var current = results.comments[i];
                    rant.rant_comments.Add(JSONToCommentObject(current));
                }
                return(rant);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Beispiel #22
0
        public static void Seed(IApplicationBuilder applicationBuilder)
        {
            using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService <WarehouseDbContext>();
                if (context.Product.Any())
                {
                    return;
                }
                var commerce = new Commerce();
                var finance  = new Finance();
                var lorem    = new Lorem();
                var company  = new Company();
                var internet = new Internet();
                var name     = new Name();
                var rant     = new Rant();

                for (var i = 0; i < 100000; i++)
                {
                    context.Product.Add(new Product
                    {
                        Category    = commerce.Categories(1)[0],
                        Color       = commerce.Color(),
                        Ean13       = commerce.Ean13(),
                        Name        = commerce.ProductName(),
                        Price       = decimal.Parse(commerce.Price()),
                        Currency    = finance.Currency().Code,
                        Description = lorem.Sentences(),
                        Company     = company.CompanyName(),
                        Mail        = internet.Email(),
                        Seller      = name.FullName(),
                        Review      = rant.Review()
                    });
                }
                context.SaveChanges();
            }
        }
Beispiel #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="rantId"></param>
        /// <returns></returns>
        public async Task <Rant> GetRant(long rantId)
        {
            string url = MakeUrl(Constants.PathRants + rantId);

            var response = await client.GetAsync(url);

            var responseText = await response.Content.ReadAsStringAsync();

            JObject tmp = JObject.Parse(responseText);

            if (CheckSuccess(tmp))
            {
                Rant r = ContentObject.Parse <Rant>(tmp["rant"] as JObject);

                JArray comments = tmp["comments"] as JArray;

                List <Comment> list = new List <Comment>();

                if (comments != null)
                {
                    foreach (JObject o in comments)
                    {
                        Comment c = ContentObject.Parse <Comment>(o);
                        list.Add(c);
                    }

                    r.Comments = list;
                }

                return(r);
            }
            else
            {
                return(null);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Requests profile details to the rest-api.
        /// </summary>
        /// <param name="username">Username of the profile to request.</param>
        /// <exception cref="ArgumentException">Thrown when <paramref name="username"/> is empty.</exception>
        /// <inheritdoc />
        public async Task <Profile> GetProfileAsync(string username, ProfileContentType type = ProfileContentType.Rants, int skip = 0)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Must be non-empty.", nameof(username));
            }

            var userId = await GetUserId(username);

            if (userId == null)
            {
                return(null);
            }

            Parameters paramz = new Parameters();

            paramz.Add("content", type.ToString().ToLower());
            paramz.Add("skip", skip.ToString());

            string url      = MakeUrl($"/api/users/{userId}", paramz);
            var    response = await client.GetAsync(url);

            var responseText = await response.Content.ReadAsStringAsync();

            JObject obj     = JObject.Parse(responseText);
            Profile profile = obj["profile"].ToObject <Profile>();

            //Add Data
            JObject content = obj["profile"]["content"]["content"] as JObject;

            string sectionName = type.ToString().ToLower();

            JObject counts = obj["profile"]["content"]["counts"] as JObject;

            profile.RantsCount     = GetCount(counts, "rants");
            profile.CommentsCount  = GetCount(counts, "comments");
            profile.UpvotedCount   = GetCount(counts, "upvoted");
            profile.FavoritesCount = GetCount(counts, "favorites");
            profile.ViewedCount    = GetCount(counts, "viewed");

            //Avatar Image
            var    img = obj["profile"]["avatar"]["i"];
            string avt = img == null? null : img.ToString();

            profile.AvatarImage = avt;

            //TODO: Collab

            JArray data = content[sectionName] as JArray;

            if (data != null)
            {
                List <Rant>    rantsList    = new List <Rant>();
                List <Comment> commentsList = new List <Comment>();

                foreach (JObject i in data)
                {
                    switch (type)
                    {
                    case ProfileContentType.Rants:
                    case ProfileContentType.Favorites:
                    case ProfileContentType.Upvoted:
                    case ProfileContentType.Viewed:
                        Rant rant = DataObject.Parse <Rant>(i);
                        rantsList.Add(rant);
                        break;

                    case ProfileContentType.Comments:
                        Comment comment = DataObject.Parse <Comment>(i);
                        commentsList.Add(comment);
                        break;
                    }
                }

                profile.Rants    = rantsList;
                profile.Comments = commentsList;
            }

            return(profile);
        }
Beispiel #25
0
 public void SaveRant(Rant rant)
 {
     _readWriteRepository.Add(rant);
 }
Beispiel #26
0
 public async Task <IList <Comment> > GetComments(Rant rant)
 {
     return((await Client.GetRant(rant.Id)).Comments);
 }