Exemple #1
0
        //[Authorize(Roles = "Admin, User")]
        public RedirectToRouteResult Submit()
        {
            if (!userProvider.GetUser(this).Identity.IsAuthenticated)
            {
                return(RedirectToAction("Register", "Account", new { returnUrl = Url.Action("Submit") }));
            }

            if (WeeklyVoted(userProvider.GetUser(this).Identity.GetUserId()))
            {
                return(RedirectToAction("List"));
            }

            var             userId = userProvider.GetUser(this).Identity.GetUserId();
            ApplicationUser user   = usersRepository.Items.First(x => x.Id == userId);

            foreach (var characterId in cartProvider.GetCart(this).Votes)
            {
                var vote = new Vote {
                    User = user, Week = Week
                };
                votesRepository.Add(vote);
                votesRepository.SaveChanges();

                var character = charactersRepository.Items.First(x => x.Id == characterId);
                var voteItem  = new VoteItem
                {
                    Position = 1,
                    Vote     = vote,
                    Hero     = character
                };
                voteItemsRepository.Add(voteItem);
            }
            cartProvider.SetCart(this, new Cart(new HashSet <int>(), cartProvider.GetCart(this).Points));
            return(RedirectToAction("List"));
        }
Exemple #2
0
        public IActionResult Get()
        {
            string cc = Request.Query["id"];
            uint   id;

            try
            {
                id = uint.Parse(cc);
            }
            catch
            {
                return(BadRequest());
            }
            VoteItem res  = new VoteItem();
            DBAction injj = new DBAction();

            if (injj.GetVoteItem(id, ref res) != true || injj.getItemsInVote(id, ref res) != true)
            {
                return(BadRequest());
            }

            var json = JObject.FromObject(res);

            return(new ObjectResult(json));
        }
Exemple #3
0
        private async Task RegisterAnonVote(ContentItem contentItem, int rating)
        {
            var currentContext = _httpContextAccessor.HttpContext;
            var anonHostname   = currentContext.Connection.RemoteIpAddress.ToString();

            if (!string.IsNullOrWhiteSpace(currentContext.Request.Headers["X-Forwarded-For"]))
            {
                anonHostname += "-" + currentContext.Request.Headers["X-Forwarded-For"];
            }



            //add new vote
            var vote = new VoteItem()
            {
                User          = "******",
                CorrelationId = contentItem?.ContentItemId,
                Value         = rating,
                Dimension     = Constants.DimensionRating,
                CreatedUtc    = _clock.UtcNow,
                Hostname      = anonHostname
            };


            await _votingStore.SaveAsync(vote);


            //  _votingService.Vote(contentItem, "Anonymous", anonHostname, rating, Constants.Voting.RatingConstant);
        }
        public void TestRestrictionGrouping()
        {
            var r = new Voat.Data.Models.VoteRestriction()
            {
                ID = 1,
                //GroupName = "Default",
                Type = typeof(ContributionCountRestriction).Name,
                Data = (new ContributionCountRestriction()
                {
                    ContentType = (ContentTypeRestriction)(Domain.Models.ContentType.Comment | Domain.Models.ContentType.Submission),
                    Duration = TimeSpan.FromDays(180),
                    Subverse = "unit",
                    MinimumCount = 1,
                    EndDate = DateTime.UtcNow
                }).Serialize(),
                VoteID = 1
            };

            var constructed = (IVoteRestriction)VoteItem.Deserialize <VoteItem>(r.Data);
            var user        = TestHelper.SetPrincipal(USERNAMES.User500CCP);
            var outcome     = constructed.Evaluate(user);

            VoatAssert.IsValid(outcome);


            var restrictionSet = new VoteRestrictionSet();

            restrictionSet.Populate(new Voat.Data.Models.VoteRestriction[] { r });

            var eval = restrictionSet.Evaluate(user);

            Assert.IsTrue(eval.IsValid);
        }
Exemple #5
0
        public async Task <IWriterResult <bool> > CreateVoteItem(string userId, CreateVoteItemModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var voteItem = await context.VoteItem.FirstOrDefaultNoLockAsync(x => x.Name == model.Name);

                if (voteItem != null)
                {
                    return(WriterResult <bool> .ErrorResult("VoteItem {0} already exists.", model.Name));
                }

                voteItem = new VoteItem
                {
                    Name        = model.Name,
                    Symbol      = model.Symbol,
                    Website     = model.Website,
                    Source      = model.Source,
                    AlgoType    = model.AlgoType,
                    Created     = DateTime.UtcNow,
                    UserId      = userId,
                    Status      = VoteItemStatus.Pending,
                    Description = model.Description
                };

                context.VoteItem.Add(voteItem);

                var contextResults = await context.SaveChangesWithLoggingAsync();

                return(WriterResult <bool> .ContextResult(contextResults, "Successfully submitted coin for review"));
            }
        }
Exemple #6
0
        public IActionResult Post([FromBody] VoteItem value)
        {
            if (value == null)
            {
                return(BadRequest());
            }
            DBAction injj  = new DBAction();
            var      state = 0;

            ICache cache  = new ICache();
            UInt64 voteId = 0;

            if (cache.GetHash(value.Token, "session") != null && (voteId = injj.InsertVote(value)) > 0)
            {
                state = 1;
            }

            var data = new
            {
                State  = state,
                VoteId = voteId
            };

            var json = JObject.FromObject(data);

            return(new ObjectResult(json));
        }
Exemple #7
0
        public async Task DeleteAsync(VoteItem workflow)
        {
            await Task.Run(() =>
                           _session.Delete(workflow));

//            var context = new WorkflowDeletedContext(workflow);
//            await _handlers.InvokeAsync(async x => await x.DeletedAsync(context), _logger);
        }
Exemple #8
0
        public async Task <ActionResult <VoteItem> > Up([FromBody] VoteItem voteItem)
        {
            // TODO get current user
            voteItem.CreateDate = DateTime.Now;
            dbContext.VoteItems.Add(voteItem);
            await dbContext.SaveChangesAsync();

            return(voteItem);
        }
Exemple #9
0
        public ActionResult AjaxForm()
        {
            var model = new VoteItem();

            if (DoAction == ActionType.Edit)
            {
                model = _api.GetVoteItem(ArrId.FirstOrDefault());
            }
            ViewBag.Action   = DoAction;
            ViewBag.AgencyID = UserItem.AgencyID;
            return(View(model));
        }
Exemple #10
0
        public async Task ChangeVoteAsync(VoteItem workflow, double value)
        {
            //   var previousValue = value;

//            foreach (var function in _functions) {
//                _calculator.Calculate(new UpdateCalculus { Dimension = vote.Dimension, ContentId = vote.ContentItemRecord.Id, PreviousVote = vote.Value, Vote = value, FunctionName = function.Name });
//            }

            workflow.CreatedUtc = DateTime.Now;//    _clock.UtcNow;
            workflow.Value      = value;

            await SaveAsync(workflow);
        }
        // GET: api/Places/5
        public VoteItem Get(int id)
        {
            string SelectCmdText = String.Format("select * from places where id={0}", id);

            Myadapter = new SqlDataAdapter(SelectCmdText, ConnecttionStr);
            MyDataSet = new DataSet();
            Myadapter.Fill(MyDataSet, "places");
            VoteItem voteItem = new VoteItem();

            voteItem.id          = (int)MyDataSet.Tables["places"].Rows[0]["id"];
            voteItem.name        = (string)MyDataSet.Tables["places"].Rows[0]["name"];
            voteItem.votedNumber = (int)MyDataSet.Tables["places"].Rows[0]["votedNumber"];
            return(voteItem);
        }
        public async Task <ActionResult <string> > Like(
            VoteItem item,
            [FromServices] DaprClient daprClient)
        {
            // unique key for vote like (article and liker)
            string key = item.userid + "|" + item.articleid;

            VoteItem newItem = item;
            await daprClient.SaveStateAsync(StoreName, key, newItem);

            // publish message in topic
            await daprClient.PublishEventAsync <VoteItem>("pubsub", "likeprocess", newItem);

            return(string.Format("Vote liked key: {0}", key));
        }
        public static Domain.Models.Vote Map(this Data.Models.Vote entity)
        {
            Domain.Models.Vote vote = null;
            if (entity != null)
            {
                vote = new Domain.Models.Vote();

                vote.ID                = entity.ID;
                vote.Title             = entity.Title;
                vote.Content           = entity.Content;
                vote.FormattedContent  = entity.FormattedContent;
                vote.Subverse          = entity.Subverse;
                vote.SubmissionID      = entity.SubmissionID;
                vote.StartDate         = entity.StartDate;
                vote.DisplayStatistics = entity.DisplayStatistics;
                vote.EndDate           = entity.EndDate;
                vote.CreationDate      = entity.CreationDate;
                vote.CreatedBy         = entity.CreatedBy;

                entity.VoteOptions?.ForEach(x =>
                {
                    var newOption = new Domain.Models.VoteOption();

                    newOption.ID               = x.ID;
                    newOption.Title            = x.Title;
                    newOption.Content          = x.Content;
                    newOption.FormattedContent = x.FormattedContent;
                    newOption.SortOrder        = x.SortOrder;

                    x.VoteOutcomes?.ForEach(o =>
                    {
                        var obj = VoteItem.Deserialize <VoteOutcome>(o.Data);
                        obj.ID  = o.ID;
                        newOption.Outcomes.Add(obj);
                    });

                    vote.Options.Add(newOption);
                });

                entity.VoteRestrictions?.ForEach(x =>
                {
                    var obj = VoteItem.Deserialize <VoteRestriction>(x.Data);
                    obj.ID  = x.ID;
                    vote.Restrictions.Add(obj);
                });
            }
            return(vote);
        }
        public HttpResponseMessage GetItem(VoteItem voteItem)
        {
            VoteItem      vI         = new VoteItem();
            SqlConnection sqlConnect = new SqlConnection();

            sqlConnect.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ASUS-PC\Desktop\D-lyw\webApi-vuejs\Web-API\App_Data\webApplicationDev.mdf;Integrated Security=True";
            try
            {
                sqlConnect.Open();
                string     findSql = "select * from votelist where ItemId = '" + voteItem.ItemId + "';";
                SqlCommand findCmd = new SqlCommand(findSql, sqlConnect);

                SqlDataReader dr = findCmd.ExecuteReader();
                while (dr.Read())
                {
                    vI.ItemId   = Int32.Parse(dr[0].ToString().Trim());
                    vI.Title    = dr[1].ToString().Trim();
                    vI.Statue   = Int32.Parse(dr[2].ToString().Trim());
                    vI.Items    = new string[6];
                    vI.ItemsNum = new int[6];
                }
                sqlConnect.Close();

                sqlConnect.Open();
                SqlCommand    cmd2 = new SqlCommand("select * from itemdetails where ItemId = '" + voteItem.ItemId + "';", sqlConnect);
                SqlDataReader dr2  = cmd2.ExecuteReader();

                while (dr2.Read())
                {
                    vI.ItemCountNum = vI.ItemCountNum == 0 ? 1 : vI.ItemCountNum + 1;
                    vI.Items[vI.ItemCountNum - 1]    = dr2[2].ToString().Trim();
                    vI.ItemsNum[vI.ItemCountNum - 1] = Int32.Parse(dr2[3].ToString().Trim());
                }
                sqlConnect.Close();
                string strJson = JsonConvert.SerializeObject(vI);
                //string strJson = ObjToJson1<VoteItem>(vI);
                return(new HttpResponseMessage {
                    Content = new StringContent(strJson, System.Text.Encoding.UTF8, "application/json")
                });
            }
            catch
            {
                string msg = "err";
                return(new HttpResponseMessage {
                    Content = new StringContent(msg, System.Text.Encoding.UTF8, "application/json")
                });
            }
        }
Exemple #15
0
 public static string ObjToJson <T>(VoteItem data)
 {
     try
     {
         System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
         using (MemoryStream ms = new MemoryStream())
         {
             serializer.WriteObject(ms, data);
             return(Encoding.UTF8.GetString(ms.ToArray()));
         }
     }
     catch
     {
         return(null);
     }
 }
Exemple #16
0
        private async Task RegisterUserVote(ClaimsPrincipal user, ContentItem contentItem, int rating)
        {
            var currentVote = await GetUserVote(user, contentItem);

            //also update in content item part so part driver does not require extra queiry
            var voteUpDownPart = contentItem.As <VotingPart>();


            if (currentVote != null && (currentVote.Value + rating == 0))
            {
                voteUpDownPart.UserVote = rating;
                await _votingStore.DeleteAsync(currentVote);

                // _votingService.RemoveVote(currentVote);
            }
            else
            {
                if (currentVote != null)
                {
                    voteUpDownPart.UserVote = rating;
                    await _votingStore.ChangeVoteAsync(currentVote, rating);
                }


                else
                {
                    //add new vote
                    var vote = new VoteItem()
                    {
                        User          = User.Identity.Name,
                        CorrelationId = contentItem?.ContentItemId,
                        Value         = rating,
                        Dimension     = Constants.DimensionRating,
                        CreatedUtc    = _clock.UtcNow,
                        Hostname      = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()
                    };


                    await _votingStore.SaveAsync(vote);

                    voteUpDownPart.UserVote = rating;
                }
            }

            contentItem.Apply(voteUpDownPart);
            _session.Save(contentItem);
        }
        private List <VoteItem> GetVoteItems(List <int> charecterIds, Vote vote)
        {
            var counter = 0;
            var ans     = new List <VoteItem>();

            foreach (var chId in charecterIds)
            {
                var chr      = repository.Characters.First(x => x.Id == chId);
                var voteItem = new VoteItem
                {
                    Character = chr,
                    Position  = counter,
                    Vote      = vote
                };
                ans.Add(voteItem);
            }
            return(ans);
        }
Exemple #18
0
        public JsonResult voteItem(VoteItem tp, string action)
        {
            try
            {
                switch (action)
                {
                case "add":
                    db.VoteItem.Add(tp);

                    tp.Index = DateTime.Now.ToTimeStamp();
                    db.SaveChanges();
                    break;

                case "edit":
                    //tp = db.VoteItem.Find(tp.Id);
                    //TryUpdateModel(tp);
                    db.Entry(tp).State = EntityState.Modified;
                    db.SaveChanges();
                    break;

                case "del":
                    tp = db.VoteItem.Find(tp.Id);
                    db.VoteItem.Remove(tp);
                    db.SaveChanges();
                    break;

                case "get":
                    tp = db.VoteItem.Single(d => d.Id == tp.Id);
                    break;

                case "totop":
                    db.VoteItem.Find(tp.Id).Index = DateTime.Now.ToTimeStamp();
                    db.SaveChanges();
                    break;
                }
                db.Configuration.LazyLoadingEnabled = false;
                return(myJson.success(tp));
            }
            catch (Exception e)
            {
                return(myJson.error(e.Message));
            }
        }
        public async Task <ActionResult> LikeProcess(VoteItem vote, [FromServices] DaprClient daprClient)
        {
            Console.WriteLine("Enter LikeProcess for article {0}", vote.articleid);

            // getting etag to avoid concurrent writes (https://github.com/dapr/dotnet-sdk/pull/498/files)
            var(state, etag) = await daprClient.GetStateAndETagAsync <ArticleItem>(StoreName, vote.articleid);

            state ??= new ArticleItem()
            {
                articleid = vote.articleid, voteCount = 0
            };

            state.voteCount++;
            Console.WriteLine("Article {0} voteCount increased to: {1} etag {2}", vote.articleid, state.voteCount, etag);

            try {
                var options = new StateOptions()
                {
                    Concurrency = ConcurrencyMode.FirstWrite
                };
                bool isSaveStateSuccess = await daprClient.TrySaveStateAsync <ArticleItem>(StoreName, vote.articleid, state, etag);

                if (isSaveStateSuccess)
                {
                    Console.WriteLine("Article {0} voteCount saved.", vote.articleid);
                }
                else
                {
                    Console.WriteLine("Article {0} voteCount NOT saved, error eTag {1}.", vote.articleid, isSaveStateSuccess);
                    throw new Exception("Wrong eTag - version has changed !");
                    // TODO: retry to get etag and update it again
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Article {0} voteCount ERROR {1}.", vote.articleid, ex.Message);
                return(BadRequest());
            }

            Console.WriteLine("Finished LikeProcess for article {0}", vote.articleid);
            return(Ok());
        }
        // POST: api/Places
        public VoteItem Post([FromBody] VoteItem place)
        {
            string SelectCmdText = "select * from places";

            Myadapter = new SqlDataAdapter(SelectCmdText, ConnecttionStr);
            MyDataSet = new DataSet();
            Myadapter.Fill(MyDataSet, "places");

            place.id = MyDataSet.Tables["places"].Rows.Count + 1;
            DataRow NewRow = MyDataSet.Tables["places"].NewRow();

            NewRow["id"]          = place.id;
            NewRow["name"]        = place.name;
            NewRow["votedNumber"] = place.votedNumber;
            MyDataSet.Tables["places"].Rows.Add(NewRow);

            SqlCommandBuilder Builder = new SqlCommandBuilder(Myadapter);

            Myadapter.Update(MyDataSet, "places");
            return(place);
        }
Exemple #21
0
        public async Task SaveAsync(VoteItem workflow)
        {
            //  await Task.Run(()=>   null) ;

            //  var isNew = workflow.Id == 0;
            await Task.Run(() =>
                           _session.Save(workflow));



//            if (isNew)
//            {
//                var context = new WorkflowCreatedContext(workflow);
//                await _handlers.InvokeAsync(async x => await x.CreatedAsync(context), _logger);
//            }
//            else
//            {
//                var context = new WorkflowUpdatedContext(workflow);
//                await _handlers.InvokeAsync(async x => await x.UpdatedAsync(context), _logger);
//            }
        }
        public void Populate(IEnumerable <Data.Models.VoteRestriction> restrictions)
        {
            //throw new NotImplementedException();
            foreach (var restriction in restrictions)
            {
                var item = VoteItem.Deserialize <VoteRestriction>(restriction.Data);

                var groupName = String.IsNullOrEmpty(item.Group.TrimSafe()) ? "" : item.Group.TrimSafe();

                List <IVoteRestriction> groupList = null;
                if (_restrictionSet.ContainsKey(groupName))
                {
                    groupList = _restrictionSet[groupName];
                }
                else
                {
                    groupList = new List <IVoteRestriction>();
                    _restrictionSet[groupName] = groupList;
                }
                groupList.Add(item);
            }
        }
Exemple #23
0
        public void Add(Vote vote, HashSet <int> charactersIds)
        {
            context.Votes.Add(vote);

            var position = 0;

            foreach (var id in charactersIds)
            {
                var character = context.Characters.FirstOrDefault(i => i.Id == id);
                var voteItem  = new VoteItem()
                {
                    Character = character,
                    Position  = position,
                    Vote      = vote
                };
                context.Entry(character).State = EntityState.Unchanged;
                context.VoteItems.Add(voteItem);
                position++;
            }

            context.SaveChangesAsync();
        }
Exemple #24
0
        public HttpResponseMessage UpdateVote(VoteItem voteItem)
        {
            SqlConnection sqlConnect = new SqlConnection();

            sqlConnect.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ASUS-PC\Desktop\D-lyw\webApi-vuejs\Web-API\App_Data\webApplicationDev.mdf;Integrated Security=True";
            try
            {
                sqlConnect.Open();
                SqlCommand updateVote = new SqlCommand("update votelist set Statue = '" + voteItem.Statue + "' where ItemId = '" + voteItem.ItemId + "'", sqlConnect);
                int        line       = updateVote.ExecuteNonQuery();
                return(new HttpResponseMessage {
                    Content = new StringContent(line.ToString(), System.Text.Encoding.UTF8, "application/json")
                });
            }
            catch
            {
                int line = 0;
                return(new HttpResponseMessage {
                    Content = new StringContent(line.ToString(), System.Text.Encoding.UTF8, "application/json")
                });
            }
        }
Exemple #25
0
        public IActionResult Put([FromBody] VoteItem value)
        {
            if (value == null)
            {
                return(BadRequest());
            }
            DBAction injj  = new DBAction();
            var      state = 0;

            ICache cache = new ICache();

            if (cache.GetHash(value.Token, "session") == value.UserBelong.ToString() && injj.CheckVoteBelongToUser(value.UserBelong, value.VoteId) && injj.UpdateVoteItem(value))
            {
                state = 1;
            }
            var data = new {
                State = state
            };
            var json = JObject.FromObject(data);

            return(new ObjectResult(json));
        }
        public IActionResult Post([FromBody] VoteItem value)
        {
            if (value == null)
            {
                return(BadRequest());
            }
            DBAction injj  = new DBAction();
            ICache   cache = new ICache();

            string userId;
            var    state = 0;

            if ((userId = cache.GetHash(value.Token, "session")) == null)
            {
                return(BadRequest());
            }
            try
            {
                if (injj.CheckVoteBelongToUser(uint.Parse(userId), value.VoteId) && injj.DeleteVote(value.VoteId))
                {
                    state = 1;
                }
            }
            catch
            {
                return(BadRequest());
            }


            var data = new
            {
                State = state,
            };

            var json = JObject.FromObject(data);

            return(new ObjectResult(json));
        }
        // PUT: api/Places
        public HttpResponseMessage Put([FromBody] VoteItem place)
        {
            string SelectCmdText = String.Format("select * from places where id={0}", place.id);

            Myadapter = new SqlDataAdapter(SelectCmdText, ConnecttionStr);
            MyDataSet = new DataSet();
            Myadapter.Fill(MyDataSet, "places");

            MyDataSet.Tables["places"].Rows[0]["id"]          = place.id;
            MyDataSet.Tables["places"].Rows[0]["name"]        = place.name;
            MyDataSet.Tables["places"].Rows[0]["votedNumber"] = place.votedNumber;

            SqlCommandBuilder Builder = new SqlCommandBuilder(Myadapter);
            int changedRows           = Myadapter.Update(MyDataSet, "places");

            if (changedRows >= 1)
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
Exemple #28
0
        public ActionResult ItemAdd(VoteItemModel voteItem)
        {
            var voteProject = GetVoteProject(Convert.ToInt32(voteItem.PId));

            if (voteProject.BeginTime < DateTime.Now)
            {
                ViewBag.Message = "Sorry, this project has began to vote, cannot add item.";
                ViewBag.users = db.Users.Where(u => u.UserName != null && u.UserName.Length > 0).OrderBy(i => i.UserName).ToList();
                return View(voteItem);
            }

            if (voteItem != null)
            {
                if (!ValidateItemName(voteItem.Name, voteItem.PId, voteItem.Id))
                {
                    ViewBag.Message = "Sorry, this item name has been used in this project.";
                    ViewBag.users = db.Users.Where(u => u.UserName != null && u.UserName.Length > 0).OrderBy(i => i.UserName).ToList();
                    return View(voteItem);
                }

                var userId = User.Identity.Name.Split(',')[0];
                var voteItemDB = new VoteItem
                {
                    PId = voteItem.PId,
                    Comment = voteItem.Comment,
                    CreatedBy = userId,
                    CreatedTime = DateTime.Now,
                    Name = voteItem.Name,
                    Nominator = userId,
                    Nominees = voteItem.Members,
                    State = 0
                };

                try
                {
                    db.VoteItems.Add(voteItemDB);
                    db.SaveChanges();

                    return RedirectToAction("ItemList", new { id = voteItem.PId });
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "DatabaseError: "+ex.Message;
                    ViewBag.users = db.Users.Where(u => u.UserName != null && u.UserName.Length > 0).OrderBy(i => i.UserName).ToList();
                    return View(voteItem);
                    //return View("DatabaseError");
                    //throw;
                }
            }
            else
            {
                ViewBag.Message = "VoteItemModel is null.";
                ViewBag.users = db.Users.Where(u => u.UserName != null && u.UserName.Length > 0).OrderBy(i => i.UserName).ToList();
                return View(voteItem);
                //return View("Error");
            }
        }
        public async Task <IActionResult> ApplyFollowAction(string contentItemId, string returnUrl)
        {
            var targetContentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Published);

            if (targetContentItem == null)// || !contentItem.Has(nameof(FollowActionPart))  )
            {
                // return NotFound();
                return(Redirect(returnUrl));
            }

            if (User == null)
            {
                //  return NotFound();
                return(Redirect(returnUrl));
            }


            var currentVote = (await _votingStore.GetAsync(vote =>
                                                           vote.User == User.Identity.Name &&
                                                           vote.CorrelationId == targetContentItem.ContentItemId &&
                                                           vote.Dimension == Constants.DimensionFollow)).FirstOrDefault();

            //also update in content item part so part driver does not require extra queiry
            var followingPart = targetContentItem.As <FollowPart>();

            if (followingPart == null)
            {
                var newPart = targetContentItem.Weld(new FollowPart()
                {
                    IsFollowing = false
                });
                targetContentItem.Apply(newPart);
            }
            var actualFollowingPart = targetContentItem.As <FollowPart>();

            string successMessage;

            if (currentVote != null)
            {
                //already following . so unfollow



                await _votingStore.DeleteAsync(currentVote);

                actualFollowingPart.IsFollowing = false;

                successMessage = "Removed from Following.";
            }
            else
            {
                //add new vote
                var vote = new VoteItem
                {
                    User          = User.Identity.Name,
                    CorrelationId = targetContentItem?.ContentItemId,
                    Value         = 1,
                    Dimension     = Constants.DimensionFollow,
                    CreatedUtc    = _clock.UtcNow,
                    Hostname      = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()
                };


                await _votingStore.SaveAsync(vote);

                actualFollowingPart.IsFollowing = true;
                successMessage = "Added to Following.";

                //favoritePart.IsFavorite = true;
                //  _votingStore.Vote(content, currentUser.UserName, _httpContextAccessor.Current().Request.UserHostAddress, 1, Constants.Dimension);
            }

            targetContentItem.Apply(actualFollowingPart);
            _session.Save(targetContentItem);
            _notifier.Success(T[successMessage]);

            //log notification
            await _notificationEventHandlers.InvokeAsync(eventdata => eventdata.LogNotificationAsync(
                                                             "Follow",
                                                             User.Identity.Name,
                                                             targetContentItem?.ContentItemId,
                                                             "Followed by user",
                                                             $"{User.Identity.Name} followed you"),
                                                         Logger);

            //send realtime notification to receiver
            //push notification to follower about number of his/her FollowerNotification.
            await _pushNotificationService.RefreshUserFollowersNotification(targetContentItem?.ContentItemId);

            if (returnUrl == null)
            {
                // return RedirectToAction("Edit", new RouteValueDictionary { { "ContentItemId", contentItem.ContentItemId } });
                return(LocalRedirect("/"));
            }
//           else if (stayOnSamePage)
//           {
//               return RedirectToAction("Edit", new RouteValueDictionary { { "ContentItemId", contentItem.ContentItemId }, { "returnUrl", returnUrl } });
//           }

            return(LocalRedirect(returnUrl));
        }
Exemple #30
0
        public HttpResponseMessage AddVoteItem(VoteItem voteItem)
        {
            string        retMsg;
            SqlConnection sqlConnect = new SqlConnection();

            sqlConnect.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ASUS-PC\Desktop\D-lyw\webApi-vuejs\Web-API\App_Data\webApplicationDev.mdf;Integrated Security=True";
            try
            {
                sqlConnect.Open();
                //string sql = @"INSERT into votelist (title, Statue, Username, StopTime) values (@title, @Statue, @Username, @StopTime); select @ItemId=@@IDENTITY;";

                /*SqlParameter[] para = {
                 *  new SqlParameter("@title", SqlDbType.NVarChar, 50),
                 *  new SqlParameter("@Statue", SqlDbType.Int),
                 *  new SqlParameter("@Username", SqlDbType.NVarChar, 50),
                 *  new SqlParameter("@StopTime", SqlDbType.NVarChar, 50),
                 *  new SqlParameter("@ItemId", SqlDbType.Int)
                 *
                 * para[0].Value = voteItem.Title;
                 * para[1].Value = voteItem.Statue;
                 * para[2].Value = voteItem.UserName;
                 * para[3].Value = voteItem.StopTime;
                 * para[4].Direction = ParameterDirection.Output;
                 * DbHelperSQL
                 * DBHelper.ExecuteNonData(sql, para);
                 * };*/
                string addcmd = "INSERT into votelist (title, Statue, Username, StopTime) values (N'" + voteItem.Title + "','" + voteItem.Statue + "',N'" + voteItem.UserName + "','" + voteItem.StopTime + "') ";

                //string getId = "select @@IDENTITY";
                //SqlCommand cmdId = new SqlCommand(getId, sqlConnect);
                SqlCommand cmdAdd = new SqlCommand(addcmd, sqlConnect);
                int        line;
                line = cmdAdd.ExecuteNonQuery();
                //int id = (Int32)cmdId.ExecuteScalar();
                if (line == 1)
                {
                    string     itemid = "select max(ItemId) from votelist;";
                    SqlCommand getId  = new SqlCommand(itemid, sqlConnect);
                    int        id     = (Int32)getId.ExecuteScalar();

                    string insertStr = "";
                    for (int i = 0; i < voteItem.ItemsNum.Length; i++)
                    {
                        insertStr += "insert into itemdetails(ItemId, ItemName, ItemNameNum) values ('" + id + "',N'" + voteItem.Items[i] + "','" + voteItem.ItemsNum[i] + "');";
                    }

                    SqlCommand insertDetail = new SqlCommand(insertStr, sqlConnect);
                    int        result       = insertDetail.ExecuteNonQuery();
                    retMsg = result.ToString();
                    return(new HttpResponseMessage {
                        Content = new StringContent(retMsg, System.Text.Encoding.UTF8, "application/json")
                    });
                }
                else
                {
                    retMsg = "false";
                    return(new HttpResponseMessage {
                        Content = new StringContent(retMsg, System.Text.Encoding.UTF8, "application/json")
                    });
                }
            }
            catch
            {
                retMsg = "server error";
                return(new HttpResponseMessage {
                    Content = new StringContent(retMsg, System.Text.Encoding.UTF8, "application/json")
                });
            }
            finally
            {
                sqlConnect.Close();
            }


            //return new HttpResponseMessage { Content = new StringContent(strJson, System.Text.Encoding.UTF8, "application/json") };
        }
Exemple #31
0
        public async Task <IActionResult> ApplyFollowAction(string contentItemId, string returnUrl)
        {
            var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Published);

            if (contentItem == null || !contentItem.Has("FavoritePart"))
            {
                // return NotFound();
                return(Redirect(returnUrl));
            }

            if (User == null)
            {
                //  return NotFound();
                return(Redirect(returnUrl));
            }


            var currentVote = (await _votingStore.GetAsync(vote =>
                                                           vote.User == User.Identity.Name &&
                                                           vote.CorrelationId == contentItem.ContentItemId &&
                                                           vote.Dimension == "Favorite")).FirstOrDefault();

            string sucessMessage = string.Empty;

            if (currentVote != null)
            {
                //already following . so unfollow
                //  favoritePart.IsFavorite = false;
                await _votingStore.DeleteAsync(currentVote);

                sucessMessage = "Removed from Following.";
            }
            else
            {
                //add new vote
                var vote = new VoteItem()
                {
                    User          = User.Identity.Name,
                    CorrelationId = contentItem?.ContentItemId,
                    Value         = 1,
                    Dimension     = "Favorite",
                    CreatedUtc    = _clock.UtcNow,
                    Hostname      = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()
                };


                await _votingStore.SaveAsync(vote);

                sucessMessage = "Added to Following.";

                //favoritePart.IsFavorite = true;
                //  _votingStore.Vote(content, currentUser.UserName, _httpContextAccessor.Current().Request.UserHostAddress, 1, Constants.Dimension);
            }

            _session.Save(contentItem);
            _notifier.Success(T[sucessMessage]);

            if (returnUrl == null)
            {
                // return RedirectToAction("Edit", new RouteValueDictionary { { "ContentItemId", contentItem.ContentItemId } });
                return(LocalRedirect("/"));
            }
//           else if (stayOnSamePage)
//           {
//               return RedirectToAction("Edit", new RouteValueDictionary { { "ContentItemId", contentItem.ContentItemId }, { "returnUrl", returnUrl } });
//           }
            else
            {
                return(LocalRedirect(returnUrl));
            }
        }