예제 #1
0
 public HttpResponseMessage PostComment(Comment comment)
 {
     comment = repository.Add(comment);
     var response = Request.CreateResponse<Comment>(HttpStatusCode.Created, comment);
     response.Headers.Location = new Uri(Request.RequestUri, "/api/comments/" + comment.ID.ToString());
     return response;
 }
        public void CreatesItem()
        {
            //Arrange
            var context = Context.Create(Utilities.CreateStandardResolver());

            var db = Sitecore.Configuration.Factory.GetDatabase("master");
            var scContext = new SitecoreService(db);

            var parentItem = db.GetItem("/sitecore/content/Tests/Issues/AlexGriciucCreateItemIssue");
            var parent = scContext.GetItem<CommentPage>("/sitecore/content/Tests/Issues/AlexGriciucCreateItemIssue");

            using (new SecurityDisabler())
            {
                parentItem.DeleteChildren();
            }

            var newItem = db.GetItem("/sitecore/content/Tests/Issues/AlexGriciucCreateItemIssue/TestName");
            Assert.IsNull(newItem);

            //Act
        //    scContext.GlassContext.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(Comment)));
            var newClass = new Comment();
            newClass.Name = "TestName";
            using (new SecurityDisabler())
            {
                scContext.Create(parent, newClass);
            }

            //Asset

            newItem = db.GetItem("/sitecore/content/Tests/Issues/AlexGriciucCreateItemIssue/TestName");
            Assert.IsNotNull(newItem);
        }
예제 #3
0
파일: AlertService.cs 프로젝트: SPKT/MHX2
        public void AddComment(Comment c)
        {
            alert = new Alert();
            alert.CreateDate = c.CreateDate;
            if (c.SystemObjectID == 1)
            {
                _statusUpdateRepository = new StatusUpdateRepository();
                StatusUpdate st = _statusUpdateRepository.GetStatusUpdateByID((int)c.SystemObjectRecordID);
                account=_accountRepository.GetAccountByID(st.SenderID);
                alertMessage = GetProfileUrl(c.CommentByUsername)+" bình luận status của "+ GetProfileUrl(account.UserName)+":" + c.Body;
                alert.Message = alertMessage;
                alert.AccountID = c.CommentByAccountID;
                alert.AlertTypeID = (int)AlertType.AlertTypes.Comment;
                SaveAlert(alert);

                Notification notification = new Notification();
                string notify = "<a href=\"/UserProfile2.aspx?AccountID=" + c.CommentByAccountID.ToString() + "\">" +
                c.CommentByUsername + "</a>" +
                 "vừa mới bình luận status của bạn: " + c.Body;
                notification.AccountID = st.SenderID;
                notification.CreateDate = c.CreateDate;
                notification.IsRead =false;
                notification.Body = notify;
                _notifycationRepository.SaveNotification(notification);
            }
        }
예제 #4
0
        public ActionResult Create(Comment comment, string returlUrl)
        {
            if (ModelState.IsValid)
            {
                comment.Date = DateTime.Now;
                db.Comments.AddObject(comment);
                db.SaveChanges();

                var success = String.Format(Resource.CommentSuccess, comment.Author);
                if (Request.IsAjaxRequest())
                {
                    return Content(success);
                }
                TempData["Result"] = success;
                return Redirect(returlUrl ?? Url.Action("Index", "About"));
            }
            else
            {
                if (Request.IsAjaxRequest())
                {
                    return PartialView("_CommentForm");
                }
                return View();
            }
        }
		public void BindDataToCell(Comment comment, NSIndexPath indexPath, UITableView tableView)
		{
			CellUserImageButton.SetUserImage(comment.user);
			CellUsernameLabel.SetTitle (comment.user.username);
			CellComment.AttributedText = NativeStringUtils.ParseStringForKeywords (comment, comment.text);
			CellTimestamp.Text = StringUtils.GetPrettyDateAbs (comment.datestamp);
		}
예제 #6
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        var oComment = new Comment();
        string strUserName = User.Identity.Name;
        string strLink = Request.Url.Scheme + "://" + Request.Url.Host + Request.RawUrl;
        string strPriority = "";
        string strIsApproved = "True";
        string strIsAvailable = "True";

        //Sửa chỗ này, các phần trên để nguyên
        string strTitle = Page.Title;
        string strContent = TextBox1.Text.Trim();
        //End

        oComment.CommentInsert(
            strUserName,
            strLink,
            strTitle,
            "",
            "",
            strContent,
            strPriority,
            strIsApproved,
            strIsAvailable
        );
    }
예제 #7
0
    public List<Comment> getComments(int RequestId)
    {
        List<Comment> _Comments = new List<Comment>();
        Query = "SELECT comment.id, comment.userid, comment.statusid, comment.text, comment.datetime FROM Comment WHERE Comment.Id = " + RequestId + " ORDER BY Comment.DateTime";
        try
        {
            Data.SqlCommand cm = new Data.SqlCommand();
            cm.CommandText = Query;
            Data.SqlDataReader rd = cm.ExecuteReader();
            while (rd.Read())
            {
                Comment _Comment = new Comment();
                _Comment.Id = rd.GetInt16(0);
                _Comment.User = getUser(rd.GetInt16(1));
                _Comment.Status = getStatusById(rd.GetInt16(2));
                _Comment.Text = rd.GetString(3);
                _Comment.DateTime = rd.GetString(4);
                _Comments.Add(_Comment);
            }
            rd.Close();
        }
        catch (Exception)
        {

            throw;
        }
        return (_Comments);
    }
예제 #8
0
        public Comment Add(string content, int postId, string userId)
        {
            if (string.IsNullOrWhiteSpace(content) || string.IsNullOrWhiteSpace(userId))
            {
                return null;
            }

            var user = this.usersService.ById(userId, false);
            if (user == null)
            {
                return null;
            }

            var comment = new Comment()
            {
                Content = content,
                PostId = postId,
                User = user
            };

            try
            {
                this.commentsRepo.Add(comment);
                this.commentsRepo.Save();
                return this.commentsRepo.GetById(comment.Id);
            }
            catch (Exception)
            {
                // log error
                return null;
            }
        }
예제 #9
0
 private static string GetText(Comment comment)
 {
     var textComment = ((TextComment) comment);
     var text = textComment.Text;
     return HtmlEncoder.HtmlEncode(
         text.Length > 1 && text[0] == ' ' && text[1] != ' ' ? text.Substring(1) : text);
 }
 public LinkIssuesInput(string fromIssueKey, string toIssueKey, string linkType, Comment comment)
 {
     FromIssueKey = fromIssueKey;
     ToIssueKey = toIssueKey;
     LinkType = linkType;
     Comment = comment;
 }
예제 #11
0
 public string formatCom(Comment item)
 {
     return string.Format(@"<div class=""bl-item"">
         <div class=""bl-item-ten"">{0}</div>
         <div class=""bl-item-moTa"">{1}</div>
     </div>", item.KH_Ten, item.NoiDung);
 }
예제 #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string strTitle, strDescription, strMetaTitle, strMetaDescription;
            if (!string.IsNullOrEmpty(Request.QueryString["tv"]))
            {
                var oComment = new Comment();
                var dv = oComment.CommentSelectOne(Request.QueryString["tv"]).DefaultView;

                if (dv != null && dv.Count <= 0) return;
                var row = dv[0];

                strTitle = Server.HtmlDecode(row["Title"].ToString());
                strDescription = Server.HtmlDecode(row["Title"].ToString());
                strMetaTitle = Server.HtmlDecode(row["Title"].ToString());
                strMetaDescription = Server.HtmlDecode(row["Title"].ToString());

            }
            else
            {
                strTitle = strMetaTitle = "Tư Vấn";
                strDescription = "";
                strMetaDescription = "";
            }
            Page.Title = !string.IsNullOrEmpty(strMetaTitle) ? strMetaTitle : strTitle;
            var meta = new HtmlMeta() { Name = "description", Content = !string.IsNullOrEmpty(strMetaDescription) ? strMetaDescription : strDescription };
            Header.Controls.Add(meta);
        }
    }
		public object Deserialize(JsonValue json, JsonMapper mapper)
		{
			Comment comment = null;
			if ( json != null && !json.IsNull )
			{
				comment = new Comment();
				comment.ID          = json.ContainsName("id"          ) ? json.GetValue<string>("id"     ) : String.Empty;
				comment.Message     = json.ContainsName("message"     ) ? json.GetValue<string>("message") : String.Empty;
				comment.CreatedTime = json.ContainsName("created_time") ? JsonUtils.ToDateTime(json.GetValue<string>("created_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue;

				comment.From        = mapper.Deserialize<Reference      >(json.GetValue("from" ));
				// 04/12/2012 Paul.  Likes is a connection object, so make sure that this is not the same likes property value. 
				// 04/15/2012 Paul.  Likes can be a number or an array. 
				JsonValue jsonLikes = json.GetValue("likes");
				if ( jsonLikes != null && !jsonLikes.IsNull )
				{
					if ( jsonLikes.IsArray )
					{
						comment.Likes       = mapper.Deserialize<List<Reference>>(jsonLikes);
						comment.LikesCount  = (comment.Likes != null) ? comment.Likes.Count : 0;
					}
					else if ( jsonLikes.IsNumber )
					{
						comment.LikesCount = jsonLikes.GetValue<int>();
					}
				}
			}
			return comment;
		}
예제 #14
0
        /// <summary>
        /// Check if comment is spam
        /// </summary>
        /// <param name="comment">
        /// The comment
        /// </param>
        /// <returns>
        /// True if comment is spam
        /// </returns>
        public bool Check(Comment comment)
        {
            try
            {
                var url = string.Format("http://www.stopforumspam.com/api?ip={0}", comment.IP);

                var request = (HttpWebRequest)WebRequest.Create(url);
                var response = (HttpWebResponse)request.GetResponse();
                var responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    var reader = new StreamReader(responseStream);

                    var value = reader.ReadToEnd();
                    reader.Close();

                    var spam = value.ToLowerInvariant().Contains("<appears>yes</appears>") ? true : false;

                    // if comment IP appears in the stopforumspam list
                    // it is for sure spam; no need to pass to others.
                    passThrough = spam ? false : true;

                    return spam;
                }
            
                return false;
            }
            catch (Exception e)
            {
                Utils.Log(string.Format("Error checking stopforumspam.com: {0}", e.Message));
                return false;
            }
        }
예제 #15
0
 public static CommentServiceModel mapCommentEntityToModel(Comment comment)
 {
     CommentServiceModel model = new CommentServiceModel();
     model.comment = comment.Comment1;
     model.id = comment.Id;
     return model;
 }
        /// <summary>
        /// Adds a new comment to the database
        /// </summary>
        public override void CreateComment(Comment commentToCreate)
        {
            var entity = ConvertCommentToCommentEntity(commentToCreate);

            _entities.AddToCommentEntitySet(entity);
            _entities.SaveChanges();
        }
예제 #17
0
        public DetailStoryViewModel()
        {
            //temp drit
            UserStory = new Story();
            UserStory.Description = "Random description. blablablablablablabla. blablalbllalblalbal";
            UserStory.Title = "Random Title";

            User tempUser = new User();
            tempUser.UserName = "******";
            tempUser.RealName = "Hans Petter Naumann";
            UserStory.Author = tempUser;
            UserStory.CreatedDate = DateTime.Now;

            Comment c1 = new Comment();
            c1.Author = tempUser;
            c1.Text = "random comment. blabla";
            c1.TimeStamp = DateTime.Now;

            Comment c2 = new Comment();
            c2.Author = tempUser;
            c2.Text = "random comment number 2. blabla";
            c2.TimeStamp = DateTime.Now;

            UserStory.Comments.Add(c1);
            UserStory.Comments.Add(c2);
            UserStory.Assignee = tempUser;
        }
        public int Add(string commentContent, string creator, int postId)
        {

            var currentUser = this.users
                .All()
                .FirstOrDefault(u => u.UserName == creator);

            var currentPost = this.posts
                .All()
                .FirstOrDefault(p => p.PostId == postId);

            var newComment = new Comment()
            {
                CommentContent = commentContent,
                User = currentUser,
                UserId = currentUser.Id,
                Post = currentPost,
                PostId = postId
            };

            this.comments.Add(newComment);
            this.comments.SaveChanges();

            return newComment.CommentId;
        }
예제 #19
0
    protected void btnlogin_Click(object sender, EventArgs e)
    {
        if (txtsubject.Text.Trim() == "") {
            Alert.Show("กรุณากรอกชื่อเรื่องด้วย !!!");
            txtsubject.Focus();
            return;
        }

        if (txtcomment.Text.Trim() == "") {
            Alert.Show("กรุณากรอกข้อเสนอแนะด้วย !!!");
            txtcomment.Focus();
            return;
        }

        try
        {
            MemberService service = new MemberService();
            Comment _comment = new Comment();
            _comment.ID = 1;
            _comment.IP = "192.18.1.1";
            _comment.Subject = txtsubject.Text.Trim();
            _comment.CommentDecription = txtcomment.Text.Trim();

            if (service.CreateComment(_comment) == true)
            {
                clear();
                Alert.Show("บันทึกเรียบร้อยแล้ว");

            }

        }
        catch (Exception ex) {
            Alert.Show("ไม่สามารถบันทึกได้เนื่องจาก " + ex.Message);
        }
    }
예제 #20
0
        public Guid InsertComment(Comment objComment)
        {
            Guid retGuid = new Guid("00000000-0000-0000-0000-000000000000");
            DataRow dr = null;
            try
            {
                DbParam[] param = new DbParam[4];

                param[0] = new DbParam("@CommentId", objComment.CommentId, SqlDbType.UniqueIdentifier);
                param[1] = new DbParam("@CommentName", objComment.CommentName, SqlDbType.VarChar);
                param[2] = new DbParam("@StatusId", objComment.StatusId, SqlDbType.UniqueIdentifier);
                param[3] = new DbParam("@UserId", objComment.UserId, SqlDbType.UniqueIdentifier);

                //retVal = Db.Insert("proc_tblComment_Ins", param, true);
                dr = Db.GetDataRow("proc_tblComment_Ins", param);
                if (dr != null && dr[0] != null)
                    retGuid = Db.ToGuid(dr[0]);

                return retGuid;
            }
            catch (Exception ex)
            {
                // CommonFunctions.LogError(ex, WINIT.ErrorLog.LogSeverity.Error);
                throw ex;
            }
        }
예제 #21
0
 public CommentDTO(Comment cm)
 {
     NOIDUNG = cm.NOIDUNG;
     THOIGIAN = cm.THOIGIAN;
     TKCOMMENT = cm.TKCOMMENT;
     MAVOUCHERCOMMENT = cm.MAVOUCHERCOMMENT;
 }
예제 #22
0
        public Comment Addcomment(int pageId, string commentText, string urlstring, string commentId)
        {
            var commentStore = DynamicDataStoreFactory.Instance.GetStore(typeof(Comment));
            string CommentGuid = Guid.NewGuid().ToString();
            var comment = new Comment()
            {
                CommentId = CommentGuid,
                CommentText = commentText,
                Date = DateTime.Now,
                UserName = "******",
                PageId = pageId,
                IsCommentDeleted = false,
                ParentCommentId = commentId == "" ? "" : commentId

            };

            commentStore.Save(comment);

            { }

            var er = commentStore.Items<Comment>();

            var query = from comments in er
                        where comments.CommentId == CommentGuid                        
                        select comments;

            var list = query.ToList<Comment>();

            return list[0];
        }
예제 #23
0
        public bool ValidateComment(Comment comment) {
            CommentSettingsRecord commentSettingsRecord = CurrentSite.As<CommentSettings>().Record;
            string akismetKey = commentSettingsRecord.AkismetKey;
            string akismetUrl = commentSettingsRecord.AkismetUrl;
            bool enableSpamProtection = commentSettingsRecord.EnableSpamProtection;
            if (enableSpamProtection == false) {
                return true;
            }
            if (String.IsNullOrEmpty(akismetKey)) {
                _notifer.Information(T("Please configure your Akismet key for spam protection"));
                return true;
            }
            if (String.IsNullOrEmpty(akismetUrl)) {
                akismetUrl = "http://www.orchardproject.net";
            }
            Akismet akismetApi = new Akismet(akismetKey, akismetUrl, null);
            AkismetComment akismetComment = new AkismetComment {
                CommentAuthor = comment.Record.Author,
                CommentAuthorEmail = comment.Record.Email,
                Blog = comment.Record.SiteName,
                CommentAuthorUrl = comment.Record.SiteName,
                CommentContent = comment.Record.CommentText,
                UserAgent = HttpContext.Current.Request.UserAgent,
            };

            if (akismetApi.VerifyKey()) {
                return akismetApi.CommentCheck(akismetComment);
            }

            return false;
        }
        public Comment AddNew(Comment toAdd)
        {
            this.comments.Add(toAdd);
            this.comments.Save();

            return toAdd;
        }
예제 #25
0
        public IHttpActionResult PostComment(int eventId, [FromBody] CommmentsResponseModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var eventToJoin = this.data.Events.All().Where(ev => ev.Id == eventId).FirstOrDefault();

            if (eventToJoin == null)
            {
                return this.BadRequest();
            }

            var currentUserName = this.User.Identity.Name;
            var currentUser = this.data.Users.All().Where(u => u.UserName == currentUserName).FirstOrDefault();

            var commentToAdd = new Comment
            {
                Content = model.Content,
                DateCreated = DateTime.UtcNow,
                EventId = eventToJoin.Id,
                AuthorId = currentUser.Id
            };

            this.data.Comments.Add(commentToAdd);
            this.data.Savechanges();

            return this.Created("api/commets/{eventId}", new
            {
                CommentId = commentToAdd.Id
            });
        }
예제 #26
0
        public static void AddMembers(AroundMooContext context)
        {
            var member = new Member("admin", "*****@*****.**", "admin!", MemberRole.Admin.ToString());
            context.Members.AddOrUpdate(member);

            var user1 = new Member("user1", "*****@*****.**", "user1!", MemberRole.User.ToString());
            context.Members.AddOrUpdate(user1);

            var user2 = new Member("user2", "*****@*****.**", "user2!", MemberRole.User.ToString());
            context.Members.AddOrUpdate(user2);

            //add infos
            var info1 = new Comment(user1, "This is the best house in the world", -37.88114, 144.749646);
            context.Comments.AddOrUpdate(info1);

            var info2 = new Comment(user1, "Be careful when driving around here", -37.88214, 144.749746);
            context.Comments.AddOrUpdate(info2);

            //member retrieve infos
            var memberComment1 = new MemberComment(user1, info1);
            var memberComment2 = new MemberComment(user1, info2);
            var memberComment3 = new MemberComment(user2, info1);
            var memberComment4 = new MemberComment(user2, info2);

            context.MemberComments.Add(memberComment1);
            context.MemberComments.Add(memberComment2);
            context.MemberComments.Add(memberComment3);
            context.MemberComments.Add(memberComment4);

            context.SaveChanges();
        }
예제 #27
0
        // Insert a comment on the first paragraph.
        public static void AddCommentOnFirstParagraph(string fileName,
            string author, string initials, string comment)
        {
            // Use the file name and path passed in as an 
            // argument to open an existing Wordprocessing document. 
            using (WordprocessingDocument document =
                WordprocessingDocument.Open(fileName, true))
            {
                // Locate the first paragraph in the document.
                Paragraph firstParagraph =
                    document.MainDocumentPart.Document.Descendants<Paragraph>().First();
                Comments comments = null;
                string id = "0";

                // Verify that the document contains a 
                // WordProcessingCommentsPart part; if not, add a new one.
                if (document.MainDocumentPart.GetPartsCountOfType<WordprocessingCommentsPart>() > 0)
                {
                    comments =
                        document.MainDocumentPart.WordprocessingCommentsPart.Comments;
                    if (comments.HasChildren)
                    {
                        // Obtain an unused ID.
                        id = comments.Descendants<Comment>().Select(e => e.Id.Value).Max();
                    }
                }
                else
                {
                    // No WordprocessingCommentsPart part exists, so add one to the package.
                    WordprocessingCommentsPart commentPart =
                        document.MainDocumentPart.AddNewPart<WordprocessingCommentsPart>();
                    commentPart.Comments = new Comments();
                    comments = commentPart.Comments;
                }

                // Compose a new Comment and add it to the Comments part.
                Paragraph p = new Paragraph(new Run(new Text(comment)));
                Comment cmt =
                    new Comment()
                    {
                        Id = id,
                        Author = author,
                        Initials = initials,
                        Date = DateTime.Now
                    };
                cmt.AppendChild(p);
                comments.AppendChild(cmt);
                comments.Save();

                // Specify the text range for the Comment. 
                // Insert the new CommentRangeStart before the first run of paragraph.
                firstParagraph.InsertBefore(new CommentRangeStart() { Id = id }, firstParagraph.GetFirstChild<Run>());

                // Insert the new CommentRangeEnd after last run of paragraph.
                var cmtEnd = firstParagraph.InsertAfter(new CommentRangeEnd() { Id = id }, firstParagraph.Elements<Run>().Last());

                // Compose a run with CommentReference and insert it.
                firstParagraph.InsertAfter(new Run(new CommentReference() { Id = id }), cmtEnd);
            }
        }
예제 #28
0
        // POST /Api/v1/LogBooks/33/Entries/1/Comments
        public HttpResponseMessage Post([FromUri]int? logBookId, [FromUri]int? entryId, CommentInput commentInput)
        {
            var logBook = base.RavenSession.Load<LogBook>(logBookId);

            if (logBook == null)
                return NotFound();

            if (logBook.IsOwnedBy(base.User.Identity.Name) == false)
                return Forbidden();

            var entry = logBook.GetEntries()
                               .SingleOrDefault(x => x.Id == entryId);

            if (entry == null)
                return NotFound();

            var comment = new Comment<Entry>();
            commentInput.MapToInstance(comment);
            entry.AddComment(comment);

            base.RavenSession.Store(logBook);

            var commentView = comment.MapTo<LogBookView.CommentView>();

            return Created(commentView);
        }
예제 #29
0
        private OperationReturn LoadScoreItem(SessionInfo session, ScoreItem parent, string scoreID)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                string     rentToken  = session.RentInfo.Token;
                ScoreSheet scoreSheet = parent.ScoreSheet;
                if (scoreSheet == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("ScoreSheet is null");
                    return(optReturn);
                }
                string temp1 = string.Empty;
                string temp2 = string.Empty;
                if (!string.IsNullOrWhiteSpace(scoreID))
                {
                    temp1 = string.Format(",T3109.C005 AS NA");
                    temp2 = string.Format(" LEFT JOIN T_31_009_{0} T3109 ON T3102.C002=T3109.C002", rentToken);
                }
                string  strSql;
                DataSet objDataSet;
                switch (session.DBType)
                {
                case 2:
                    strSql = string.Format(
                        "SELECT T3102.*{4} FROM T_31_002_{0} T3102{5}  WHERE T3102.C003 = {1} AND T3102.C004 = {2}{3} ",
                        rentToken, scoreSheet.ID, parent.ID, scoreID, temp1, temp2);
                    optReturn = MssqlOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                case 3:
                    strSql = string.Format(
                        "SELECT T3102.*{4} FROM T_31_002_{0} T3102{5} WHERE T3102.C003 = {1} AND T3102.C004 = {2}{3} ",
                        rentToken, scoreSheet.ID, parent.ID, scoreID, temp1, temp2);
                    optReturn = OracleOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                default:
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_PARAM_INVALID;
                    optReturn.Message = string.Format("DBType invalid");
                    return(optReturn);
                }
                if (objDataSet == null || objDataSet.Tables.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("DataSet is null or DataTables empty");
                    return(optReturn);
                }
                List <ScoreItem> listItems = new List <ScoreItem>();
                for (int i = 0; i < objDataSet.Tables[0].Rows.Count; i++)
                {
                    DataRow   dr = objDataSet.Tables[0].Rows[i];
                    ScoreItem scoreItem;
                    bool      isStandard = dr["C009"].ToString() == "Y";
                    if (isStandard)
                    {
                        Standard     standard     = null;
                        StandardType standardType = (StandardType)Convert.ToInt32(dr["C015"]);
                        switch (standardType)
                        {
                        case StandardType.Numeric:
                            NumericStandard numericStandard = new NumericStandard();
                            numericStandard.Type         = ScoreObjectType.NumericStandard;
                            numericStandard.MaxValue     = Convert.ToDouble(dr["C027"]);
                            numericStandard.MinValue     = Convert.ToDouble(dr["C028"]);
                            numericStandard.DefaultValue = string.IsNullOrWhiteSpace(dr["C029"].ToString()) ? 0 : Convert.ToDouble(dr["C029"]);
                            numericStandard.ScoreClassic = StandardClassic.TextBox;
                            standard = numericStandard;
                            break;

                        case StandardType.YesNo:
                            YesNoStandard yesNoStandard = new YesNoStandard();
                            yesNoStandard.Type = ScoreObjectType.YesNoStandard;
                            if (string.IsNullOrWhiteSpace(dr["C029"].ToString()))
                            {
                                yesNoStandard.DefaultValue = false;
                            }
                            else
                            {
                                if (Convert.ToDouble(dr["C029"]) == 1.0)
                                {
                                    yesNoStandard.DefaultValue = true;
                                }
                                else
                                {
                                    yesNoStandard.DefaultValue = false;
                                }
                            }
                            yesNoStandard.ReverseDisplay = dr["C104"].ToString() == "1";
                            yesNoStandard.ScoreClassic   = StandardClassic.YesNo;
                            standard = yesNoStandard;
                            break;

                        case StandardType.Slider:
                            SliderStandard sliderStandard = new SliderStandard();
                            sliderStandard.Type         = ScoreObjectType.SliderStandard;
                            sliderStandard.MinValue     = Convert.ToDouble(dr["C023"]);
                            sliderStandard.MaxValue     = Convert.ToDouble(dr["C024"]);
                            sliderStandard.Interval     = Convert.ToDouble(dr["C026"]);
                            sliderStandard.DefaultValue = string.IsNullOrWhiteSpace(dr["C029"].ToString()) ? 0 : Convert.ToDouble(dr["C029"]);
                            sliderStandard.ScoreClassic = StandardClassic.Slider;
                            standard = sliderStandard;
                            break;

                        case StandardType.Item:
                            ItemStandard itemStandard = new ItemStandard();
                            itemStandard.Type         = ScoreObjectType.ItemStandard;
                            itemStandard.ScoreClassic = StandardClassic.DropDownList;
                            itemStandard.DefaultIndex = string.IsNullOrWhiteSpace(dr["C029"].ToString())?0: Convert.ToInt32(dr["C029"]);
                            standard = itemStandard;
                            break;
                        }
                        if (standard == null)
                        {
                            optReturn.Result  = false;
                            optReturn.Code    = Defines.RET_OBJECT_NULL;
                            optReturn.Message = string.Format("Standard is null");
                            return(optReturn);
                        }
                        standard.PointSystem    = Convert.ToDouble(dr["C018"]);
                        standard.StandardType   = standardType;
                        standard.IsAutoStandard = dr["C101"].ToString() == "Y";
                        if (!string.IsNullOrWhiteSpace(scoreID))
                        {
                            if (string.IsNullOrWhiteSpace(dr["NA"].ToString()))
                            {
                                standard.IsNA = false;
                            }
                            else
                            {
                                standard.IsNA = dr["NA"].ToString() == "Y" ? true : false;
                            }
                        }
                        string strStaID = dr["C102"].ToString();
                        long   staID;
                        if (long.TryParse(strStaID, out staID))
                        {
                            standard.StatisticalID = staID;
                        }
                        scoreItem = standard;
                    }
                    else
                    {
                        ScoreGroup scoreGroup = new ScoreGroup();
                        scoreGroup.Type  = ScoreObjectType.ScoreGroup;
                        scoreGroup.IsAvg = dr["C016"].ToString() == "Y";
                        scoreItem        = scoreGroup;
                    }
                    scoreItem.ScoreSheet     = parent.ScoreSheet;
                    scoreItem.Parent         = parent;
                    scoreItem.ItemID         = Convert.ToInt32(dr["C001"]);
                    scoreItem.ID             = Convert.ToInt64(dr["C002"]);
                    scoreItem.OrderID        = Convert.ToInt32(dr["C005"]);
                    scoreItem.Title          = dr["C006"].ToString();
                    scoreItem.Description    = dr["C007"].ToString();
                    scoreItem.TotalScore     = Convert.ToDouble(dr["C008"]);
                    scoreItem.IsAbortScore   = dr["C010"].ToString() == "Y";
                    scoreItem.ControlFlag    = dr["C011"].ToString() == "Y" ? 1 : 0;
                    scoreItem.IsKeyItem      = dr["C012"].ToString() == "Y";
                    scoreItem.IsAllowNA      = dr["C013"].ToString() == "Y";
                    scoreItem.IsJumpItem     = dr["C014"].ToString() == "Y";
                    scoreItem.IsAddtionItem  = dr["C017"].ToString() == "Y";
                    scoreItem.UsePointSystem = dr["C019"].ToString() == "Y";
                    scoreItem.ScoreType      = dr["C020"].ToString() == "F"
                        ? ScoreType.YesNo
                        : dr["C020"].ToString() == "P" ? ScoreType.Pecentage : ScoreType.Numeric;
                    scoreItem.Tip = dr["C022"].ToString();
                    scoreItem.AllowModifyScore = dr["C103"].ToString() == "Y";

                    #region 子项

                    //如果是 ScoreGroup 加载子项
                    if (!isStandard)
                    {
                        ScoreGroup scoreGroup = scoreItem as ScoreGroup;
                        optReturn = LoadScoreItem(session, scoreGroup, scoreID);
                        if (!optReturn.Result)
                        {
                            return(optReturn);
                        }
                        List <ScoreItem> subItems = optReturn.Data as List <ScoreItem>;
                        if (subItems == null)
                        {
                            optReturn.Result  = false;
                            optReturn.Code    = Defines.RET_OBJECT_NULL;
                            optReturn.Message = string.Format("ListItems is null");
                            return(optReturn);
                        }
                        for (int j = 0; j < subItems.Count; j++)
                        {
                            ScoreItem subItem = subItems[j];
                            scoreGroup.Items.Add(subItem);
                        }
                        scoreGroup.Items = scoreGroup.Items.OrderBy(j => j.OrderID).ToList();
                    }

                    //如果是多值型评分标准,加载评分标准子项
                    ItemStandard temp = scoreItem as ItemStandard;
                    if (temp != null)
                    {
                        optReturn = LoadStandardItem(session, temp);
                        if (!optReturn.Result)
                        {
                            return(optReturn);
                        }
                        List <StandardItem> valueItems = optReturn.Data as List <StandardItem>;
                        if (valueItems == null)
                        {
                            optReturn.Result  = false;
                            optReturn.Code    = Defines.RET_OBJECT_NULL;
                            optReturn.Message = string.Format("ValueItems is null");
                            return(optReturn);
                        }
                        for (int j = 0; j < valueItems.Count; j++)
                        {
                            StandardItem valueItem = valueItems[j];
                            temp.ValueItems.Add(valueItem);
                        }
                        temp.ValueItems = temp.ValueItems.OrderBy(j => j.OrderID).ToList();
                    }

                    #endregion


                    #region 备注

                    OperationReturn commentReturn;
                    commentReturn = LoadComment(session, scoreItem);
                    if (!commentReturn.Result)
                    {
                        return(commentReturn);
                    }
                    List <Comment> listComments = commentReturn.Data as List <Comment>;
                    if (listComments == null)
                    {
                        optReturn.Result  = false;
                        optReturn.Code    = Defines.RET_OBJECT_NULL;
                        optReturn.Message = string.Format("listComments is null");
                        return(optReturn);
                    }
                    for (int j = 0; j < listComments.Count; j++)
                    {
                        Comment comment = listComments[j];
                        scoreItem.Comments.Add(comment);
                    }
                    scoreItem.Comments = scoreItem.Comments.OrderBy(j => j.OrderID).ToList();

                    #endregion

                    #region 样式

                    OperationReturn styleReturn;
                    styleReturn = LoadVisualStyle(session, scoreItem, "T");
                    if (!styleReturn.Result)
                    {
                        if (styleReturn.Code != Defines.RET_NOT_EXIST)
                        {
                            return(styleReturn);
                        }
                        scoreItem.TitleStyle = null;
                    }
                    else
                    {
                        VisualStyle style = styleReturn.Data as VisualStyle;
                        if (style != null)
                        {
                            style.ScoreSheet     = scoreSheet;
                            scoreItem.TitleStyle = style;
                        }
                    }

                    styleReturn = LoadVisualStyle(session, scoreItem, "P");
                    if (!styleReturn.Result)
                    {
                        if (styleReturn.Code != Defines.RET_NOT_EXIST)
                        {
                            return(styleReturn);
                        }
                        scoreItem.PanelStyle = null;
                    }
                    else
                    {
                        VisualStyle style = styleReturn.Data as VisualStyle;
                        if (style != null)
                        {
                            style.ScoreSheet     = scoreSheet;
                            scoreItem.PanelStyle = style;
                        }
                    }

                    #endregion

                    listItems.Add(scoreItem);
                }
                optReturn.Data = listItems;
            }
            catch (Exception ex)
            {
                optReturn.Result  = false;
                optReturn.Code    = Defines.RET_FAIL;
                optReturn.Message = ex.Message;
            }
            return(optReturn);
        }
예제 #30
0
        private OperationReturn LoadScoreSheet(SessionInfo session, string scoreSheetID, string scoreID)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                string  rentToken = session.RentInfo.Token;
                string  strSql;
                DataSet objDataSet;
                switch (session.DBType)
                {
                case 2:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_001_{0} WHERE C001 = {1}",
                            rentToken,
                            scoreSheetID);
                    optReturn = MssqlOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                case 3:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_001_{0} WHERE C001 = {1}",
                            rentToken,
                            scoreSheetID);
                    optReturn = OracleOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                default:
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_PARAM_INVALID;
                    optReturn.Message = string.Format("DBType invalid");
                    return(optReturn);
                }
                if (objDataSet == null || objDataSet.Tables.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("DataSet is null or DataTables empty");
                    return(optReturn);
                }
                if (objDataSet.Tables[0].Rows.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_NOT_EXIST;
                    optReturn.Message = string.Format("ScoreSheet not exist");
                    return(optReturn);
                }
                DataRow    dr         = objDataSet.Tables[0].Rows[0];
                ScoreSheet scoreSheet = new ScoreSheet();
                scoreSheet.Type          = ScoreObjectType.ScoreSheet;
                scoreSheet.ScoreSheet    = scoreSheet;
                scoreSheet.ID            = Convert.ToInt64(dr["C001"]);
                scoreSheet.Title         = dr["C002"].ToString();
                scoreSheet.ViewClassic   = dr["C003"].ToString() == "C" ? ScoreItemClassic.Table : ScoreItemClassic.Tree;
                scoreSheet.TotalScore    = Convert.ToDouble(dr["C004"]);
                scoreSheet.Creator       = Convert.ToInt64(dr["C005"]);
                scoreSheet.CreateTime    = Convert.ToDateTime(dr["C006"]);
                scoreSheet.DateFrom      = Convert.ToDateTime(dr["C009"]);
                scoreSheet.DateTo        = Convert.ToDateTime(dr["C010"]);
                scoreSheet.QualifiedLine = Convert.ToDouble(dr["C011"]);
                scoreSheet.ScoreType     = dr["C014"].ToString() == "F"
                    ? ScoreType.YesNo
                    : dr["C014"].ToString() == "P" ? ScoreType.Pecentage : ScoreType.Numeric;
                scoreSheet.UseTag            = Convert.ToInt32(dr["C017"]);
                scoreSheet.Description       = dr["C019"].ToString();
                scoreSheet.CalAdditionalItem = dr["C020"].ToString() != "N";
                scoreSheet.UsePointSystem    = dr["C021"].ToString() != "N";
                string strScoreWidth = dr["C101"].ToString();
                string strTipWidth = dr["C102"].ToString();
                double intScoreWidth, intTipWidth;
                if (double.TryParse(strScoreWidth, out intScoreWidth))
                {
                    scoreSheet.ScoreWidth = intScoreWidth;
                }
                if (double.TryParse(strTipWidth, out intTipWidth))
                {
                    scoreSheet.TipWidth = intTipWidth;
                }
                scoreSheet.HasAutoStandard  = dr["C103"].ToString() != "N";
                scoreSheet.AllowModifyScore = dr["C104"].ToString() != "N";

                #region 子项
                if (scoreID == "0")
                {
                    scoreID = string.Empty;
                }
                else
                {
                    scoreID = string.Format(" AND T3109.C003={0}", scoreID);
                }
                //加载子项
                optReturn = LoadScoreItem(session, scoreSheet, scoreID);
                if (!optReturn.Result)
                {
                    return(optReturn);
                }
                List <ScoreItem> listItems = optReturn.Data as List <ScoreItem>;
                if (listItems == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("ListItems is null");
                    return(optReturn);
                }
                for (int i = 0; i < listItems.Count; i++)
                {
                    ScoreItem scoreItem = listItems[i];
                    scoreSheet.Items.Add(scoreItem);
                }
                scoreSheet.Items = scoreSheet.Items.OrderBy(i => i.OrderID).ToList();

                #endregion 子项


                #region 样式

                OperationReturn styleReturn;
                styleReturn = LoadVisualStyle(session, scoreSheet, "T");
                if (!styleReturn.Result)
                {
                    if (styleReturn.Code != Defines.RET_NOT_EXIST)
                    {
                        return(styleReturn);
                    }
                    scoreSheet.TitleStyle = null;
                }
                else
                {
                    VisualStyle style = styleReturn.Data as VisualStyle;
                    if (style != null)
                    {
                        style.ScoreSheet      = scoreSheet;
                        scoreSheet.TitleStyle = style;
                    }
                }

                styleReturn = LoadVisualStyle(session, scoreSheet, "P");
                if (!styleReturn.Result)
                {
                    if (styleReturn.Code != Defines.RET_NOT_EXIST)
                    {
                        return(styleReturn);
                    }
                    scoreSheet.PanelStyle = null;
                }
                else
                {
                    VisualStyle style = styleReturn.Data as VisualStyle;
                    if (style != null)
                    {
                        style.ScoreSheet      = scoreSheet;
                        scoreSheet.PanelStyle = style;
                    }
                }

                #endregion


                #region 备注

                OperationReturn commentReturn;
                commentReturn = LoadComment(session, scoreSheet);
                if (!commentReturn.Result)
                {
                    return(commentReturn);
                }
                List <Comment> listComments = commentReturn.Data as List <Comment>;
                if (listComments == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("listComments is null");
                    return(optReturn);
                }
                for (int i = 0; i < listComments.Count; i++)
                {
                    Comment comment = listComments[i];
                    scoreSheet.Comments.Add(comment);
                }
                scoreSheet.Comments = scoreSheet.Comments.OrderBy(j => j.OrderID).ToList();

                #endregion


                #region 控制项

                OperationReturn controlReturn;
                controlReturn = LoadControlItem(session, scoreSheet);
                if (!controlReturn.Result)
                {
                    return(controlReturn);
                }
                List <ControlItem> listControlItems = controlReturn.Data as List <ControlItem>;
                if (listControlItems == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("ListCotnrolItems is null");
                    return(optReturn);
                }
                for (int i = 0; i < listControlItems.Count; i++)
                {
                    ControlItem controlItem = listControlItems[i];
                    scoreSheet.ControlItems.Add(controlItem);
                }
                scoreSheet.ControlItems = scoreSheet.ControlItems.OrderBy(j => j.OrderID).ToList();
                #endregion

                optReturn.Data = scoreSheet;
            }
            catch (Exception ex)
            {
                optReturn.Result  = false;
                optReturn.Code    = Defines.RET_FAIL;
                optReturn.Message = ex.Message;
            }
            return(optReturn);
        }
예제 #31
0
 public async Task UpdateComment(Comment comment)
 {
 }
예제 #32
0
 public CommentGraphType(Comment data)
 {
     this.data = data;
 }
예제 #33
0
 /// <summary>
 /// 增加一条数据
 /// </summary>
 public long Add(Comment model)
 {
     return(dal.Add(model));
 }
 public Comment Post([FromBody] Comment value)
 {
     return(_CommentManager.Add(value));
 }
 public bool Post([FromBody] Comment newComment)
 {
     newComment.CreatedAt = DateTime.UtcNow;
     commentRepo.Create(newComment);
     return(true);
 }
예제 #36
0
        public async Task <IHttpActionResult> DeleteService([FromUri] int serviceId)
        {
            Service service = unitOfWork.Services.Get(serviceId);

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

            RAIdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (UserManager.IsInRole(user.Id, "Manager") && !UserManager.IsInRole(user.Id, "Admin"))
            {
                if (service.Creator != user.Id)
                {
                    return(BadRequest("Access denied."));
                }
            }

            List <long> branchOfficeIds = new List <long>();

            if (service.BranchOfficces != null)
            {
                foreach (BranchOffice branchOffice in service.BranchOfficces)
                {
                    branchOfficeIds.Add(branchOffice.Id);
                    ImageHelper.DeleteImage(branchOffice.Image);
                }
            }

            List <long> vehiclesIds = new List <long>();

            if (service.Vehicles != null)
            {
                foreach (Vehicle vehicle in service.Vehicles)
                {
                    vehiclesIds.Add(vehicle.Id);
                    ImageHelper.DeleteImages(vehicle.Images);
                }
            }

            List <long> commentIds = new List <long>();

            if (service.Comments != null)
            {
                foreach (Comment comment in service.Comments)
                {
                    commentIds.Add(comment.Id);
                }
            }

            List <long> raitingIds = new List <long>();

            if (service.Ratings != null)
            {
                foreach (Rating rating in service.Ratings)
                {
                    raitingIds.Add(rating.Id);
                }
            }

            ImageHelper.DeleteImage(service.LogoImage);

            try
            {
                lock (lockObjectForServices)
                {
                    foreach (long branchOfficeId in branchOfficeIds)
                    {
                        BranchOffice branchOffice = unitOfWork.BranchOffices.Get(branchOfficeId);
                        unitOfWork.BranchOffices.Remove(branchOffice);
                    }

                    foreach (long vehicleId in vehiclesIds)
                    {
                        Vehicle vehicle = unitOfWork.Vehicles.Get(vehicleId);
                        unitOfWork.Vehicles.Remove(vehicle);
                    }

                    foreach (long commentId in commentIds)
                    {
                        Comment comment = unitOfWork.Comments.Get(commentId);
                        unitOfWork.Comments.Remove(comment);
                    }

                    foreach (long raitingId in raitingIds)
                    {
                        Rating raiting = unitOfWork.Ratings.Get(raitingId);
                        unitOfWork.Ratings.Remove(raiting);
                    }

                    unitOfWork.Services.Remove(service);
                    unitOfWork.Complete();
                }
            }
            catch (DBConcurrencyException)
            {
                if (!ServiceExists(service.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Ok("Service successfully deleted."));
        }
예제 #37
0
 public void Post([FromBody] Comment comment)
 {
     _commentService.AddComment(comment);
 }
예제 #38
0
 public override void VisitComment(Comment comment)
 {
     new CommentBlock(this, comment).Emit();
 }
 /// <summary>
 /// Creates a new instance of <see cref="WaveImpactAsphaltCoverWaveConditionsCalculation"/>.
 /// </summary>
 public WaveImpactAsphaltCoverWaveConditionsCalculation()
 {
     Name            = RiskeerCommonDataResources.Calculation_DefaultName;
     InputParameters = new WaveConditionsInput();
     Comments        = new Comment();
 }
예제 #40
0
		public void SaveComment(Comment comment)
		{
			comment.ContentItem.Comments.Add(comment);
			this._commonDao.SaveObject(comment);
		}
예제 #41
0
 /// <summary>
 /// 更新一条数据
 /// </summary>
 public bool Update(Comment model)
 {
     return(dal.Update(model));
 }
예제 #42
0
		public void DeleteComment(Comment comment)
		{
			comment.ContentItem.Comments.Remove(comment);
			this._commonDao.DeleteObject(comment);
		}
예제 #43
0
        protected override void Seed(DataBaseContext context)
        {
            //adding admin user
            EverNoteUser admin = new EverNoteUser()
            {
                Name = "hasan",
                Surname = "gurhan",
                Email = "*****@*****.**",
                ActivateGuid = Guid.NewGuid(),
                IsActivite = true,
                Username = "******",
                ProfileImageFilename = "User.png",
                Password = "******",
                CreatedOn = DateTime.Now,
                ModifiedOn = DateTime.Now.AddMinutes(5),
                ModifiedUsername = "******"


            };
            //adding standart user
            EverNoteUser standartUser = new EverNoteUser()
            {
                Name = "ipsadsadek",
                Surname = "gurhsadasdan",
                Email = "*****@*****.**",
                ActivateGuid = Guid.NewGuid(),
                IsActivite = true,
                Username = "******",
                ProfileImageFilename = "User.png",
                Password = "******",
                CreatedOn = DateTime.Now,
                ModifiedOn = DateTime.Now.AddMinutes(5),
                ModifiedUsername = "******"


            };
            context.EvernoteUsers.Add(admin);
            context.EvernoteUsers.Add(standartUser);
            for (int i = 0; i < 8; i++)
            {
                EverNoteUser user = new EverNoteUser()
                {
                    Name = FakeData.NameData.GetFirstName(),
                    Surname = FakeData.NameData.GetSurname(),
                    Email = FakeData.NetworkData.GetEmail(),
                    ActivateGuid = Guid.NewGuid(),
                    IsActivite = true,
                    Username = $"user{i}",
                    ProfileImageFilename = "User.png",
                    Password = "******",
                    CreatedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now),
                    ModifiedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now),
                    ModifiedUsername = $"user{i}",


                };
                context.EvernoteUsers.Add(user);
            }
        
            context.SaveChanges();
            //userlist for using ...
            List<EverNoteUser> userlist = context.EvernoteUsers.ToList();
            // fake data categories
            for (int i= 0; i < 10; i++)
            {
                Category cat = new Category()
                {
                    Title = FakeData.PlaceData.GetStreetName(),
                    Description = FakeData.PlaceData.GetAddress(),
                    CreatedOn = DateTime.Now,
                    ModifiedOn = DateTime.Now,
                    ModifiedUsername = "******"

                };
                context.Categories.Add(cat);
                //adding fake notes
                for (int k = 0;  k < FakeData.NumberData.GetNumber(5,9); k++)
                {
                    EverNoteUser owner = userlist[FakeData.NumberData.GetNumber(0, userlist.Count - 1)];

                    Note note = new Note()
                    {
                        Title = FakeData.TextData.GetAlphabetical(FakeData.NumberData.GetNumber(5, 25)),
                        Text = FakeData.TextData.GetSentences(FakeData.NumberData.GetNumber(1, 3)),
                        Category = cat,
                        IsDraft = false,
                        LikeCount = FakeData.NumberData.GetNumber(1, 9),
                        Owner = owner,
                        CreatedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now),
                        ModifiedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now),
                        ModifiedUsername = owner.Username,

                    };
                    cat.Notes.Add(note);
                    //adding fake comments
                    for (int j = 0; j < FakeData.NumberData.GetNumber(3, 5); j++)
                    {
                        EverNoteUser comment_owner = userlist[FakeData.NumberData.GetNumber(0, userlist.Count - 1)];
                        Comment comment = new Comment()
                        {
                            Text = FakeData.TextData.GetSentence(),
                            Owner = comment_owner,
                            CreatedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now),
                            ModifiedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now),
                            ModifiedUsername = comment_owner.Username,

                        };
                        note.Commnets.Add(comment);
                    }
                        //adding fake like
                       
                        for (int m = 0; m < note.LikeCount; m++)
                        {
                            Liked liked = new Liked()
                            {
                                LikedUser = userlist[m]
                            };
                            note.Likes.Add(liked);
                        }
                }
            }
            context.SaveChanges();
        }
예제 #44
0
        private void AddComment(/*Paragraph textPart, */ Run textPoint, string comment)
        {
            Paragraph textPart = textPoint.Parent as Paragraph;

            if (textPart == null)
            {
                return;
            }
            Comments comments = null;
            string   id       = "0";

            // Verify that the document contains a
            // WordProcessingCommentsPart part; if not, add a new one.
            if (_document.MainDocumentPart.GetPartsCountOfType <WordprocessingCommentsPart>() > 0)
            {
                comments =
                    _document.MainDocumentPart.WordprocessingCommentsPart.Comments;
                if (comments.HasChildren)
                {
                    // Obtain an unused ID.
                    id = comments.Descendants <Comment>().Select(e => e.Id.Value).Max();
                }
            }
            else
            {
                // No WordprocessingCommentsPart part exists, so add one to the package.
                WordprocessingCommentsPart commentPart =
                    _document.MainDocumentPart.AddNewPart <WordprocessingCommentsPart>();
                commentPart.Comments = new Comments();
                comments             = commentPart.Comments;
            }

            // Compose a new Comment and add it to the Comments part.
            Paragraph p   = new Paragraph(new Run(new Text(comment)));
            Comment   cmt =
                new Comment()
            {
                Id       = id,
                Author   = _author,
                Initials = _initials,
                Date     = DateTime.Now
            };

            cmt.AppendChild(p);
            comments.AppendChild(cmt);
            comments.Save();
            //Коммент ставить перед Runnom

            // Specify the text range for the Comment.
            // Insert the new CommentRangeStart before the first run of paragraph.
            textPart.InsertBefore(new CommentRangeStart()
            {
                Id = id
            }, textPoint);
            var cmtEnd = textPart.InsertAfter(new CommentRangeEnd()
            {
                Id = id
            }, textPoint);

            // Insert the new CommentRangeEnd after last run of paragraph.


            // Compose a run with CommentReference and insert it.
            textPart.InsertAfter(new Run(new CommentReference()
            {
                Id = id
            }), cmtEnd);
        }
예제 #45
0
        static void Main(string[] args)
        {
            //CLASS VECTOR

            Console.WriteLine("Número de Produtos");
            int n = int.Parse(Console.ReadLine());

            Produto[] vect = new Produto[n];
            for (int i = 0; i < n; i++)
            {
                Console.WriteLine("Nome do produto");
                string nome = Console.ReadLine();
                Console.WriteLine("Preço do produto");
                double price = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
                vect[i] = new Produto {
                    Nome = nome, Price = price
                };
            }
            for (int i = 0; i < n; i++)
            {
                Console.WriteLine(vect[i].Nome + "," + vect[i].Price);
                Console.WriteLine("----------------------------------------------------------------");
            }
            double soma = 0.0;

            for (int i = 0; i < n; i++)
            {
                soma += vect[i].Price;
            }
            Console.WriteLine(soma.ToString("F2", CultureInfo.InvariantCulture));

            //
            //
            // CLASS DATETIME

            DateTime d6 = DateTime.Parse("2000-08-15");

            Console.WriteLine(d6);
            DateTime d7 = DateTime.Parse("15/12/2015");

            Console.WriteLine(d7);
            DateTime d8 = DateTime.ParseExact("200-12-08", "yyyy,MM,dd", CultureInfo.InvariantCulture);

            Console.WriteLine(d8);
            TimeSpan t1  = new TimeSpan();
            TimeSpan t2  = new TimeSpan(9000000000L);
            TimeSpan t3  = new TimeSpan(2, 11, 21);
            TimeSpan t4  = new TimeSpan(1, 2, 11, 21);
            TimeSpan t5  = new TimeSpan(1, 2, 11, 21, 321);
            TimeSpan t6  = TimeSpan.FromDays(1.5);
            TimeSpan t7  = TimeSpan.FromHours(1.5);
            TimeSpan t8  = TimeSpan.FromMinutes(1.5);
            TimeSpan t9  = TimeSpan.FromSeconds(1.5);
            TimeSpan t10 = TimeSpan.FromTicks(9000000000L);

            Console.WriteLine(t1);
            Console.WriteLine(t2);
            Console.WriteLine(t3);
            Console.WriteLine(t4);
            Console.WriteLine(t5);
            Console.WriteLine(t6);
            Console.WriteLine(t7);
            Console.WriteLine(t8);
            Console.WriteLine(t9);
            Console.WriteLine(t10);

            DateTime d1 = DateTime.Now;

            Console.WriteLine(d1);
            Console.WriteLine(d1.Ticks);
            DateTime d2 = new DateTime(2021, 03, 17);
            DateTime d3 = new DateTime(2021, 03, 17, 16, 02, 3);
            DateTime d4 = DateTime.Today;
            DateTime d5 = DateTime.UtcNow;

            Console.WriteLine(d2);
            Console.WriteLine(d3);
            Console.WriteLine(d4);
            Console.WriteLine(d5);
            //
            //
            //CLASS MATRIZ
            Console.WriteLine("Matriz is size:");
            int n1 = int.Parse(Console.ReadLine());

            int[,] mat1 = new int[n1, n1];
            for (int i = 0; i < n1; i++)
            {
                Console.WriteLine(i + "º" + "Line:");
                string[] values = Console.ReadLine().Split(' ');
                for (int j = 0; j < n1; j++)
                {
                    mat1[i, j] = int.Parse(values[j]);
                }
            }
            for (int i = 0; i < n1; i++)
            {
                Console.WriteLine("Diagonal : " + "[" + mat1[i, i] + "]");
            }
            for (int i = 0; i < n1; i++)
            {
                for (int j = 0; j < n1; j++)
                {
                    Console.Write("[" + mat1[i, j] + "]");
                    if (j == n1 - 1)
                    {
                        Console.WriteLine();
                    }
                }
            }
            int count = 0;

            for (int i = 0; i < n1; i++)
            {
                for (int j = 0; j < n1; j++)
                {
                    if (mat1[i, j] < 0)
                    {
                        Console.WriteLine("Number:" + "[" + mat1[i, j] + "]");
                        count++;
                    }
                }
            }
            Console.WriteLine("Negative numbers" + count);

            //
            //
            //String Builder

            Comment c1 = new Comment("Have a nice trip");
            Comment c2 = new Comment("Wow that's awesome");
            Post    p1 = new Post(
                DateTime.Parse("21/06/2018 13:05:45"),
                "Traveling to New Zealand",
                "Im going to visit this wonderful country",
                12);

            p1.addComent(c1);
            p1.addComent(c2);
            Console.WriteLine(p1);
            //
            //
            //
            //SWITCH
            Console.WriteLine("Number");
            int    x = int.Parse(Console.ReadLine());
            string day;

            switch (x)
            {
            case 1:
                day = "MONDAY";
                break;

            case 2:
                day = "Tuesday";
                break;

            default:
                day = "Invalido";
                break;
            }
            Console.WriteLine(day);
            Console.WriteLine("-------------------------------------------------------------------------");


            //EXPRESSÃO CONDICIONAL
            Console.WriteLine("Preço:");
            double preco = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
            double desconto;

            if (preco < 20.00)
            {
                desconto = preco * 0.1;
            }
            else
            {
                desconto = preco * 0.05;
            }
            Console.WriteLine(desconto);
            Console.WriteLine("-------------------------------------------------------------------------");
            Console.WriteLine("Preço:");
            double preco2    = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
            double desconto2 = (preco < 20.00) ? preco2 * 0.1 : preco2 * 0.05;

            Console.WriteLine(desconto2);
        }
예제 #46
0
 public Task <Comment> CreateAsync(Comment comment)
 {
     comment.Id = comments.Max(p => p.Id) + 1;
     comments.Add(comment);
     return(Task.FromResult(comment));
 }
예제 #47
0
 public int SaveComment(Comment comment)
 {
     _context.Comments.Add(comment);
     return(_context.SaveChanges());
 }
예제 #48
0
        public async Task <Comment> Add(Comment entity)
        {
            entity = await _repository.CreateAsync(entity);

            return(entity);
        }
예제 #49
0
        public void Load(string uri, int vposShift, int startPos, int endPos)
        {
            XmlReader      xr     = XmlReader.Create(uri);
            List <Comment> result = new List <Comment>();
            List <Perm>    perms  = new List <Perm>();
            List <Vote>    votes  = new List <Vote>();

            if (xr == null)
            {
                return;
            }

            int     count = 0;
            Comment cmt   = null;
            Vote    vote  = null;
            Perm    perm  = null;

            while (xr.Read())
            {
                if (xr.ReadToFollowing("chat"))
                {
                    int vpos = int.Parse(xr.GetAttribute("vpos")) - startPos + vposShift;
                    if (vpos < -10 || vpos > endPos + 10)
                    {
                        continue;
                    }

                    int      premium = int.Parse(xr.GetAttribute("premium") ?? "0");
                    string   mail    = xr.GetAttribute("mail") ?? "";
                    string[] mails   = mail.ToLower().Split(' ');
                    cmt = new Comment()
                    {
                        Count = count,
                        //Number = int.Parse(xr.GetAttribute("no")),
                        Vpos = vpos,
                        //Mail = xr.GetAttribute("mail") ?? "",
                        Mails = mails,
                        Text  = xr.ReadString()
                    };
                    bool add = true;

                    if (cmt.Text.StartsWith("/hb"))
                    {
                        continue;
                    }
                    if (cmt.Text.Contains("\n"))// Environment.NewLine
                    {
                        cmt.IsAA = true;
                    }

                    if (premium >= 3)
                    {
                        cmt.Text = Comment.StripHtmlTags(cmt.Text);
                        add      = false;

                        if (cmt.Text.StartsWith("/clear") || cmt.Text.StartsWith("/cls"))
                        {
                            if (perm != null)
                            {
                                double endTime = cmt.Vpos / 100.0;
                                if (perm.StartTime + 180.0 >= endTime)
                                {
                                    perm.EndTime = endTime;
                                }
                                perm = null;
                            }
                        }
                        else if (cmt.Text.StartsWith("/vote "))
                        {
                            //start showresult stop
                            cmt.IsVote = true;
                            cmt.Text   = cmt.Text.Substring(6);
                            if (cmt.Text.StartsWith("start "))
                            {
                                if (vote != null)
                                {
                                    votes.Add(vote);
                                }
                                vote             = new Vote();
                                vote.VoteComment = cmt;
                                vote.StartTime   = cmt.Vpos / 100.0;
                                vote.ResultTime  = (cmt.Vpos / 100.0) + 10.0; //temp
                                vote.EndTime     = (cmt.Vpos / 100.0) + 10.0; //temp
                            }
                            else if (cmt.Text.StartsWith("showresult "))
                            {
                                if (vote != null)
                                {
                                    vote.ResultComment = cmt;
                                    vote.ResultTime    = (cmt.Vpos / 100.0);
                                    vote.EndTime       = (cmt.Vpos / 100.0) + 10.0; //temp
                                }
                            }
                            else if (cmt.Text.StartsWith("stop"))
                            {
                                if (vote != null)
                                {
                                    vote.EndTime = cmt.Vpos / 100.0;
                                    votes.Add(vote);
                                    vote = null;
                                }
                            }
                        }
                        else
                        {
                            if (cmt.Text.StartsWith("/perm "))
                            {
                                cmt.Text = cmt.Text.Substring(6);
                            }
                            cmt.IsPerm     = true;
                            perm           = new Perm();
                            perm.Comment   = cmt;
                            perm.StartTime = cmt.Vpos / 100.0 - 3;  //ちょっと早めに出す
                            perm.EndTime   = perm.StartTime + 12.0; //temp

                            perms.Add(perm);
                        }
                    }
                    if (add)
                    {
                        result.Add(cmt);
                    }
                    count++;
                }
            }

            if (vote != null)
            {
                votes.Add(vote);
            }

            result.Sort((a, b) =>
            {
                return(a.Vpos >= b.Vpos ? 1 : -1);
            });
            //逆順
            votes.Sort((a, b) =>
            {
                return(a.StartTime >= b.StartTime ? -1 : 1);
            });
            perms.Sort((a, b) =>
            {
                return(a.StartTime >= b.StartTime ? -1 : 1);
            });

            Comments = result.ToArray();
            Perms    = perms.ToArray();
            Votes    = votes.ToArray();
        }
 public void AddComment(Comment comment)
 {
     var coleccion = ConnectionManager.GetBookCollection();
 }
예제 #51
0
        public ActionResult Comment(string document, Comment c)
        {
            if (document != null)
            {
                if (c.Comment1 != null)
                {
                    int documentIdToFind = 0;
                    try
                    {
                        documentIdToFind = Convert.ToInt32(new Encryption().DecryptString(document, User.Identity.Name));
                    }
                    catch (FormatException fe)
                    {
                        TempData["error_message"] = "Document does not exist";

                        new LogsOperations().AddLog(
                            new Log()
                        {
                            Controller = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString(),
                            Exception  = fe.Message,
                            Time       = DateTime.Now,
                            Message    = "User tried to manually search for a document in the address bar"
                        }
                            );
                        return(RedirectToAction("Index"));
                    }
                    catch (Exception ex)
                    {
                        TempData["error_message"] = "Document unavailable";
                        new LogsOperations().AddLog(
                            new Log()
                        {
                            Controller = "Comment",
                            Exception  = ex.Message,
                            Time       = DateTime.Now,
                            Message    = "documentId decryption error"
                        }
                            );
                        return(RedirectToAction("Index"));
                    }

                    DocumentsOperations dops = new DocumentsOperations();
                    if (dops.DoesDocumentExist(documentIdToFind))
                    {
                        try
                        {
                            Document d = dops.GetDocument(documentIdToFind);
                            if (dops.IsReviewerAllocatedToDocument(User.Identity.Name, documentIdToFind))
                            {
                                ViewData["document_id"] = new Encryption().EncryptString(d.Id.ToString(), User.Identity.Name);
                                try
                                {
                                    dops.AddComment(d, c, User.Identity.Name);
                                    ModelState.Clear();
                                }
                                catch (Exception ex)
                                {
                                    ViewData["error_message"] = ex.Message;
                                    new LogsOperations().AddLog(
                                        new Log()
                                    {
                                        Controller = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString(),
                                        Exception  = ex.Message,
                                        Time       = DateTime.Now,
                                        Message    = "Adding comment exception"
                                    }
                                        );

                                    return(RedirectToAction("Review"));
                                }

                                return(View());
                            }
                            else
                            {
                                TempData["error_message"] = "You are not a reviewer of this document";
                                new LogsOperations().AddLog(
                                    new Log()
                                {
                                    Controller = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString(),
                                    Exception  = "User is not document's reviewer",
                                    Time       = DateTime.Now,
                                    Message    = "User is not document's reviewer"
                                }
                                    );
                                return(RedirectToAction("Review"));
                            }
                        }
                        catch (DocumentExistsException ex)
                        {
                            TempData["error_message"] = ex.Message;
                            new LogsOperations().AddLog(
                                new Log()
                            {
                                Controller = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString(),
                                Exception  = ex.Message,
                                Time       = DateTime.Now,
                                Message    = ex.Message
                            }
                                );

                            return(RedirectToAction("Review"));
                        }
                        catch (Exception ex)
                        {
                            TempData["error_message"] = ex.Message;
                            new LogsOperations().AddLog(
                                new Log()
                            {
                                Controller = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString(),
                                Exception  = ex.Message,
                                Time       = DateTime.Now,
                                Message    = "Error checking reviewing permissions"
                            }
                                );

                            return(RedirectToAction("Review"));
                        }
                    }
                    else
                    {
                        TempData["error_message"] = "Document does not exist";
                        new LogsOperations().AddLog(
                            new Log()
                        {
                            Controller = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString(),
                            Exception  = "Document does not exist",
                            Time       = DateTime.Now,
                            Message    = "Document does not exist"
                        }
                            );
                        return(RedirectToAction("Review"));
                    }
                }
                else
                {
                    TempData["error_message"] = "Comment cannot be empty";
                    new LogsOperations().AddLog(
                        new Log()
                    {
                        Controller = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString(),
                        Exception  = "No comment entered",
                        Time       = DateTime.Now,
                        Message    = "No comment entered"
                    }
                        );
                    return(RedirectToAction("Review"));
                }
            }
            else
            {
                TempData["error_message"] = "No document selected";
                new LogsOperations().AddLog(
                    new Log()
                {
                    Controller = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString(),
                    Exception  = "No document selected",
                    Time       = DateTime.Now,
                    Message    = "No document selected"
                }
                    );
                return(RedirectToAction("Review"));
            }

            //DocumentsOperations dops = new DocumentsOperations();
            //Document d = dops.GetDocument(document);
            //ViewData["document_id"] = d.Id;
            //try
            //{
            //    dops.AddComment(d, c, User.Identity.Name);
            //    ModelState.Clear();
            //}
            //catch (Exception ex)
            //{
            //    ViewData["error_message"] = ex.Message;
            //    new LogsOperations().AddLog(
            //        new Log()
            //        {
            //            Controller = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString(),
            //            Exception = ex.Message,
            //            Time = DateTime.Now,
            //            Message = "Adding comment exception"
            //        }
            //    );
            //}
            //return View();
        }
예제 #52
0
        protected override void Seed(DatabaseContext context)
        {
            //adding admin user
            EverNoteUser admin = new EverNoteUser()
            {
                Name                = "Yasin",
                SurName             = "Akdoğan",
                Email               = "*****@*****.**",
                ActivateGuid        = Guid.NewGuid(),
                IsActive            = true,
                IsAdmin             = true,
                UserName            = "******",
                Password            = "******",
                CreatedOn           = DateTime.Now,
                ModifiedOn          = DateTime.Now.AddMinutes(5),
                ModifiedUserName    = "******",
                ProfilImageFileName = "userimg.jfif"
            };
            //adding standart user
            EverNoteUser standartUser = new EverNoteUser()
            {
                Name                = "Ahmet",
                SurName             = "Korkmaz",
                Email               = "*****@*****.**",
                ActivateGuid        = Guid.NewGuid(),
                IsActive            = true,
                IsAdmin             = true,
                UserName            = "******",
                Password            = "******",
                CreatedOn           = DateTime.Now,
                ModifiedOn          = DateTime.Now.AddMinutes(5),
                ModifiedUserName    = "******",
                ProfilImageFileName = "userimg.jfif"
            };

            context.EverNoteUsers.Add(admin);
            context.EverNoteUsers.Add(standartUser);

            //adding fake user
            for (int i = 0; i < 8; i++)
            {
                EverNoteUser fakeUser = new EverNoteUser()
                {
                    Name                = NameData.GetFirstName(),
                    SurName             = NameData.GetSurname(),
                    Email               = NetworkData.GetEmail(),
                    ActivateGuid        = Guid.NewGuid(),
                    IsActive            = true,
                    IsAdmin             = true,
                    UserName            = $"user{i}",
                    Password            = "******",
                    CreatedOn           = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now),
                    ModifiedOn          = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now),
                    ModifiedUserName    = $"user{i}",
                    ProfilImageFileName = "userimg.jfif"
                };
                context.EverNoteUsers.Add(fakeUser);
            }
            context.SaveChanges();

            //User List For Using
            List <EverNoteUser> userList = context.EverNoteUsers.ToList();

            //adding fake Categories
            for (int i = 0; i < 10; i++)
            {
                Category cat = new Category()
                {
                    Title            = PlaceData.GetStreetName(),
                    Description      = PlaceData.GetAddress(),
                    CreatedOn        = DateTime.Now,
                    ModifiedOn       = DateTime.Now,
                    ModifiedUserName = "******"
                };
                context.Categories.Add(cat);
                //adding fake notes
                for (int k = 0; k < NumberData.GetNumber(5, 9); k++)
                {
                    EverNoteUser owner = userList[NumberData.GetNumber(0, userList.Count - 1)];
                    Note         note  = new Note()
                    {
                        Title            = TextData.GetAlphabetical(NumberData.GetNumber(5, 25)),
                        Text             = TextData.GetSentences(NumberData.GetNumber(1, 3)),
                        Category         = cat,
                        IsDraft          = false,
                        LikeCount        = NumberData.GetNumber(1, 9),
                        Owner            = owner,
                        CreatedOn        = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now),
                        ModifiedOn       = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now),
                        ModifiedUserName = owner.UserName
                    };
                    cat.Notes.Add(note);
                    //adding fake comment
                    for (int j = 0; j < NumberData.GetNumber(3, 5); j++)
                    {
                        EverNoteUser comment_owner = userList[NumberData.GetNumber(0, userList.Count - 1)];
                        Comment      comment       = new Comment()
                        {
                            Text             = TextData.GetSentence(),
                            Owner            = comment_owner,
                            CreatedOn        = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now),
                            ModifiedOn       = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now),
                            ModifiedUserName = comment_owner.UserName,
                            //Note=note
                        };
                        note.Comments.Add(comment);
                        //adding fake Likes
                        for (int m = 0; m < note.LikeCount; m++)
                        {
                            Liked liked = new Liked()
                            {
                                LikedUser = userList[m]
                            };
                            note.Likes.Add(liked);
                        }
                    }
                }
                context.SaveChanges();
            }
        }
예제 #53
0
 public void CreateComment([FromBody] Comment comment)
 {
     context.Comments.Add(comment);
     context.SaveChanges();
 }
예제 #54
0
 public ActionResult EditComment(Comment comment)
 {
     com.Entry(comment).State = EntityState.Modified;
     com.SaveChanges();
     return(RedirectToAction("Comments"));
 }
예제 #55
0
        public void Initialize()
        {
            context.Database.Migrate();

            if (!this.roleManager.Roles.Any(x => x.Name == "Admin" || x.Name == "User"))
            {
                this.roleManager.CreateAsync(new Role {
                    Name = "Admin"
                }).Wait();
                this.roleManager.CreateAsync(new Role {
                    Name = "User"
                }).Wait();

                var category = new Category()
                {
                    Name        = "IT",
                    Description = "Information technology (IT) is the use of computers to store, retrieve, transmit, and manipulate data, or information, often in the context of a business or other enterprise.",
                    CreatedBy   = "admin",
                    CreatedDate = DateTime.Now
                };

                var category1 = new Category()
                {
                    Name        = "Sport",
                    Description = "Sport is generally recognised as system of activities which are based in physical athleticism or physical dexterity.",
                    CreatedBy   = "admin",
                    CreatedDate = DateTime.Now
                };
                var category2 = new Category()
                {
                    Name        = "Cryptocurrency",
                    Description = "A cryptocurrency (or crypto currency) is a digital asset designed to work as a medium of exchange that uses strong cryptography to secure financial transactions, control the creation of additional units, and verify the transfer of assets. Cryptocurrencies are a kind of alternative currency and digital currency (of which virtual currency is a subset). Cryptocurrencies use decentralized control as opposed to centralized digital currency and central banking systems.",
                    CreatedBy   = "admin",
                    CreatedDate = DateTime.Now
                };
                context.Add(category);
                context.Add(category1);
                context.Add(category2);

                var post1 = new Post
                {
                    Title       = "Bitcoin falls below $5,000",
                    CategoryId  = category2.Id,
                    Slug        = RegexHelper.CreateSlug("Bitcoin falls below $5,000"),
                    Description = "The value of Bitcoin has fallen below $5,000 (£3,889) for the first time since October 2017.",
                    Content     = "<h3>The value of Bitcoin has fallen below $5,000 (£3,889) for the first time since October 2017.</h3><p>The fall brought the total value of all Bitcoin in existence to below $87bn.&nbsp;</p><p>On Thursday, 15 November, Bitcoin Cash - an offshoot of Bitcoin - split into two different crypto-currencies, which are now in competition with each other.&nbsp;</p><p>And some observers have blamed this for creating turmoil in the crypto-currency markets, with many of the digital assets experiencing falls.&nbsp;</p><p>Bitcoin exchange Kraken said in a blog post that it regarded one of the two new Bitcoin Cash crypto-currencies - Bitcoin SV - as \"an extremely risky investment\".&nbsp;</p><p>Bitcoin is a notoriously volatile crypto-currency.&nbsp;</p><p>At its peak, in November 2017, it briefly hit $19,783 - which means the price has fallen by about 75%.&nbsp;</p>",
                    ImagePath   = "~/images/post-img/init_post_img_1.jpg",
                    CreatedBy   = "admin",
                    CreatedDate = DateTime.Now
                };

                var comment = new Comment
                {
                    Content     = "Bitcoin is worse everyday!",
                    Post        = post1,
                    CreatedBy   = "admin",
                    CreatedDate = DateTime.Now
                };

                var post2 = new Post
                {
                    Title       = "Instagram targets fake likes and comments",
                    CategoryId  = category.Id,
                    Slug        = RegexHelper.CreateSlug("Instagram targets fake likes and comments"),
                    Description = "Photo-sharing platform Instagram has announced a new initiative that will target fake likes and comments.",
                    Content     = "<h3>Photo-sharing platform Instagram has announced a new initiative that will target fake likes and comments.</h3><p>The fall brought the total value of all Bitcoin in existence to below $87bn.&nbsp;</p><p>The company say they have developed tools that can identify accounts that use third-party services and apps to artificially boost their popularity.&nbsp;</p><p>Any accounts violating will be warned and told to change their password.&nbsp;</p><p>Since its launch in 2010, Instagram has become a tool for online influencers to amass large followings and often, in turn, get paid to market products.&nbsp;</p><p>Payment for this form of advertising is often scaled by the size of the influencers online audience and engagements but an online investigation by marketing agency Mediakiz last year showed just how easy it is to become a fake influencer.&nbsp;</p><p>Some popular apps utilised by users to boost their followings have been recently shut down, but others that pay monthly subscription fees are still available, website Techcrunch reports.&nbsp;</p>",
                    ImagePath   = "~/images/post-img/init_post_img_2.jpg",
                    CreatedBy   = "admin",
                    CreatedDate = DateTime.Now
                };

                var post3 = new Post
                {
                    Title       = "Blackout for thousands of dark web pages",
                    CategoryId  = category.Id,
                    Slug        = RegexHelper.CreateSlug("Blackout for thousands of dark web pages"),
                    Description = "Hackers have deleted more than 6,500 sites being held on a popular dark web server.",
                    Content     = "<h3>Hackers have deleted more than 6,500 sites being held on a popular dark web server.</h3><p>Called Daniel's Hosting, the site was sitting on the hidden Tor network and many people used it to host pages they did not want to publish on the wider web.</p><p>Administrator Daniel Winzen said no back-ups were kept of the pages it hosted.</p><p>He said the site should be back in service in December.</p><p>\"Around 6,500 hidden services were hosted on the server,\" wrote Mr Winzen in a message put on the welcome page of the web companion to the site.</p><p>\"There is no way to recover from this breach, all data is gone.\"</p><p>Tor, or The Onion Router, is a way of organising web-like pages so it is hard to work out where the information is located and who is running them.</p><p>Web pages sited on the Tor network get a .onion suffix.</p><p>The Tor browser also lets people browse the web in a way that conceals their location and obscures their identity.</p><p>Daniel's Hosting became one of the most popular sites for .onion site owners after the previously biggest host went offline in early 2017.</p>",
                    ImagePath   = "~/images/post-img/init_post_img_3.png",
                    CreatedBy   = "admin",
                    CreatedDate = DateTime.Now
                };

                context.Add(post1);
                context.Add(comment);
                context.Add(post2);
                context.Add(post3);
                context.SaveChangesWithoutAudit();
            }

            var defaultAdminAccount = this.userManager.FindByNameAsync("admin").Result;

            if (defaultAdminAccount == null)
            {
                var user = new User {
                    UserName = "******", Email = "*****@*****.**"
                };
                this.userManager.CreateAsync(user, "Duy@123").Wait();
                this.userManager.AddToRoleAsync(user, "Admin").Wait();
            }
        }
예제 #56
0
        /// <summary>
        /// Returns true if CarInfo instances are equal
        /// </summary>
        /// <param name="other">Instance of CarInfo to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(CarInfo other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Model == other.Model ||
                     Model != null &&
                     Model.Equals(other.Model)
                     ) &&
                 (
                     Year == other.Year ||
                     Year != null &&
                     Year.Equals(other.Year)
                 ) &&
                 (
                     Price == other.Price ||
                     Price != null &&
                     Price.Equals(other.Price)
                 ) &&
                 (
                     SerialNumber == other.SerialNumber ||
                     SerialNumber != null &&
                     SerialNumber.Equals(other.SerialNumber)
                 ) &&
                 (
                     SoldDateUtc == other.SoldDateUtc ||
                     SoldDateUtc != null &&
                     SoldDateUtc.Equals(other.SoldDateUtc)
                 ) &&
                 (
                     Comment == other.Comment ||
                     Comment != null &&
                     Comment.Equals(other.Comment)
                 ) &&
                 (
                     Transmission == other.Transmission ||
                     Transmission != null &&
                     Transmission.Equals(other.Transmission)
                 ) &&
                 (
                     Motor == other.Motor ||
                     Motor != null &&
                     Motor.Equals(other.Motor)
                 ) &&
                 (
                     GarageId == other.GarageId ||
                     GarageId != null &&
                     GarageId.Equals(other.GarageId)
                 ) &&
                 (
                     SellerId == other.SellerId ||
                     SellerId != null &&
                     SellerId.Equals(other.SellerId)
                 ));
        }
 public Comment Put(int id, [FromBody] Comment value)
 {
     return(_CommentManager.Update(id, value));
 }
예제 #58
0
        public async Task <IActionResult> AjaxPostComment(CommentViewModel model)
        {
            // disable status code page for ajax requests
            var statusCodePagesFeature = HttpContext.Features.Get <IStatusCodePagesFeature>();

            if (statusCodePagesFeature != null)
            {
                statusCodePagesFeature.Enabled = false;
            }

            // this should validate the [EmailAddress] on the model
            // failure here should indicate invalid email since it is the only attribute in use
            if (!ModelState.IsValid)
            {
                Response.StatusCode = 403;
                await Response.WriteAsync("Please enter a valid e-mail address");

                return(new EmptyResult());
            }

            var project = await projectService.GetCurrentProjectSettings();

            if (project == null)
            {
                log.LogDebug("returning 500 blog not found");
                Response.StatusCode = 500;
                return(new EmptyResult());
            }

            if (string.IsNullOrEmpty(model.PostId))
            {
                log.LogDebug("returning 500 because no postid was posted");
                Response.StatusCode = 500;
                return(new EmptyResult());
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                log.LogDebug("returning 403 because no name was posted");
                Response.StatusCode = 403;
                await Response.WriteAsync("Please enter a valid name");

                return(new EmptyResult());
            }

            if (string.IsNullOrEmpty(model.Content))
            {
                log.LogDebug("returning 403 because no content was posted");
                Response.StatusCode = 403;
                await Response.WriteAsync("Please enter a valid content");

                return(new EmptyResult());
            }

            var blogPost = await blogService.GetPost(model.PostId);

            if (blogPost == null)
            {
                log.LogDebug("returning 500 blog post not found");
                Response.StatusCode = 500;
                return(new EmptyResult());
            }

            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                if (!string.IsNullOrEmpty(project.RecaptchaPublicKey))
                {
                    var captchaResponse = await this.ValidateRecaptcha(Request, project.RecaptchaPrivateKey);

                    if (!captchaResponse.Success)
                    {
                        log.LogDebug("returning 403 captcha validation failed");
                        Response.StatusCode = 403;
                        await Response.WriteAsync("captcha validation failed");

                        return(new EmptyResult());
                    }
                }
            }

            var userAgent = HttpContext.Request.Headers["User-Agent"].ToString();

            var canEdit = await User.CanEditBlog(project.Id, authorizationService);

            var isApproved = canEdit;

            if (!isApproved)
            {
                isApproved = !project.ModerateComments;
            }

            var comment = new Comment()
            {
                Id        = Guid.NewGuid().ToString(),
                Author    = model.Name,
                Email     = model.Email,
                Website   = GetUrl(model.WebSite),
                Ip        = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(),
                UserAgent = userAgent,
                IsAdmin   = User.CanEditProject(project.Id),
                Content   = System.Text.Encodings.Web.HtmlEncoder.Default.Encode(
                    model.Content.Trim()).Replace("\n", "<br />"),

                IsApproved = isApproved,
                PubDate    = DateTime.UtcNow
            };

            blogPost.Comments.Add(comment);
            await blogService.Update(blogPost);

            // TODO: clear cache

            //no need to send notification when project owner posts a comment, ie in response
            var shouldSendEmail = !canEdit;

            if (shouldSendEmail)
            {
                var postUrl = await blogService.ResolvePostUrl(blogPost);

                var baseUrl = string.Concat(HttpContext.Request.Scheme,
                                            "://",
                                            HttpContext.Request.Host.ToUriComponent());

                postUrl = baseUrl + postUrl;

                emailService.SendCommentNotificationEmailAsync(
                    project,
                    blogPost,
                    comment,
                    postUrl,
                    postUrl,
                    postUrl
                    ).Forget(); //async but don't want to wait
            }

            var viewModel = new BlogViewModel();

            viewModel.ProjectSettings = project;
            viewModel.BlogRoutes      = blogRoutes;
            viewModel.CurrentPost     = blogPost;
            viewModel.TmpComment      = comment;
            viewModel.TimeZoneHelper  = timeZoneHelper;
            viewModel.TimeZoneId      = viewModel.ProjectSettings.TimeZoneId;


            viewModel.CanEdit = canEdit;

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