예제 #1
0
        public ActionResult Create([Bind(Include = "Id,UserId,Title,Description,CreatedAt,Like")] Question question, int[] TagsId)
        {
            question.Id        = db.Questions.ToList().Count() + 1;
            question.UserId    = User.Identity.GetUserId();
            question.UserName  = User.Identity.GetUserName();
            question.CreatedAt = DateTime.Now;

            if (TagsId != null)
            {
                foreach (var tagItemId in TagsId)
                {
                    QuestionTag questionTag = new QuestionTag
                    {
                        Id         = db.QuestionTags.ToList().Count() + 1,
                        QuestionId = question.Id,
                        TagId      = tagItemId
                    };
                    db.QuestionTags.Add(questionTag);
                }
            }
            if (ModelState.IsValid)
            {
                db.Questions.Add(question);
                db.SaveChanges();
                ViewBag.Tags = new MultiSelectList(db.Tags.ToList().OrderBy(t => t.Description), "TagsId", "Description");
                return(RedirectToAction("Index"));
            }

            return(View(question));
        }
예제 #2
0
        public PartialViewResult SendTag(Guid id, string tagName)
        {
            var question = db.Questions.SingleOrDefault(x => x.Id == id);

            if (question != null)
            {
                // Gibt es den Tag schon bei dieser Frage?
                var tagExists = question.Tags.Any(x => x.Name.ToLower().Equals(tagName.ToLower()));

                if (!tagExists)
                {
                    // gibt es den Tag generell schon?
                    var tag = db.QuestionTags.FirstOrDefault(x => x.Name.ToLower().Equals(tagName.ToLower()));

                    if (tag == null)
                    {
                        tag      = new QuestionTag();
                        tag.Name = tagName;
                        db.QuestionTags.Add(tag);
                        db.SaveChanges();
                    }

                    question.Tags.Add(tag);
                    // braucht es nur einmal, oder? testen
                    db.SaveChanges();
                }
            }

            return(PartialView("_TagList", question));
        }
예제 #3
0
        public QuestionTag Save(QuestionTag questionTag)
        {
            var questionTagsList = mongoDatabase.GetCollection("QuestionTags");
            WriteConcernResult result;
            bool hasError = false;

            if (string.IsNullOrEmpty(questionTag._Id))
            {
                questionTag._Id = ObjectId.GenerateNewId().ToString();
                result          = questionTagsList.Insert <QuestionTag>(questionTag);
                hasError        = result.HasLastErrorMessage;
            }
            else
            {
                IMongoQuery  query  = Query.EQ("_id", questionTag._Id);
                IMongoUpdate update = Update
                                      .Set("Tag", questionTag.Tag.TagName);
                result   = questionTagsList.Update(query, update);
                hasError = result.HasLastErrorMessage;
            }
            if (!hasError)
            {
                return(questionTag);
            }
            else
            {
                throw new Exception("");
            }
        }
예제 #4
0
        public Response AddQuestionTags(List <Guid> tagIds, Guid questionId)
        {
            Response response = new Response();

            try
            {
                using (var db = new KalingaHubDBModel())
                {
                    foreach (var tagId in tagIds)
                    {
                        QuestionTag questionTag = new QuestionTag {
                            QuestionId = questionId, TagId = tagId
                        };
                        db.QuestionTags.Add(questionTag);
                    }
                    db.SaveChanges();
                    response.IsSuccess = true;
                }
            }
            catch (Exception e)
            {
                response.IsSuccess = false;
                response.Message   = e.Message;
                return(response);
            }
            return(response);
        }
예제 #5
0
        public async Task <IActionResult> AddTag([FromRoute] int id, [FromRoute] string tagName)
        {
            var question = await _context.Questions.Include(q => q.Author).SingleOrDefaultAsync(m => m.QuestionId == id);

            if (question == null)
            {
                return(NotFound());
            }

            var tag = await _context.Tags.SingleOrDefaultAsync(m => m.Name == tagName);

            if (tag == null)
            {
                tag = new Tag()
                {
                    Name = tagName
                };
                _context.Tags.Add(tag);
                await _context.SaveChangesAsync(); // need to save now to get an ID
            }

            var questionTag = new QuestionTag()
            {
                Question = question, Tag = tag
            };

            _context.Add(questionTag);

            await _context.SaveChangesAsync();

            return(Ok());
        }
        public List <Models.QuestionTag> TopTags()
        {
            List <Models.QuestionTag> a     = new List <QuestionTag>();
            List <Question>           qList = context.Questions.ToList();

            foreach (var item in qList)
            {
                List <TagQuestion> qTags = context.TagQuestions.Where(x => x.QuestionId == item.QuestionId).ToList();

                foreach (var tq in qTags)
                {
                    if (a.Any(x => x.TagId == tq.TagId))
                    {
                        a.FirstOrDefault(x => x.TagId == tq.TagId).Appearance += 1;
                    }
                    else
                    {
                        Models.QuestionTag qtag = new QuestionTag
                        {
                            TagId          = tq.TagId,
                            TagDescription = context.TagMasters.FirstOrDefault(x => x.TagId == tq.TagId).TagDescription,
                            Appearance     = 1
                        };

                        a.Add(qtag);
                    }
                }
            }


            a = a.OrderByDescending(x => x.Appearance).Take(5).ToList();

            return(a);
        }
예제 #7
0
        public async Task DetachTag(QuestionTag questionTag)
        {
            var questionTagToDelete = await _dbContext.QuestionTags.Where(t => t.TagId == questionTag.TagId && t.QuestionId == questionTag.QuestionId).FirstOrDefaultAsync();

            _dbContext.QuestionTags.Remove(questionTagToDelete);
            await _dbContext.SaveChangesAsync();
        }
예제 #8
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await GetCurrentUser();

            user.Points += 5;
            Tag         tag = _context.Tags.First(t => t.Id == TagId);
            QuestionTag qt  = new QuestionTag {
                QuestionId = Question.Id,
                Question   = Question,
                TagId      = tag.Id,
                Tag        = tag
            };

            Question.QuestionTags.Add(qt);
            user.Questions.Add(Question);

            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            QuestionTag questionTag = db.QuestionTags.Find(id);

            db.QuestionTags.Remove(questionTag);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #10
0
        public async Task <IActionResult> AddQuestionTag(int projectId, int questionId, string tagText)
        {
            if (string.IsNullOrEmpty(tagText))
            {
                return(Json(new Result {
                    Message = "Parameter tagText"
                }));
            }

            var project = _applicationContext.Projects
                          .FirstOrDefault(p => p.Id == projectId);

            if (project == null)
            {
                return(Json(new Result {
                    Message = "Parameter projectId"
                }));
            }

            var question = _applicationContext.Questions
                           .Include(q => q.QuestionTags)
                           .ThenInclude(qt => qt.Tag)
                           .FirstOrDefault(q => q.Id == questionId);

            if (question == null)
            {
                return(Json(new Result {
                    Message = "Parameter questionId"
                }));
            }

            if (question.QuestionTags.FirstOrDefault(qt => qt.Tag.Text == tagText) != null)
            {
                return(Json(new Result {
                    Message = "Такой тэг уже привязан к этому вопросу!"
                }));
            }

            var newTag = new Tag
            {
                Text = tagText
            };

            var newQuestionTag = new QuestionTag
            {
                Question = question,
                Tag      = newTag
            };

            question.QuestionTags.Add(newQuestionTag);
            await _applicationContext.SaveChangesAsync();

            return(Json(new Result {
                Success = true
            }));
        }
예제 #11
0
        public ActionResult AssignTagConfirm(int?Id, int?TagId)
        {
            var         question = db.Questions.Find(Id);
            var         tag      = db.Tags.Find(TagId);
            QuestionTag qt       = new QuestionTag();

            qt.TagId      = tag.Id;
            qt.QuestionId = question.Id;
            db.QuestionTags.Add(qt);
            db.SaveChanges();
            return(RedirectToAction("AssignTag", new { questionId = question.Id }));
        }
예제 #12
0
 public ActionResult Edit([Bind(Include = "Id,QuestionId,TagId")] QuestionTag questionTag)
 {
     if (ModelState.IsValid)
     {
         db.Entry(questionTag).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.QuestionId = new SelectList(db.Questions, "Id", "Title", questionTag.QuestionId);
     ViewBag.TagId      = new SelectList(db.Tags, "Id", "Description", questionTag.TagId);
     return(View(questionTag));
 }
예제 #13
0
        public async Task <IActionResult> Create(AdminQuestionViewModel model)
        {
            if (ModelState.IsValid)
            {
                var question = new Question();

                question.Title     = model.Title;
                question.Content   = model.Content;
                question.IsVisible = model.IsVisible;

                question.Author = await _userManager.GetUserAsync(User);

                question.PublicationDate = DateTime.Now;
                question.Tags            = new List <QuestionTag>();


                // Add tags
                if (!string.IsNullOrEmpty(model.Tags))
                {
                    var tags = model.Tags.Split(',', StringSplitOptions.RemoveEmptyEntries);

                    if (tags.Any())
                    {
                        foreach (var tag in tags)
                        {
                            var dbTag = _context.Tags.FirstOrDefault(t => t.Name.ToLower() == tag.ToLower());
                            if (dbTag == null)
                            {
                                // Tag does not exist, create it
                                dbTag      = new Tag();
                                dbTag.Name = tag;
                                _context.Tags.Add(dbTag);
                            }

                            var questionTag = new QuestionTag();
                            questionTag.Question = question;
                            questionTag.Tag      = dbTag;

                            question.Tags.Add(questionTag);
                        }
                    }
                }

                _context.Add(question);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(model));
        }
예제 #14
0
        public void SaveTest()
        {
            var questionTag = new QuestionTag
            {
                Tag = new Tag {
                    TagName = "MongoDB"
                }
            };

            var data = repository.Save(questionTag);

            //Xunit.Assert.NotNull(data);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(data);
        }
예제 #15
0
        // GET: QuestionTags/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            QuestionTag questionTag = db.QuestionTags.Find(id);

            if (questionTag == null)
            {
                return(HttpNotFound());
            }
            return(View(questionTag));
        }
예제 #16
0
        private void InsertTag(string[] ary2, int lastQuesId)
        {
            foreach (var str in ary2)
            {
                Tag         tag = _repoTag.GetByName(str);
                QuestionTag qt  = new QuestionTag();
                if (qt != null)
                {
                    qt.QuestionId = lastQuesId;
                    qt.TagId      = tag.TagId;

                    _repoQuesTag.Insert(qt);
                }
            }
        }
예제 #17
0
        // GET: QuestionTags/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            QuestionTag questionTag = db.QuestionTags.Find(id);

            if (questionTag == null)
            {
                return(HttpNotFound());
            }
            ViewBag.QuestionId = new SelectList(db.Questions, "Id", "Title", questionTag.QuestionId);
            ViewBag.TagId      = new SelectList(db.Tags, "Id", "Description", questionTag.TagId);
            return(View(questionTag));
        }
예제 #18
0
        public ActionResult Edit(long id, string title, FormCollection frmCol)
        {
            bool sor = true;

            ValidateQuestion(frmCol, ref sor);
            TagValidControl(frmCol, ref sor);


            Question ques = _repoQues.GetById(id);

            if (!sor)
            {
                return(View("Sor", FrmView.Data.WithQuestion(ques)));
            }
            ques.Detail = frmCol["Question.Detail"].Replace("'", "%t%").Replace("@", "@@");
            ques.Title  = frmCol["Question.Title"].Replace("'", "%t%").Replace("@", "@@");
            _repoQues.Update(ques);
            var NewAry = frmCol["tags"].Split(',');

            string[] OldAry = _repoQuesTag.ListByQuestionId(ques.QuestionId).Select(x => x.TagName).ToArray();
            foreach (var str in NewAry)
            {
                if (!OldAry.Contains(str))
                {
                    Tag         tag = _repoTag.GetByName(str);
                    QuestionTag qt  = new QuestionTag();
                    qt.TagId      = tag.TagId;
                    qt.QuestionId = ques.QuestionId;
                    _repoQuesTag.Insert(qt);
                }
            }
            foreach (var str in OldAry)
            {
                if (!NewAry.Contains(str))
                {
                    Tag tag = _repoTag.GetByName(str);
                    _repoQuesTag.Delete(ques.QuestionId, tag.TagId);
                }
            }
            return(RedirectToAction("Detay", "Soru", new { id = ques.QuestionId, title = ques.Title.ConvertWebUrl() }));
        }
예제 #19
0
        // GET: TagsController/AttachQuestionTag
        public async Task <IActionResult> AttachQuestionTag(int tagId, int questionId)
        {
            try
            {
                var question = await _repository.GetQuestionByIdWithoutDetailsAsync(questionId);

                if (question == null)
                {
                    Response.StatusCode      = 404;
                    ViewData["ErrorMessage"] = "404 Resource not found.";
                    return(View("Error"));
                }
                var tag = await _repository.GetTagByIdAsync(tagId);

                if (tag == null)
                {
                    Response.StatusCode      = 404;
                    ViewData["ErrorMessage"] = "404 Resource not found.";
                    return(View("Error"));
                }
                QuestionTag newQuestionTag = new QuestionTag
                {
                    QuestionId = questionId,
                    TagId      = tagId
                };
                await _repository.AttachQuestionTagAsync(newQuestionTag);

                return(RedirectToAction("Details", "Questions", new { questionId = questionId }));
            }
            catch (DbUpdateException dbex)
            {
                ViewData["ErrorMessage"] = "DB issue - " + dbex.Message;
                return(View("Error"));
            }
            catch (Exception ex)
            {
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Error"));
            }
        }
예제 #20
0
 public void Add(QuestionTag obj)
 {
     _repository.Add(obj);
 }
예제 #21
0
        public JsonResult Create(string value)
        {
            AddQuestionModel myObject = JsonConvert.DeserializeObject <AddQuestionModel>(value);

            if (myObject == null)
            {
                return(Json(new { status = "error" }));
            }
            var         temp            = "here";
            int         questionType    = myObject.selectedQType;
            AddQuestion qObj            = myObject.qObj;
            var         mcList          = myObject.mcList;
            var         selectedTagList = myObject.selectedTagList;
            //dynamic myObject = JArray.Parse(value);
            Question question;

            try
            {
                var userId = userManager.GetUserId(User);
                //a String question

                question                = new Question();
                question.UserId         = userId;
                question.QuestionValue  = qObj.qText;
                question.QuestionAnswer = qObj.qAns;
                question.QuestionType   = questionType;
                trivialGameContext.Add(question);
                trivialGameContext.SaveChanges();

                //a Multiple Choice Question
                if (questionType == 3)
                {
                    foreach (var mc in mcList)
                    {
                        QuestionMcanswer questionMcanswer = new QuestionMcanswer();
                        questionMcanswer.QuestionId = question.Id;
                        questionMcanswer.Options    = mc.value;
                        questionMcanswer.Correct    = mc.answer == true ? 1 : 0;
                        questionMcanswer.Question   = question;
                        trivialGameContext.Add(questionMcanswer);
                        trivialGameContext.SaveChanges();
                    }
                }

                //add tag relate to this question
                if (selectedTagList != null)
                {
                    foreach (var mc in selectedTagList)
                    {
                        QuestionTag questionTag = new QuestionTag();
                        questionTag.QuestionId = question.Id;
                        questionTag.TagId      = mc.value;
                        trivialGameContext.Add(questionTag);
                        trivialGameContext.SaveChanges();
                    }
                }

                return(Json(new { status = "success" }));
            }
            catch (Exception e)
            {
                return(Json(new { status = "error" }));
            }
        }
예제 #22
0
        public ActionResult Create([Bind(Include = "Id,category,postedBy,time,title,description")] Question question)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (ModelState.IsValid)
                {
                    question.time     = DateTime.UtcNow;
                    question.postedBy = User.Identity.GetUserId();
                    db.Questions.Add(question);

                    string s = Request["tags"];
                    s = s.Trim();
                    string[]       values = s.Split(',');
                    Tag []         tags   = new Tag[values.Length];
                    QuestionTag [] qt     = new QuestionTag[values.Length];
                    //int count = 0;
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = values[i].Trim();
                        string ss = values[i];
                        if (ss != "")
                        {
                            var data = db.Tags.FirstOrDefault(x => x.name.Equals(ss, StringComparison.OrdinalIgnoreCase));

                            tags[i] = new Tag();
                            if (data != null)
                            {
                                tags[i].Id = data.Id;
                            }
                            else
                            {
                                tags[i].name      = values[i];
                                tags[i].time      = DateTime.UtcNow;
                                tags[i].createdBy = User.Identity.GetUserId();
                                db.Tags.Add(tags[i]);
                            }
                        }
                        else
                        {
                            tags[i] = null;
                        }
                    }


                    db.SaveChanges();

                    for (int i = 0; i < values.Length; i++)
                    {
                        qt[i]            = new QuestionTag();
                        qt[i].questionId = question.Id;
                        qt[i].tagId      = tags[i].Id;
                        db.QuestionTags.Add(qt[i]);
                    }

                    db.SaveChanges();
                    return(RedirectToAction("Details", new { id = question.Id, title = ElectronicsController.URLFriendly(question.title) }));
                }

                ViewBag.postedBy = new SelectList(db.AspNetUsers, "Id", "Email", question.postedBy);
                return(View(question));
            }
            return(View(question));
        }
예제 #23
0
        public void SaveQuestionTags(string s, Question q, bool update = false)
        {
            if (update)
            {
                var adid   = q.Id;
                var adtags = db.QuestionTags.Where(x => x.questionId.Equals(adid)).ToList();
                foreach (var cc in adtags)
                {
                    db.QuestionTags.Remove(cc);
                }
                db.SaveChanges();
            }
            string[] values = s.Split(',');
            Inspinia_MVC5_SeedProject.Models.Tag[] tags = new Inspinia_MVC5_SeedProject.Models.Tag[values.Length];
            QuestionTag[] qt = new  QuestionTag[values.Length];
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = values[i].Trim();
                string ss = values[i];
                if (ss != "")
                {
                    var data = db.Tags.FirstOrDefault(x => x.name.Equals(ss, StringComparison.OrdinalIgnoreCase));

                    tags[i] = new Inspinia_MVC5_SeedProject.Models.Tag();
                    if (data != null)
                    {
                        tags[i].Id = data.Id;
                    }
                    else
                    {
                        tags[i].name      = values[i];
                        tags[i].time      = DateTime.UtcNow;
                        tags[i].createdBy = System.Web.HttpContext.Current.User.Identity.GetUserId();
                        db.Tags.Add(tags[i]);
                    }
                }
                else
                {
                    tags[i] = null;
                }
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                string sb = e.ToString();
            }
            for (int i = 0; i < values.Length; i++)
            {
                if (tags[i] != null)
                {
                    qt[i]            = new  QuestionTag();
                    qt[i].questionId = q.Id;
                    qt[i].tagId      = tags[i].Id;
                    db.QuestionTags.Add(qt[i]);
                }
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                string sb = e.ToString();
            }
        }
예제 #24
0
        public async Task AttachQuestionTagAsync(QuestionTag questionTag)
        {
            await _dbContext.QuestionTags.AddAsync(questionTag);

            await _dbContext.SaveChangesAsync();
        }
예제 #25
0
 public FrmViewData WithQuestionTag(QuestionTag item)
 {
     this.QuestionTag = item;
     return(this);
 }
예제 #26
0
        public async Task <IActionResult> Edit(int id, QuestionCreateViewModel model)
        {
            if (id != model.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var DBQuestion = await _context.Questions.FindAsync(id);

                    if (!await UserOwnsQuestionAsync(DBQuestion))
                    {
                        return(NotFound());
                    }

                    DBQuestion.Title   = model.Title;
                    DBQuestion.Content = model.Content;


                    // Add tags
                    DBQuestion.Tags.Clear();

                    if (!string.IsNullOrEmpty(model.Tags))
                    {
                        var tags = model.Tags.Split(',', StringSplitOptions.RemoveEmptyEntries);

                        if (tags.Any())
                        {
                            foreach (var tag in tags)
                            {
                                var dbTag = _context.Tags.FirstOrDefault(t => t.Name.ToLower() == tag.ToLower());
                                if (dbTag == null)
                                {
                                    // Tag does not exist, create it
                                    dbTag      = new Tag();
                                    dbTag.Name = tag;
                                    _context.Tags.Add(dbTag);
                                }

                                var questionTag = new QuestionTag();
                                questionTag.Question = DBQuestion;
                                questionTag.Tag      = dbTag;

                                DBQuestion.Tags.Add(questionTag);
                            }
                        }
                    }

                    _context.Update(DBQuestion);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!QuestionExists(model.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(model));
        }
예제 #27
0
        protected void post_Btn_Click(object sender, EventArgs e)
        {
            DBCramming db = new DBCramming();

            Model.Question _q = new Model.Question();

            var id = from q in db.Questions
                     select q.QuestionID;

            string[] tags = tag.Text.Split(' ');
            if (tags.Length <= 3)
            {
                if (tag.Text == "")
                {
                    valid.Text = "Vui lòng nhập tối thiểu 1 tag";
                }
                else
                {
                    foreach (string t in tags)
                    {
                        var check = from tg in db.Tags
                                    where tg.TagName == t
                                    select tg.TagID;
                        if (check.Count() < 1)
                        {
                            var new_id = from tg in db.Tags

                                         select tg.TagID;
                            Tag new_tag = new Tag();
                            new_tag.TagID   = new_id.Max() + 1;
                            new_tag.TagName = t;
                            db.Tags.Add(new_tag);
                            db.SaveChanges();
                        }
                    }
                    if (title.Text == "")
                    {
                        valid.Text = "Tiêu đề không được rỗng";
                    }
                    else
                    {
                        if (body.Text == "")
                        {
                            valid.Text = "Nội dung không được rỗng";
                        }
                        else
                        {
                            _q.UserID     = Session["id"].ToString();
                            _q.QuestionID = id.Max() + 1;
                            _q.Title      = title.Text;
                            _q.Body       = body.Text;
                            _q.viewcount  = 0;
                            _q.Likes      = 0;
                            _q.Posttime   = DateTime.Now;

                            db.Questions.Add(_q);
                            int res = db.SaveChanges();

                            foreach (string t in tags)
                            {
                                QuestionTag new_qt = new QuestionTag();
                                var         new_id = from qt in db.QuestionTags
                                                     select qt.QTID;
                                var tag_id = from b in db.Tags
                                             where b.TagName == t
                                             select b.TagID;
                                new_qt.QTID       = new_id.Max() + 1;
                                new_qt.TagID      = tag_id.FirstOrDefault();
                                new_qt.QuestionID = _q.QuestionID;

                                db.QuestionTags.Add(new_qt);
                                db.SaveChanges();
                            }
                            if (res > 0)
                            {
                                Response.Redirect("Question.aspx");
                            }
                            else
                            {
                                valid.Text = "Đã có lỗi xảy ra vui lòng thử lại";
                            }
                        }
                    }
                }
            }
            else
            {
                valid.Text = "Vui lòng nhập ít hơn 3 tag";
            }
        }
예제 #28
0
        //public Dictionary<Tag, int> GetTagCloud(int quantity)
        //{
        //    var parameters = new SqlParameter[] { new SqlParameter("@Quantity", quantity.ToString())};
        //    var tags1 = _repository.FromSql(new TagCloud() , @"SELECT TOP (CONVERT(INT,@Quantity)) Id, QuestionId, TagId
        //                                           ,COUNT(0) Count  FROM[dbo].[QuestionTag]  GROUP BY Id, QuestionId, TagId  ORDER BY COUNT(0) DESC", parameters);

        //    var tags = _repository.GetTagCloud();
        //    //.GroupBy(info => info.Tag)
        //    //.Select(group => new {
        //    //    Tag = group.Key,
        //    //    Count = group.Count()
        //    //})
        //    //.OrderByDescending(x => x.Count)
        //    //.Take(quantity)
        //    //.ToDictionary(x => x.Tag, x=>x.Count);

        //    var tagg = tags.Select(c => new
        //    {
        //        c.Tag
        //    }).GroupBy(c => c.Tag, (k, g) => new
        //    {
        //        Tag = k,
        //        Count = g.Count()
        //    }).OrderByDescending(x => x.Count).Take(quantity);

        //    return tagg.ToDictionary(x => x.Tag, x => x.Count);
        //}

        public void Remove(QuestionTag obj)
        {
            _repository.Remove(obj);
        }
예제 #29
0
 public void Update(QuestionTag obj)
 {
     _repository.Update(obj);
 }
예제 #30
0
        public bool CreateDefaults()
        {
            //bool AnswerRepositoryIsEmpty = AnswerRepository.Select().Count() == 0;
            //bool AnswerRepositoryIsEmpty = AnswerRepository.FindBy(item=>item.Description=="zzzz").Count() == 0;
            bool AnswerRepositoryIsEmpty = AnswerRepository.FindAllAsync().GetAwaiter().GetResult().Count() == 0;

            if (AnswerRepositoryIsEmpty == false)
            {
                return(false);
            }
            bool CategoryRepositoryIsEmpty = CategoryRepository.FindAllAsync().GetAwaiter().GetResult().Count() == 0;
            bool EarningRepositoryIsEmpty  = EarningRepository.FindAllAsync().GetAwaiter().GetResult().Count() == 0;
            bool QuestionRepositoryIsEmpty = QuestionRepository.FindAllAsync().GetAwaiter().GetResult().Count() == 0;
            bool TagRepositoryIsEmpty      = TagRepository.FindAllAsync().GetAwaiter().GetResult().Count() == 0;
            //bool ApplicationUserRepositoryIsEmpty = ApplicationUserRepository.All().Count() == 0;
            bool ApplicationUserRepositoryIsEmpty = ApplicationUserRepository.FindAllAsync().GetAwaiter().GetResult().Count() == 0;

            ////aboutIsEmpty = false;
            //if (CategoryRepositoryIsEmpty == false) return false;
            if (CategoryRepositoryIsEmpty)
            {
                try
                {
                    string[] categoryNames = new string[] { "Categoryname1", "Categoryname2" };
                    foreach (var item in categoryNames)
                    {
                        var newItem = new Category
                        {
                            CreatedDate = DateTime.Now,
                            UpdatedDate = DateTime.Now,
                            Name        = item,
                            ImageOrIcon = "https://img.icons8.com/nolan/64/bug.png"
                        };
                        CategoryRepository.AddAsync(newItem).GetAwaiter().GetResult();
                    }
                    Commit();
                }
                catch (Exception e)
                {
                    throw e;
                    Console.WriteLine("{0} Exception caught.", e.Message);
                }
            }
            if (TagRepositoryIsEmpty)
            {
                try
                {
                    string[] tagNames = new string[] { "tag1", "tag2", "tag3", "tag4" };
                    foreach (var item in tagNames)
                    {
                        var newItem = new Tag
                        {
                            CreatedDate = DateTime.Now,
                            UpdatedDate = DateTime.Now,
                            Name        = item
                        };
                        TagRepository.AddAsync(newItem).GetAwaiter().GetResult();
                    }
                    Commit();
                }
                catch (Exception e)
                {
                    throw e;
                    Console.WriteLine("{0} Exception caught.", e.Message);
                }
            }
            if (ApplicationUserRepositoryIsEmpty)
            {
                try
                {
                    string[] userNames = new string[] { "User1", "User2", "User3", "User4" };
                    foreach (var item in userNames)
                    {
                        var newItem = new ApplicationUser
                        {
                            Id                 = Guid.NewGuid().ToString(),
                            CreatedDate        = DateTime.Now,
                            UpdatedDate        = DateTime.Now,
                            FacebookName       = item,
                            ProfilePicture     = "SeedPicture",
                            ProfilePictureWeb  = "https://img.icons8.com/nolan/64/user.png",
                            ConcurrencyStamp   = Guid.NewGuid().ToString(),
                            SecurityStamp      = Guid.NewGuid().ToString("N").ToUpper(),
                            NormalizedEmail    = item.ToLower() + "@asqme.com",
                            Email              = item.ToLower() + "@asqme.com",
                            NormalizedUserName = item.ToLower() + "@asqme.com",
                            UserName           = item.ToLower() + "@asqme.com",
                        };
                        //var newItem2 = new ApplicationUser
                        //{
                        //    CreatedDate = DateTime.Now,
                        //    UpdatedDate = DateTime.Now,
                        //    FacebookName = "FacebookName",
                        //    ProfilePicture = "SeedPicture",
                        //    ProfilePictureWeb = "https://img.icons8.com/nolan/64/user.png",
                        //    ConcurrencyStamp = Guid.NewGuid().ToString(),
                        //    SecurityStamp = Guid.NewGuid().ToString(),
                        //    NormalizedEmail = AppSettings.Value.AdminEmail,
                        //    Email = AppSettings.Value.AdminEmail,
                        //    NormalizedUserName = AppSettings.Value.AdminEmail,
                        //    UserName = AppSettings.Value.AdminEmail,
                        //};
                        ApplicationUserRepository.AddAsync(newItem).GetAwaiter().GetResult();
                        //UserManager.CreateAsync(newItem2).GetAwaiter().GetResult();
                    }
                    Commit();
                }
                catch (Exception e)
                {
                    throw e;
                    Console.WriteLine("{0} Exception caught.", e.Message);
                }
            }
            if (QuestionRepositoryIsEmpty)
            {
                try
                {
                    var users      = ApplicationUserRepository.FindAllAsync().GetAwaiter().GetResult().ToList();
                    var tags       = TagRepository.FindAllAsync().GetAwaiter().GetResult().ToList();
                    var categories = CategoryRepository.FindAllAsync().GetAwaiter().GetResult().ToList();
                    foreach (var item in tags)
                    {
                        var newItem = new Question
                        {
                            CreatedDate       = DateTime.Now,
                            UpdatedDate       = DateTime.Now,
                            Title             = "Question Title",
                            Description       = "Question Description",
                            ApplicationUserId = users[new Random().Next(0, users.Count() - 1)].Id,
                            SolverAnswerId    = int.MinValue,
                            CategoryId        = categories[new Random().Next(0, categories.Count() - 1)].Id
                        };
                        QuestionRepository.AddAsync(newItem).GetAwaiter().GetResult();
                        //Commit();
                        //Id = QuestionTagRepository.All().Count() + 1,
                        //CreatedDate = DateTime.Now,
                        //UpdatedDate = DateTime.Now,
                        var newItem2 = new QuestionTag
                        {
                            QuestionId = newItem.Id,
                            TagId      = tags[new Random().Next(0, tags.Count() - 1)].Id
                        };
                        QuestionTagRepository.AddAsync(newItem2).GetAwaiter().GetResult();
                    }
                    Commit();
                }
                catch (Exception e)
                {
                    throw e;
                    Console.WriteLine("{0} Exception caught.", e.Message);
                }
            }
            if (AnswerRepositoryIsEmpty)
            {
                var users     = ApplicationUserRepository.FindAllAsync().GetAwaiter().GetResult().ToList();
                var questions = QuestionRepository.FindAllAsync().GetAwaiter().GetResult().ToList();
                try
                {
                    foreach (var item in questions)
                    {
                        var newItem = new Answer
                        {
                            CreatedDate       = DateTime.Now,
                            UpdatedDate       = DateTime.Now,
                            QuestionId        = item.Id,
                            ApplicationUserId = users[new Random().Next(0, users.Count() - 1)].Id,
                            Description       = "Answer Description"
                        };
                        AnswerRepository.AddAsync(newItem).GetAwaiter().GetResult();
                        Commit();
                        item.SolverAnswerId = newItem.Id;
                        QuestionRepository.UpdateAsync(item).GetAwaiter().GetResult();
                        Commit();
                    }
                }
                catch (Exception e)
                {
                    throw e;
                    Console.WriteLine("{0} Exception caught.", e.Message);
                }
            }
            if (EarningRepositoryIsEmpty)
            {
                try
                {
                    var users = ApplicationUserRepository.FindAllAsync().GetAwaiter().GetResult().ToList();
                    //var earningsTypes = new string[] { "Received", "Sent" };
                    var earningsTypes = Enum.GetValues(typeof(Earning.EarningType));
                    foreach (var item in users)
                    {
                        foreach (var item2 in users)
                        {
                            var newItem = new Earning
                            {
                                CreatedDate  = DateTime.Now,
                                UpdatedDate  = DateTime.Now,
                                EarningsType = (Earning.EarningType)earningsTypes.GetValue(new Random().Next(earningsTypes.Length)),
                                Amount       = 1m,
                                SenderId     = users.Where(u => u.Id != item.Id).ToList()
                                               [new Random().Next(0, users.Count() - 2)].Id,
                                ApplicationUserId = item.Id
                            };
                            EarningRepository.AddAsync(newItem).GetAwaiter().GetResult();
                        }
                        Commit();
                    }
                }
                catch (Exception e)
                {
                    throw e;
                    Console.WriteLine("{0} Exception caught.", e.Message);
                }
            }
            //Commit();
            if (CategoryRepositoryIsEmpty || TagRepositoryIsEmpty || ApplicationUserRepositoryIsEmpty ||
                QuestionRepositoryIsEmpty || AnswerRepositoryIsEmpty || EarningRepositoryIsEmpty)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }