Esempio n. 1
0
    private void PageBind(int id)
    {
        MessageSendModel message = MessageSendBLL.GetMessageSendById(id);

        this.txtBianhao.Text = message.Receive;
        this.content1.Value  = message.Content;
        this.txtTitle.Text   = message.InfoTitle;
        this.drop_LoginRole.SelectedValue = message.LoginRole;
        this.DropDownList1.Enabled        = false;
        this.DropDownList2.Enabled        = false;
        this.DropDownList1.SelectedValue  = message.CountryCode;
        this.DropDownList2.SelectedValue  = message.LanguageCode;

        //this.ChkLevel.Checked=(message.ConditionLevel != -1);
        this.ChkBonus.Checked = (message.ConditionBonusFrom != -1 && message.ConditionBonusTo != -1);
        this.ChkNet.Checked   = (message.ConditionLeader != "");

        this.BindDropLevel();
        this.SetVisible();
        //this.DropLevel.SelectedValue = message.ConditionLevel.ToString();
        this.TxtBonusFrom.Text          = message.ConditionBonusFrom.ToString();
        this.TxtBonusTo.Text            = message.ConditionBonusTo.ToString();
        this.TxtLeader.Text             = message.ConditionLeader.ToString();
        this.DropRelation.SelectedValue = message.ConditionRelation.ToString();
    }
Esempio n. 2
0
 /// <summary>
 /// 发布公告
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 public static bool Addsendaffiche(MessageSendModel message)
 {
     SqlParameter[] param = new SqlParameter[] {
         new SqlParameter("@LoginRole", message.LoginRole),
         new SqlParameter("@Receive", message.Receive),
         new SqlParameter("@InfoTitle", message.InfoTitle),
         new SqlParameter("@Content", message.Content),
         new SqlParameter("@SenderRole", message.SenderRole),
         new SqlParameter("@Sender", message.Sender),
         new SqlParameter("@Sendedate", DateTime.Now.ToUniversalTime()),
         new SqlParameter("@DropFlag", message.DropFlag),
         new SqlParameter("@ReadFlag", message.ReadFlag),
         new SqlParameter("@CountryCode", message.CountryCode),
         new SqlParameter("@LanguageCode", message.LanguageCode),
         new SqlParameter("@ClassID", message.MessageClassID),
         new SqlParameter("@ReplyFor", message.ReplyFor),
         new SqlParameter("@ConditionLevel", message.ConditionLevel),
         new SqlParameter("@ConditionBonusFrom", message.ConditionBonusFrom),
         new SqlParameter("@ConditionBonusTo", message.ConditionBonusTo),
         new SqlParameter("@ConditionLeader", message.ConditionLeader),
         new SqlParameter("@ConditionRelation", message.ConditionRelation),
         new SqlParameter("@Qishu", message.Qishu),
         new SqlParameter("@MessageType", message.MessageType)
     };
     if (DBHelper.ExecuteNonQuery("sendaffiche", param, CommandType.StoredProcedure) > 0)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
        public void GetAllMessages_ShouldReturnCorrectNumberOfMessages()
        {
            using (new TransactionScope())
            {
                var firstResponse  = this.httpServer.CreatePostRequest("/api/users/register", this.firstUser);
                var secondResponse = this.httpServer.CreatePostRequest("/api/users/register", this.secondUser);

                var firstLoggedUser  = this.GetUserFromResponse(firstResponse);
                var secondLoggedUser = this.GetUserFromResponse(secondResponse);

                var message = new MessageSendModel()
                {
                    Content    = "Some content",
                    ReceiverId = secondLoggedUser.Id
                };

                // Send the messages
                var response = this.httpServer.CreatePostRequest(
                    "/api/messages/send?sessionKey=" + firstLoggedUser.SessionKey, message);
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

                response = this.httpServer.CreatePostRequest(
                    "/api/messages/send?sessionKey=" + firstLoggedUser.SessionKey, message);
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

                // Get the messages
                var getAllResponse = this.httpServer.CreateGetRequest(
                    "/api/messages/all?sessionKey=" + firstLoggedUser.SessionKey);
                Assert.AreEqual(HttpStatusCode.OK, getAllResponse.StatusCode);

                var messagesAsString = getAllResponse.Content.ReadAsStringAsync().Result;
                var messages         = JsonConvert.DeserializeObject <IList <MessageModel> >(messagesAsString);
                Assert.AreEqual(2, messages.Count);
            }
        }
        public void SendMessage_TwoValidMessages_ShouldSaveInDatabase()
        {
            using (new TransactionScope())
            {
                var firstResponse  = this.httpServer.CreatePostRequest("/api/users/register", this.firstUser);
                var secondResponse = this.httpServer.CreatePostRequest("/api/users/register", this.secondUser);

                var firstLoggedUser  = this.GetUserFromResponse(firstResponse);
                var secondLoggedUser = this.GetUserFromResponse(secondResponse);

                var message = new MessageSendModel()
                {
                    Content    = "Some content",
                    ReceiverId = secondLoggedUser.Id
                };

                var response = this.httpServer.CreatePostRequest(
                    "/api/messages/send?sessionKey=" + firstLoggedUser.SessionKey, message);
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

                response = this.httpServer.CreatePostRequest(
                    "/api/messages/send?sessionKey=" + firstLoggedUser.SessionKey, message);
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

                var userOne = this.db.Users.GetById(firstLoggedUser.Id);
                Assert.AreEqual(2, userOne.SentMessages.Count);
                Assert.AreEqual(0, userOne.ReceivedMessages.Count);

                var userTwo = this.db.Users.GetById(secondLoggedUser.Id);
                Assert.AreEqual(2, userTwo.ReceivedMessages.Count);
                Assert.AreEqual(0, userTwo.SentMessages.Count);
            }
        }
Esempio n. 5
0
        public void sendMessage(int userId, MessageSendModel model, string keyDialog)
        {
            var db        = new MyDBModels.DB();
            var user      = db.user.Where(u => u.UserId == userId).First();
            var profileId = user.ProfileId;

            var currentCommunication = db.communication.Where(c => c.KeyDialog == keyDialog).First();

            MyDBModels.Message messsage = new MyDBModels.Message();
            messsage.DataMessage     = model.DataMessage;
            messsage.TimeWritten     = model.TimeWritten;
            messsage.IsReadProfileId = new int[] { profileId };
            messsage.ProfileId       = profileId;
            messsage.TypeMessage     = 1;
            db.message.Add(messsage);
            db.SaveChanges();

            var messageIdArray = currentCommunication.MessageIdArray.ToList();

            messageIdArray.Add(db.message.Where(m => m.ProfileId == profileId && m.TimeWritten == model.TimeWritten).FirstOrDefault().MessageId);//OrderByDescending need?
            currentCommunication.MessageIdArray = messageIdArray.ToArray();

            var dataAccess = new CommunicationDataAccess();

            if (!currentCommunication.IsGroup)
            {
                var friendProfileId = currentCommunication.ParticipantProfileIdArray.Where(p => p != profileId).First();
                dataAccess.searchAndConnectOldCommunication(profileId, friendProfileId);
            }

            db.SaveChanges();
        }
Esempio n. 6
0
        /// <summary>
        /// 根据编号查询发件箱信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static MessageSendModel GetMessageSendById(int id)
        {
            SqlParameter[] par = new SqlParameter[]
            {
                new SqlParameter("@id", SqlDbType.Int)
            };
            par[0].Value = id;
            SqlDataReader    reader  = DBHelper.ExecuteReader("getMessageSendById", par, CommandType.StoredProcedure);
            MessageSendModel message = new MessageSendModel();

            if (reader.Read())
            {
                //ConditionLevel, ConditionBonusFrom, ConditionBonusTo, ConditionLeader, ConditionRelation, Qishu
                message.Id                 = Convert.ToInt32(reader["ID"]);
                message.InfoTitle          = reader["InfoTitle"].ToString();
                message.LoginRole          = reader["LoginRole"].ToString();
                message.ReadFlag           = Convert.ToInt32(reader["ReadFlag"].ToString());
                message.Receive            = reader["Receive"].ToString();
                message.Senddate           = Convert.ToDateTime(reader["Senddate"].ToString());
                message.Content            = reader["Content"].ToString();
                message.SenderRole         = reader["SenderRole"].ToString();
                message.Sender             = reader["Sender"].ToString();
                message.DropFlag           = Convert.ToInt32(reader["DropFlag"].ToString());
                message.ConditionLevel     = Convert.ToInt16(reader["ConditionLevel"]);
                message.ConditionBonusFrom = Convert.ToDouble(reader["ConditionBonusFrom"]);
                message.ConditionBonusTo   = Convert.ToDouble(reader["ConditionBonusTo"]);
                message.ConditionLeader    = reader["ConditionLeader"].ToString();
                message.ConditionRelation  = Convert.ToChar(reader["ConditionRelation"]);
                message.Qishu              = Convert.ToInt32(reader["Qishu"]);
            }
            reader.Close();
            return(message);
        }
Esempio n. 7
0
    private void PageBind(int id)
    {
        MessageSendModel message = MessageSendBLL.GetMessageSendById(id);

        this.txtBianhao.Text = message.Receive;
        this.TextBox1.Text   = message.Content;
        this.txtTitle.Text   = message.InfoTitle;
        this.drop_LoginRole.SelectedItem.Value = message.LoginRole;
        this.DropDownList1.Enabled             = false;
        this.DropDownList2.Enabled             = false;
        this.DropDownList1.SelectedValue       = message.CountryCode;
        this.DropDownList2.SelectedValue       = message.LanguageCode;
    }
        public async Task <IActionResult> Contact([FromRoute] string culture, MessageSendModel Message)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    await lawyerDbContext.Messages.AddAsync(new Message
                    {
                        Email          = Message.Email,
                        Name           = Message.Name,
                        MessageContent = Message.Message,
                        Subject        = Message.Subject,
                    });

                    await lawyerDbContext.SaveChangesAsync();

                    return(RedirectToAction(nameof(Contact)));
                }
                catch
                {
                    return(BadRequest());
                }
            }

            try
            {
                int?languageId = DbContextService.GetLanguageIdByShortName(lawyerDbContext, culture);

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

                var contact = (await lawyerDbContext.GetContactViewAsync()).SingleOrDefault(m => m.LanguageId == languageId);

                ContactsViewModel contactsViewModel = new ContactsViewModel
                {
                    Email   = contact.ContactEmail,
                    Number  = contact.ContactNumber,
                    Address = contact.ContactAdress
                };
                return(View(contactsViewModel));
            }
            catch
            {
                return(NotFound());
            }
        }
        public async Task <ActionResult> ContactUser(ContactUserModel model)
        {
            var listing = await _listingService.FindAsync(model.ListingID);

            var userIdCurrent = User.Identity.GetUserId();
            var user          = userIdCurrent.User();

            // Check if user send message to itself, which is not allowed
            if (listing.UserID == userIdCurrent)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[You cannot send message to yourself!]]]";
                return(RedirectToAction("Listing", "Listing", new { id = model.ListingID }));
            }

            // Send message to user
            var message = new MessageSendModel()
            {
                UserFrom  = userIdCurrent,
                UserTo    = listing.UserID,
                Subject   = listing.Title,
                Body      = model.Message,
                ListingID = listing.ID
            };

            await MessageHelper.SendMessage(message);

            // Send email with notification
            var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "privatemessage").SelectAsync();

            var emailTemplate = emailTemplateQuery.Single();

            dynamic email = new Postal.Email("Email");

            email.To      = user.Email;
            email.From    = CacheHelper.Settings.EmailAddress;
            email.Subject = emailTemplate.Subject;
            email.Body    = emailTemplate.Body;
            email.Message = model.Message;
            EmailHelper.SendEmail(email);

            TempData[TempDataKeys.UserMessage] = "[[[Message sent succesfully!]]]";

            return(RedirectToAction("Listing", "Listing", new { id = model.ListingID }));
        }
        public void SendMessage_WhenContentIsNull_ShouldReturnBadRequest()
        {
            using (new TransactionScope())
            {
                var firstResponse  = this.httpServer.CreatePostRequest("/api/users/register", this.firstUser);
                var secondResponse = this.httpServer.CreatePostRequest("/api/users/register", this.secondUser);

                var firstLoggedUser  = this.GetUserFromResponse(firstResponse);
                var secondLoggedUser = this.GetUserFromResponse(secondResponse);

                var message = new MessageSendModel()
                {
                    ReceiverId = secondLoggedUser.Id
                };

                var response = this.httpServer.CreatePostRequest(
                    "/api/messages/send?sessionKey=" + firstLoggedUser.SessionKey, message);
                Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
            }
        }
Esempio n. 11
0
 /// <summary>
 /// 保存邮件
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 public static bool AddMessageSend(MessageSendModel message)
 {
     SqlParameter[] param = new SqlParameter[] {
         new SqlParameter("@LoginRole", message.LoginRole),
         new SqlParameter("@Receive", message.Receive),
         new SqlParameter("@InfoTitle", message.InfoTitle),
         new SqlParameter("@Content", message.Content),
         new SqlParameter("@SenderRole", message.SenderRole),
         new SqlParameter("@Sender", message.Sender),
         new SqlParameter("@DropFlag", message.DropFlag),
         new SqlParameter("@ReadFlag", message.ReadFlag)
     };
     if (DBHelper.ExecuteNonQuery("AddMessageSend", param, CommandType.StoredProcedure) > 0)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Esempio n. 12
0
    //发送系统邮件
    public static bool SendSystemEmail(string sendnumber, string sendrole, string content, string recivenumber)
    {
        MessageSendModel messagesend = new MessageSendModel();

        //邮件保存
        messagesend.Content      = content;
        messagesend.DropFlag     = 0;
        messagesend.InfoTitle    = "系统邮件";
        messagesend.LoginRole    = "2";
        messagesend.ReadFlag     = 0;
        messagesend.Sender       = sendnumber;
        messagesend.SenderRole   = "2";
        messagesend.LanguageCode = "L001";
        messagesend.CountryCode  = "1";
        messagesend.MessageType  = 'm';
        messagesend.Receive      = recivenumber;
        messagesend.SetNoCondition();
        bool bb = MessageSendBLL.Addsendaffiche(messagesend);

        HttpContext.Current.Session["EmailCount"] = AjaxClass.GetNewEmailCount( );
        return(bb);
    }
Esempio n. 13
0
        public HttpResponseMessage SendMessage([FromBody] MessageSendModel model, [FromUri] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var sender   = this.GetUserBySessionKey(sessionKey);
                var receiver = this.db.Users.GetById(model.ReceiverId);

                if (receiver == null)
                {
                    throw new ArgumentException("The 'recieverId' is invalid");
                }

                this.ValidateMessageContent(model.Content);

                var newMessage = new Message()
                {
                    Content  = model.Content,
                    Sender   = sender,
                    Receiver = receiver,
                    PostDate = DateTime.Now
                };

                sender.SentMessages.Add(newMessage);
                receiver.ReceivedMessages.Add(newMessage);

                this.db.Users.Update(sender);
                this.db.Users.Update(receiver);
                this.db.Messages.Add(newMessage);

                this.db.SaveChanges();

                var response = this.Request.CreateResponse(HttpStatusCode.Created);
                return(response);
            });

            return(responseMsg);
        }
Esempio n. 14
0
        public ActionResult Send(MessageSendModel model)
        {
            try
            {
                // TODO: Add insert logic here
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }
                using (DBManager db = new DBManager())
                {
                    int    result;
                    string sXml = model.UserID.ToString();
                    sXml = sXml.Remove(sXml.Length - 1, 1);
                    sXml = sXml.Replace(";", "</ID><ID>");
                    sXml = "<IDs><ID>" + sXml + "</ID></IDs>";
                    string procedureName         = "CPK.uspMessageInsert";
                    List <SqlParameter> paraList = new List <SqlParameter>();
                    paraList.Add(Common.GetParameter("Title", DbType.String, model.Title, ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("Content", DbType.String, model.Content, ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("UserID", DbType.String, "Administrator", ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("Recipient", DbType.String, sXml, ParameterDirection.Input));

                    result = db.GetExecuteNonQuery(paraList, procedureName);
                }
                TempData["message"]     = "Successfully Created!";
                TempData["messageType"] = "Success";
                return(RedirectToAction("Index"));
            }
            catch
            {
                TempData["message"]     = "Error occured while Creating!";
                TempData["messageType"] = "Error";
                return(RedirectToAction("Index"));
            }
        }
Esempio n. 15
0
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        #region 验证用户输入
        if (Request["type"] != "huifu" && txtBianhao.Text.Trim() == "" && this.RadioBianhao.Checked)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert(\"" + GetTran("001607", "请输入收件人编号") + "!!!\");</script>");

            return;
        }
        if (txtTitle.Text.Trim() == "")
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("001609", "请输入标题") + "!!!');</script>");

            Literal1.Text = "";
            return;
        }
        if (this.content1.Value.Trim().Length.Equals(0))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "请输入邮件内容") + "!!!');</script>");

            return;
        }
        if (this.content1.Value.Trim().Length > 4000)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("000863", "您输入的信息过长") + "!!!');</script>");

            return;
        }
        double from = 0;
        double to   = 0;
        if (this.RadioRange.Checked && this.ChkBonus.Checked)
        {
            try
            {
                from = Convert.ToDouble(this.TxtBonusFrom.Text.Trim());
                to   = Convert.ToDouble(this.TxtBonusTo.Text.Trim());
            }
            catch
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "您输入的奖金区间无效") + "!!!');</script>");
                return;
            }
            if (from >= to)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "您输入的奖金区间无效") + "!!!');</script>");
                return;
            }
        }
        if (this.drop_LoginRole.SelectedValue.Equals("2") && this.RadioRange.Checked && this.ChkNet.Checked)
        {
            if (this.TxtLeader.Text.Trim().Length.Equals(0))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "请指定团队首领编号") + "!!!');</script>");
                return;
            }
            else
            {
                if (!MessageSendBLL.CheckNumber(2, this.TxtLeader.Text.Trim()))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "指定的团队首领不存在") + "!!!');</script>");
                    return;
                }
            }
        }
        #endregion

        StringBuilder sb = new StringBuilder();
        //if (Request["type"] != null)
        //{
        if (Request["type"] == "huifu")
        {
            MessageSendModel messagesend = new MessageSendModel();

            //邮件保存
            messagesend.Content      = this.content1.Value.Trim();
            messagesend.DropFlag     = 0;
            messagesend.InfoTitle    = txtTitle.Text.Trim().Replace("<", "&lt;").Replace(">", "&gt;");
            messagesend.LoginRole    = drop_LoginRole.SelectedItem.Value;
            messagesend.ReadFlag     = 0;
            messagesend.Sender       = Session["Company"].ToString();
            messagesend.SenderRole   = "0";
            messagesend.LanguageCode = this.DropDownList2.SelectedValue;
            messagesend.CountryCode  = this.DropDownList1.SelectedValue;
            messagesend.MessageType  = 'm';
            messagesend.SetNoCondition();
            int hfid;
            try
            {
                hfid = Convert.ToInt32(Request["hfid"]);
                if (hfid < 0)
                {
                    return;
                }
            }
            catch (Exception)
            {
                return;
            }
            messagesend.ReplyFor = hfid;
            System.Data.SqlClient.SqlDataReader dr = DAL.DBHelper.ExecuteReader("select Sender,ClassID from MessageReceive where ID=@id", new System.Data.SqlClient.SqlParameter("@id", hfid), CommandType.Text);
            if (dr.Read())
            {
                messagesend.Receive        = dr["Sender"].ToString();
                messagesend.MessageClassID = Convert.ToInt32(dr["ClassID"]);
            }
            else
            {
                ScriptHelper.SetAlert(Page, GetTran("001589", "对不起发件人不存在") + "!!!");
                return;
            }
            if (MessageSendBLL.Addsendaffiche(messagesend))
            {
                string href = "ManageMessage_Recive.aspx" + (Request["ClassID"] == null ? "" : "?ClassID=" + Request["ClassID"]);
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("001587", "邮件回复成功") + "!!!');location.href='" + href + "';</script>");
            }
            else
            {
                ScriptHelper.SetAlert(Page, GetTran("001588", "邮件回复失败") + "!!!");
            }
        }

        else//信息
        {
            if (Request["Id"] != null)
            {
                int id = Convert.ToInt32(Request["Id"]);
                //还没改  MessageSendBLL.DelMessageSendById(id);
                sb.Append(GetTran("001590", "邮件修改"));
            }
            else
            {
                Response.Cache.SetExpires(DateTime.Now);
                Permissions.CheckManagePermission(EnumCompanyPermission.ManageMessage);
                sb.Append(GetTran("001592", "邮件发送"));
            }
            MessageSendModel messagesend = new MessageSendModel();
            //邮件保存
            messagesend.Content      = this.content1.Value.Trim();
            messagesend.DropFlag     = 0;
            messagesend.InfoTitle    = txtTitle.Text.Trim().Replace("<", "&lt;").Replace(">", "&gt;");
            messagesend.LoginRole    = drop_LoginRole.SelectedItem.Value;
            messagesend.ReadFlag     = 0;
            messagesend.Sender       = Session["Company"].ToString();
            messagesend.SenderRole   = "0";
            messagesend.LanguageCode = this.DropDownList2.SelectedValue;
            messagesend.CountryCode  = this.DropDownList1.SelectedValue;

            messagesend.Qishu       = CommonDataDAL.getMaxqishu();
            messagesend.MessageType = 'm';
            messagesend.SetNoCondition();
            if (this.RadioBianhao.Checked) //指定了编号
            {
                if (txtBianhao.Text.Trim().Length > 0)
                {
                    if (!txtBianhao.Text.Trim().Equals("*"))
                    {
                        //验证编号是否存在
                        string[] strArray = txtBianhao.Text.Trim().Split(new char[] { ',' });
                        foreach (string strNO in strArray)
                        {
                            if (strNO != "")
                            {
                                int id = Convert.ToInt32(drop_LoginRole.SelectedValue);
                                //验证编号是否存在
                                if (!MessageSendBLL.CheckNumber(id, strNO))
                                {
                                    Response.Write("<script>alert('" + strNO + GetTran("001584", "不存在") + "');</script>");
                                    return;
                                }
                            }
                        }
                    }
                }
                else
                {
                    ScriptHelper.SetAlert(Page, GetTran("001594", "请输入收件人") + "!!!");
                    return;
                }
                messagesend.Receive = DisposeString.DisString(txtBianhao.Text.Trim());
            }
            else //指定了Range
            {
                messagesend.Receive = "*";
                //if (this.ChkLevel.Checked)
                //{
                //    messagesend.ConditionLevel = Convert.ToInt16(this.DropLevel.SelectedValue);
                //}
                if (this.ChkBonus.Checked)
                {
                    messagesend.ConditionBonusFrom = Convert.ToDouble(this.TxtBonusFrom.Text.Trim());
                    messagesend.ConditionBonusTo   = Convert.ToDouble(this.TxtBonusTo.Text.Trim());
                }
                if (this.ChkNet.Checked)
                {
                    messagesend.ConditionRelation = Convert.ToChar(this.DropRelation.SelectedValue);
                    messagesend.ConditionLeader   = this.TxtLeader.Text.Trim();
                }
            }


            if (MessageSendBLL.Addsendaffiche(messagesend))
            {
                sb.Append(GetTran("001600", "成功") + "!!!");
                ScriptHelper.SetAlert(Page, sb.ToString());
            }
            else
            {
                sb.Append(GetTran("001541", "失败") + "!!!");
                ScriptHelper.SetAlert(Page, sb.ToString());
            }
        }
        this.txtTitle.Text  = "";
        this.TextBox1.Text  = "";
        this.content1.Value = "";
    }
Esempio n. 16
0
        /// <summary>
        /// Send Message
        /// </summary>
        /// <param name="userFrom"></param>
        /// <param name="userTo"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static async Task SendMessage(MessageSendModel messageModel)
        {
            var unitOfWork = ContainerManager.GetConfiguredContainer().Resolve <IUnitOfWorkAsync>();

            MessageThread messageThread;

            // Use message subject to find the message thread if no listing id is provided
            if (!messageModel.ListingID.HasValue)
            {
                var messageThreadQuery = await MessageThreadService
                                         .Query(x =>
                                                x.Subject.Equals(messageModel.Subject, StringComparison.InvariantCultureIgnoreCase) &&
                                                x.MessageParticipants.Any(y => y.UserID == messageModel.UserFrom) &&
                                                x.MessageParticipants.Any(y => y.UserID == messageModel.UserTo))
                                         .SelectAsync();

                messageThread = messageThreadQuery.FirstOrDefault();
            }
            else
            {
                // Otherwise, use listing ID
                var messageThreadQuery = await MessageThreadService
                                         .Query(x => x.ListingID == messageModel.ListingID)
                                         .SelectAsync();

                messageThread = messageThreadQuery.FirstOrDefault();
            }

            // Create message thread if there is not one yet.
            if (messageThread == null)
            {
                messageThread = new MessageThread()
                {
                    Subject     = messageModel.Subject,
                    ListingID   = messageModel.ListingID,
                    Created     = DateTime.Now,
                    LastUpdated = DateTime.Now,
                    ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
                };

                MessageThreadService.Insert(messageThread);

                await UnitOfWorkAsync.SaveChangesAsync();

                // Add message participants
                MessageParticipantService.Insert(new MessageParticipant()
                {
                    UserID          = messageModel.UserFrom,
                    MessageThreadID = messageThread.ID,
                    ObjectState     = Repository.Pattern.Infrastructure.ObjectState.Added
                });

                MessageParticipantService.Insert(new MessageParticipant()
                {
                    UserID          = messageModel.UserTo,
                    MessageThreadID = messageThread.ID,
                    ObjectState     = Repository.Pattern.Infrastructure.ObjectState.Added
                });
            }

            // Insert mail message to db
            var message = new Message()
            {
                UserFrom        = messageModel.UserFrom,
                Body            = messageModel.Body,
                MessageThreadID = messageThread.ID,
                Created         = DateTime.Now,
                LastUpdated     = DateTime.Now,
                ObjectState     = Repository.Pattern.Infrastructure.ObjectState.Added
            };

            MessageService.Insert(message);

            await UnitOfWorkAsync.SaveChangesAsync();

            // Add read state of messages
            MessageReadStateService.Insert(new MessageReadState()
            {
                MessageID   = message.ID,
                UserID      = messageModel.UserFrom,
                ReadDate    = DateTime.Now,
                ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
            });

            MessageReadStateService.Insert(new MessageReadState()
            {
                MessageID   = message.ID,
                UserID      = messageModel.UserTo,
                ReadDate    = null,
                ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
            });

            await UnitOfWorkAsync.SaveChangesAsync();
        }
Esempio n. 17
0
        public async Task <IdentityResult> RegisterAccount(RegisterViewModel model)
        {
            var user = new ApplicationUser
            {
                UserName       = model.Email,
                Email          = model.Email,
                FirstName      = model.FirstName,
                LastName       = model.LastName,
                PhoneNumber    = model.Phone,
                Gender         = model.Gender,
                CountryID      = model.CountryID,
                RegisterDate   = DateTime.Now,
                RegisterIP     = System.Web.HttpContext.Current.Request.GetVisitorIP(),
                LastAccessDate = DateTime.Now,
                LastAccessIP   = System.Web.HttpContext.Current.Request.GetVisitorIP()
            };

            var result = await UserManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                #region Mensaje
                // Send Message
                var roleAdministrator = await RoleManager.FindByNameAsync(BeYourMarket.Model.Enum.Enum_UserType.Administrator.ToString());

                var administrator = roleAdministrator.Users.FirstOrDefault();

                var message = new MessageSendModel()
                {
                    UserFrom = administrator.UserId,
                    UserTo   = user.Id,
                    Subject  = HttpContext.ParseAndTranslate(string.Format("[[[Welcome to {0}!]]]", CacheHelper.Settings.Name)),
                    Body     = HttpContext.ParseAndTranslate(string.Format("[[[Hi, Welcome to {0}! I am happy to assist you if you has any questions.]]]", CacheHelper.Settings.Name))
                };

                await MessageHelper.SendMessage(message);

                #endregion

                #region Correo
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var urlHelper   = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
                var callbackUrl = urlHelper.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: System.Web.HttpContext.Current.Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "signup").SelectAsync();

                var emailTemplate = emailTemplateQuery.FirstOrDefault();

                if (emailTemplate != null)
                {
                    dynamic email = new Postal.Email("Email");
                    email.To          = user.Email;
                    email.From        = CacheHelper.Settings.EmailAddress;
                    email.Subject     = emailTemplate.Subject;
                    email.Body        = emailTemplate.Body;
                    email.CallbackUrl = callbackUrl;
                    EmailHelper.SendEmail(email);
                }
                #endregion
            }

            return(result);
        }
Esempio n. 18
0
 /// <summary>
 /// 保存邮件
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 public bool AddMessageSend(MessageSendModel message)
 {
     return(MessageSendDAL.AddMessageSend(message));
 }
Esempio n. 19
0
 /// <summary>
 /// 发布公告
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 public static bool Addsendaffiche(MessageSendModel message)
 {
     return(MessageSendDAL.Addsendaffiche(message));
 }
Esempio n. 20
0
 public int MemberSendToManage(MessageSendModel msm)
 {
     //MessageSendDAL dao = new MessageSendDAL();
     return(MessageSendDAL.MemberSendToManage(msm));
 }
Esempio n. 21
0
        public void sendMessage(MessageSendModel model, string keyDialog)
        {
            AuthorizationUtils authorization = new AuthorizationUtils(Request);

            logic.sendMessageLogic(authorization.getUserId(), model, keyDialog);
        }
        public async Task <ActionResult> ReviewListing(ListingReview listingReview)
        {
            var currentUserId = User.Identity.GetUserId();

            // Check if listing review is enabled
            if (!CacheHelper.Settings.ListingReviewEnabled)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[Listing review is not allowed!]]]";
                return(RedirectToAction("Listing", "Listing", new { id = listingReview.ID }));
            }

            // Check if users reach max review limit
            var today       = DateTime.Today.Date;
            var reviewQuery = await _listingReviewService.Query(x => x.UserFrom == currentUserId &&
                                                                System.Data.Entity.DbFunctions.TruncateTime(x.Created) == today).SelectAsync();

            var reviewCount = reviewQuery.Count();

            if (reviewCount >= CacheHelper.Settings.ListingReviewMaxPerDay)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[You have reach the review limits today!]]]";
                return(RedirectToAction("Listing", "Listing", new { id = listingReview.ID }));
            }

            var listingQuery = await _listingService.Query(x => x.ID == listingReview.ID)
                               .Include(x => x.AspNetUser)
                               .SelectAsync();

            var listing = listingQuery.FirstOrDefault();

            // User cannot comment himself
            if (currentUserId == listing.UserID)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[You cannot review yourself!]]]";
                return(RedirectToAction("Listing", "Listing", new { id = listingReview.ID }));
            }

            // update review id on the order
            var review = new ListingReview()
            {
                UserFrom    = currentUserId,
                UserTo      = listing.UserID,
                Description = listingReview.Description,
                Rating      = listingReview.Rating,
                Spam        = false,
                Active      = true,
                Enabled     = true,
                ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added,
                Created     = DateTime.Now
            };

            review.ListingID = listingReview.ID;

            _listingReviewService.Insert(review);

            await _unitOfWorkAsync.SaveChangesAsync();

            // update rating on the user
            var listingReviewQuery = await _listingReviewService.Query(x => x.UserTo == listing.UserID).SelectAsync();

            var rating = listingReviewQuery.Average(x => x.Rating);

            var user = await UserManager.FindByIdAsync(listing.UserID);

            user.Rating = rating;
            await UserManager.UpdateAsync(user);

            // Notify the user with the rating and comment
            var message = new MessageSendModel()
            {
                UserFrom  = review.UserFrom,
                UserTo    = review.UserTo,
                Subject   = review.Title,
                Body      = string.Format("{0} <span class=\"score s{1} text-xs\"></span>", review.Description, review.RatingClass),
                ListingID = listingReview.ID
            };

            await MessageHelper.SendMessage(message);

            TempData[TempDataKeys.UserMessage] = "[[[Thanks for your feedback!]]]";
            return(RedirectToAction("Listing", "Listing", new { id = listingReview.ID }));
        }
Esempio n. 23
0
        public static int StoreSendToManage(MessageSendModel msm)
        {
            int i = 0;

            try
            {
                System.Text.StringBuilder insertSql2 = new System.Text.StringBuilder();
                insertSql2.Append("insert into MessageSend values(@role,@receive,@title,@content,1,@sender,@senddate,0,0,null,null,@msgclassid,@replyfor,@messagetype)");

                SqlParameter[] para1 =
                {
                    new SqlParameter("@role",        SqlDbType.Char,       10),
                    new SqlParameter("@receive",     SqlDbType.VarChar,  4000),
                    new SqlParameter("@title",       SqlDbType.VarChar,    50),
                    new SqlParameter("@content",     SqlDbType.Text),
                    new SqlParameter("@sender",      SqlDbType.VarChar,    20),
                    new SqlParameter("@senddate",    SqlDbType.DateTime,    8),
                    new SqlParameter("@msgclassid",  SqlDbType.Int),
                    new SqlParameter("@replyfor",    SqlDbType.Int),
                    new SqlParameter("@messagetype", SqlDbType.Char)
                };
                para1[0].Value = msm.LoginRole.ToString();
                para1[1].Value = msm.Receive.ToString();
                para1[2].Value = msm.InfoTitle.ToString();
                para1[3].Value = msm.Content.ToString();
                para1[4].Value = msm.Sender.ToString();
                para1[5].Value = msm.Senddate.ToUniversalTime();
                para1[6].Value = msm.MessageClassID;
                para1[7].Value = msm.ReplyFor;
                para1[8].Value = msm.MessageType;
                using (SqlConnection conn = new SqlConnection(DBHelper.connString))
                {
                    conn.Open();
                    SqlTransaction tran = conn.BeginTransaction();
                    try
                    {
                        DBHelper.ExecuteNonQuery(tran, insertSql2.ToString(), para1, CommandType.Text);

                        string sqlStr2       = "select max(id) from messagesend where sender = '" + msm.Sender.ToString() + "'";
                        int    MessagesendId = Convert.ToInt32(DBHelper.ExecuteScalar(tran, sqlStr2, CommandType.Text));

                        System.Text.StringBuilder insertSql = new System.Text.StringBuilder();
                        insertSql.Append("insert into MessageReceive values(@messagesendId,@role,@receive,@title,@content,1,@sender,@senddate,0,0,0,null,null,@msgclassid,@replyfor,@messagetype) ");
                        SqlParameter[] para =
                        {
                            new SqlParameter("@MessagesendId", SqlDbType.Int),
                            new SqlParameter("@role",          SqlDbType.Char,       10),
                            new SqlParameter("@receive",       SqlDbType.VarChar,  4000),
                            new SqlParameter("@title",         SqlDbType.VarChar,    50),
                            new SqlParameter("@content",       SqlDbType.NVarChar, 4000),
                            new SqlParameter("@sender",        SqlDbType.VarChar,    20),
                            new SqlParameter("@senddate",      SqlDbType.DateTime,    8),
                            new SqlParameter("@msgclassid",    SqlDbType.Int),
                            new SqlParameter("@replyfor",      SqlDbType.Int),
                            new SqlParameter("@messagetype",   SqlDbType.Char)
                        };
                        para[0].Value = MessagesendId;
                        para[1].Value = msm.LoginRole.ToString();
                        para[2].Value = msm.Receive.ToString();
                        para[3].Value = msm.InfoTitle.ToString();
                        para[4].Value = msm.Content.ToString();
                        para[5].Value = msm.Sender.ToString();
                        para[6].Value = msm.Senddate.ToUniversalTime();
                        para[7].Value = msm.MessageClassID;
                        para[8].Value = msm.ReplyFor;
                        para[9].Value = msm.MessageType;
                        i             = DBHelper.ExecuteNonQuery(tran, insertSql.ToString(), para, CommandType.Text);
                        tran.Commit();
                    }
                    catch
                    {
                        tran.Rollback();
                        throw;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch (Exception)
            {
            }
            return(i);
        }
Esempio n. 24
0
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        #region 验证用户输入
        if (txtBianhao.Text.Trim() == "")
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert(\"" + GetTran("001607", "请输入收件人编号") + "!!!\");</script>");

            return;
        }
        if (txtTitle.Text.Trim() == "")
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("001609", "请输入标题") + "!!!');</script>");

            Literal1.Text = "";
            return;
        }
        if (this.content1.Value.Trim().Length.Equals(0))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "请输入公告内容") + "!!!');</script>");

            return;
        }
        if (this.content1.Value.Trim().Length > 4000)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("000863", "您输入的信息过长") + "!!!');</script>");

            return;
        }
        double from = 0;
        double to   = 0;
        if (this.ChkBonus.Checked)
        {
            if (string.IsNullOrEmpty(this.TxtBonusFrom.Text.Trim()))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert(' 起始奖金不能为空!');</script>");
                return;
            }
            if (string.IsNullOrEmpty(this.TxtBonusTo.Text.Trim()))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert(' 未尾奖金不能为空!');</script>");
                return;
            }
            try
            {
                from = Convert.ToDouble(this.TxtBonusFrom.Text.Trim());
                to   = Convert.ToDouble(this.TxtBonusTo.Text.Trim());
                if (from <= 0)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert(' 起始奖金不能为负数!');</script>");
                    return;
                }
                if (from <= 0)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert(' 未尾奖金不能负数!');</script>");
                    return;
                }
            }
            catch
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "您输入的奖金区间无效") + "!!!');</script>");
                return;
            }
            if (from >= to)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "您输入的奖金区间无效") + "!!!');</script>");
                return;
            }
        }

        if (this.drop_LoginRole.SelectedValue.Equals("2") && this.ChkNet.Checked)
        {
            if (this.TxtLeader.Text.Trim().Length.Equals(0))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "请指定团队领导人编号") + "!!!');</script>");
                return;
            }
            else
            {
                if (!MessageSendBLL.CheckNumber(2, this.TxtLeader.Text.Trim()))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("kwl", "指定的团队领导人不存在") + "!!!');</script>");
                    return;
                }
            }
        }
        #endregion
        StringBuilder sb = new StringBuilder();

        if (Request["Id"] != null)
        {
            int id = Convert.ToInt32(Request["Id"]);

            ChangeLogs cl = new ChangeLogs("MessageSend", "ltrim(rtrim(id))");
            cl.AddRecord(id);

            ChangeLogs clsend = new ChangeLogs("MessageReceive", "ltrim(rtrim(messagesendid))");
            clsend.AddRecord(id);


            BLL.other.Company.MessageReceiveBLL bll = new MessageReceiveBLL();
            bll.delGongGao(id);

            cl.ModifiedIntoLogs(ChangeCategory.company19, Session["Company"].ToString(), ENUM_USERTYPE.objecttype10);
            clsend.ModifiedIntoLogs(ChangeCategory.company19, Session["Company"].ToString(), ENUM_USERTYPE.objecttype10);

            this.btn_Save.Text = GetTran("000259", "修改");
            sb.Append(GetTran("001621", "公告修改"));
        }
        else
        {
            sb.Append(GetTran("001620", "公告发布"));
        }
        MessageSendModel messagesend = new MessageSendModel();

        //messagesend.Content = TextBox1.Text.Trim();
        messagesend.Content   = this.content1.Value.Trim();
        messagesend.DropFlag  = 0;
        messagesend.InfoTitle = txtTitle.Text.Trim().Replace("<", "&lt;").Replace(">", "&gt;");
        messagesend.LoginRole = drop_LoginRole.SelectedItem.Value;
        messagesend.ReadFlag  = 0;

        messagesend.Sender     = Session["Company"].ToString();
        messagesend.SenderRole = "0";
        messagesend.Receive    = "*";

        messagesend.CountryCode  = this.DropDownList1.SelectedValue;
        messagesend.LanguageCode = this.DropDownList2.SelectedValue;
        //if (this.ChkLevel.Checked)
        //{
        //    messagesend.ConditionLevel = Convert.ToInt16(this.DropLevel.SelectedValue);
        //}
        //else
        //{
        //    messagesend.ConditionLevel = -1;
        //}
        if (this.ChkBonus.Checked)
        {
            messagesend.ConditionBonusFrom = Convert.ToDouble(this.TxtBonusFrom.Text.Trim());
            messagesend.ConditionBonusTo   = Convert.ToDouble(this.TxtBonusTo.Text.Trim());
        }
        else
        {
            messagesend.ConditionBonusFrom = -1;
            messagesend.ConditionBonusTo   = -1;
        }
        if (this.ChkNet.Checked)
        {
            messagesend.ConditionRelation = Convert.ToChar(this.DropRelation.SelectedValue);
            messagesend.ConditionLeader   = this.TxtLeader.Text.Trim();
        }
        else
        {
            messagesend.ConditionLeader   = "";
            messagesend.ConditionRelation = '0';
        }
        messagesend.Qishu       = CommonDataDAL.getMaxqishu();
        messagesend.MessageType = 'a';
        if (MessageSendBLL.Addsendaffiche(messagesend))
        {
            BLL.other.Company.MessageReceiveBLL bll = new MessageReceiveBLL();

            if (this.drop_LoginRole.SelectedValue == "1")
            {
                bll.UpdateStore();
            }
            else if (this.drop_LoginRole.SelectedValue == "2")
            {
                bll.UpdateMember();
            }

            sb.Append(GetTran("001600", "成功") + "!!!");
            ScriptHelper.SetAlert(Page, sb.ToString());
        }
        else
        {
            sb.Append(GetTran("001618", "失败"));
            ScriptHelper.SetAlert(Page, sb.ToString());
        }

        txtTitle.Text  = "";
        TextBox1.Text  = "";
        content1.Value = "";
    }
Esempio n. 25
0
        public async Task <ActionResult> OrderAction(int id, int status)
        {
            var orderQuery = await _orderService.Query(x => x.ID == id).Include(x => x.Listing).SelectAsync();

            var order = orderQuery.FirstOrDefault();

            if (order == null)
            {
                return(new HttpNotFoundResult());
            }

            var currentUserId = User.Identity.GetUserId();

            // Unauthorized access
            if (order.UserProvider != currentUserId && order.UserReceiver != currentUserId)
            {
                return(new HttpUnauthorizedResult());
            }

            var descriptor = _pluginFinder.GetPluginDescriptorBySystemName <IHookPlugin>(order.PaymentPlugin);

            if (descriptor == null)
            {
                return(new HttpNotFoundResult("Not found"));
            }

            var controllerType = descriptor.Instance <IHookPlugin>().GetControllerType();
            var controller     = ContainerManager.GetConfiguredContainer().Resolve(controllerType) as IPaymentController;

            string message     = string.Empty;
            var    orderResult = controller.OrderAction(id, status, out message);

            var orderStatus     = (Enum_OrderStatus)status;
            var orderStatusText = string.Empty;

            switch (orderStatus)
            {
            case Enum_OrderStatus.Created:
            case Enum_OrderStatus.Pending:
                orderStatusText = "[[[Pending]]]";
                break;

            case Enum_OrderStatus.Confirmed:
                orderStatusText = "[[[Confirmed]]]";
                break;

            case Enum_OrderStatus.Cancelled:
                orderStatusText = "[[[Cancelled]]]";
                break;

            default:
                orderStatusText = orderStatus.ToString();
                break;
            }

            var result = new
            {
                Success = orderResult,
                Message = message
            };

            if (orderResult)
            {
                // Send message to the user
                var messageSend = new MessageSendModel()
                {
                    UserFrom  = currentUserId,
                    UserTo    = order.UserProvider == currentUserId ? order.UserReceiver : order.UserProvider,
                    ListingID = order.ListingID,
                    Subject   = order.Listing.Title,
                    Body      = HttpContext.ParseAndTranslate(string.Format(
                                                                  "[[[Order %0 - %1 - Total Price %2 %3. <a href=\"%4\">See Details</a>|||{0}|||{1}|||{2}|||{3}|||{4}]]]",
                                                                  HttpContext.ParseAndTranslate(orderStatusText),
                                                                  HttpContext.ParseAndTranslate(order.Description),
                                                                  order.Price,
                                                                  order.Currency,
                                                                  Url.Action("Orders")))
                };

                await MessageHelper.SendMessage(messageSend);
            }

            TempData[TempDataKeys.UserMessage] = string.Format("[[[The order is %0.|||{0}]]]", orderStatus);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Esempio n. 26
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        MessageSendBLL msb = new MessageSendBLL();

        if (this.txtNumber.SelectedItem.Text.Trim() == "")
        {
            msg = "<Script language='javascript'>alert('" + GetTran("000848", "对不起,编号不能为空") + "!');</Script>";
            ClientScript.RegisterStartupScript(this.GetType(), "", msg);
            return;
        }
        string sqlStr = "";

        switch (drop_LoginRole.SelectedValue)
        {
        case "0": sqlStr = "Select count(0) From Manage where Number='" + this.txtNumber.SelectedValue.Trim() + "'"; break;

        case "1": sqlStr = "Select count(0) From MemberInfo where Number='" + this.txtNumber.SelectedValue.Trim() + "'"; break;

        case "2": sqlStr = "Select count(0) From StoreInfo where storeid='" + this.txtNumber.SelectedValue.Trim() + "'"; break;
        }
        if (msb.check(sqlStr) != 1)
        {
            msg = "<Script language='javascript'>alert('" + GetTran("000850", "对不起") + "," + drop_LoginRole.SelectedItem.Text + "" + GetTran("000854", "的编号错误") + "!');</Script>";
            ClientScript.RegisterStartupScript(this.GetType(), "", msg);
            return;
        }
        //if (this.RadioListClass.SelectedValue.Equals(""))
        //{
        //    msg = "<script language='javascript'>alert('" + GetTran("007712", "请选择邮件分类") + "!!!');</script>";
        //    ClientScript.RegisterStartupScript(this.GetType(), "", msg);

        //    return;
        //}
        if (this.txtTitle.Text.Trim() == "")
        {
            msg = "<Script language='javascript'>alert('" + GetTran("000859", "对不起,标题信息不能为空") + "!');</Script>";
            ClientScript.RegisterStartupScript(this.GetType(), "", msg);
            return;
        }
        if (this.content1.Text.Trim().Length.Equals(0))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + GetTran("007399", "请输入邮件内容") + "!!!');</script>");

            return;
        }
        if (this.content1.Text.Trim().Length > 400)
        {
            msg = "<script language='javascript'>alert('" + GetTran("000863", "您输入的信息过长") + "!!!');</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "", msg);

            return;
        }

        //if (uppic.FileName!=null)
        //{

        //    string fullFileName = uppic.PostedFile.FileName;
        //    //string fileName = fullFileName.Substring(fullFileName.LastIndexOf("\\") + 1);//图片名称
        //    string type = fullFileName.Substring(fullFileName.LastIndexOf(".") + 1).ToLower();
        //    if (type == "jpg" || type == "gif" || type == "bmp" || type == "png" || type == "jpeg")
        //    {
        //        HttpPostedFile upFile = uppic.PostedFile;//HttpPostedFile对象,用来读取上传图片的属性
        //        int fileLength = upFile.ContentLength;//记录文件的长度
        //        byte[] fileBytePicture = new byte[fileLength];//用图片的长度来初始化一个字节数组存储临时的图片文件
        //        Stream fileStream = upFile.InputStream;//建立文件流对象
        //        fileStream.Read(fileBytePicture, 0, fileLength);

        //        //Insert into db, picture字段,image类型
        //        //在此要注意,SQL语句中插入DB不能像varchar()类型,用单引号引起来,这样的话会报错,要使用参数自行插入,eg:
        //        //cmd.CommandText = @"INSERT INTO Category(Category,Picture)VALUES(@Category,@Picture)";
        //        //cmd.Parameters.AddWithValue("@Category", category);//string category     //cmd.Parameters.AddWithValue("@Picture", picture);// byte[] picture
        //    }



        //string filepath = uppic.PostedFile.FileName;  //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg
        ////string filepath = FileUpload1.FileName;               //得到上传的文件名20022775_m.jpg
        //string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg
        //serverpath = Server.MapPath("~/MemberMobile/images/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg
        //uppic.PostedFile.SaveAs(serverpath);//将上传的文件另存为
        //}
        DateTime         date = DateTime.Now;
        MessageSendModel msm  = new MessageSendModel();

        ///表示会员
        msm.LoginRole      = "0";
        msm.Receive        = BLL.CommonClass.CommonDataBLL.getManageID(1);
        msm.InfoTitle      = this.txtTitle.Text.ToString().Replace("<", "&lt;").Replace(">", "&gt;");
        msm.Content        = this.content1.Text.Trim();
        msm.Sender         = Session["Member"].ToString();
        msm.Senddate       = date;
        msm.SenderRole     = "2";
        msm.MessageClassID = 0;
        msm.MessageType    = 'm';

        int i = 0;

        i = msb.MemberSendToManage(msm);
        if (i > 0)
        {
            msg = "<Script language='javascript'>alert('" + GetTran("007400", "邮件发送成功") + "!');</script>";
        }
        else
        {
            msg = "<Script language='javascript'>alert('" + GetTran("007401", "邮件发送失败") + "!');</script>";
        }
        ClientScript.RegisterStartupScript(this.GetType(), "", msg);

        btnCancle_Click(null, null);
    }
Esempio n. 27
0
        public async Task <ActionResult> Payment(int id, string stripeToken, string stripeEmail)
        {
            var selectQuery = await _orderService.Query(x => x.ID == id).Include(x => x.Listing).SelectAsync();

            // Check if order exists
            var order = selectQuery.FirstOrDefault();

            if (order == null)
            {
                return(new HttpNotFoundResult());
            }

            var stripeConnectQuery = await _stripeConnectService.Query(x => x.UserID == order.UserProvider).SelectAsync();

            var stripeConnect = stripeConnectQuery.FirstOrDefault();

            if (stripeConnect == null)
            {
                return(new HttpNotFoundResult());
            }

            // Check for customer profile
            var userId = User.Identity.GetUserId();

            // Create a customer profile for future checkouts
            var customerCreate = new StripeCustomerCreateOptions()
            {
                Email  = stripeEmail,
                Source = new StripeSourceOptions()
                {
                    TokenId = stripeToken
                }
            };
            var customerCreateService = new StripeCustomerService(CacheHelper.GetSettingDictionary("StripeApiKey").Value);
            var response = customerCreateService.Create(customerCreate);

            var customer = new StripeCustomerReference()
            {
                UserID           = userId,
                StripeCustomerID = response.Id,
                ObjectState      = Repository.Pattern.Infrastructure.ObjectState.Added
            };

            _stripeCusRefService.Insert(customer);
            await _unitOfWorkAsyncStripe.SaveChangesAsync();

            //https://stripe.com/docs/checkout
            var charge = new StripeChargeCreateOptions();

            // always set these properties
            charge.Amount     = order.PriceInCents;
            charge.Currency   = CacheHelper.Settings.Currency;
            charge.CustomerId = customer.StripeCustomerID;

            // set booking fee
            var bookingFee = (int)Math.Round(CacheHelper.Settings.TransactionFeePercent * order.PriceInCents);

            if (bookingFee < CacheHelper.Settings.TransactionMinimumFee * 100)
            {
                bookingFee = (int)(CacheHelper.Settings.TransactionMinimumFee * 100);
            }

            charge.ApplicationFee = bookingFee;
            charge.Capture        = false;
            charge.Description    = order.Description;
            charge.Destination    = stripeConnect.stripe_user_id;
            var          chargeService = new StripeChargeService(CacheHelper.GetSettingDictionary("StripeApiKey").Value);
            StripeCharge stripeCharge  = chargeService.Create(charge);

            // Update order status
            order.Status        = (int)Enum_OrderStatus.Pending;
            order.PaymentPlugin = StripePlugin.PluginName;
            _orderService.Update(order);

            // Save transaction
            var transaction = new StripeTransaction()
            {
                OrderID        = id,
                ChargeID       = stripeCharge.Id,
                StripeEmail    = stripeEmail,
                CustomerId     = customer.StripeCustomerID,
                Created        = DateTime.Now,
                LastUpdated    = DateTime.Now,
                FailureCode    = stripeCharge.FailureCode,
                FailureMessage = stripeCharge.FailureMessage,
                ObjectState    = Repository.Pattern.Infrastructure.ObjectState.Added
            };

            _transactionService.Insert(transaction);

            await _unitOfWorkAsync.SaveChangesAsync();

            await _unitOfWorkAsyncStripe.SaveChangesAsync();

            ClearCache();

            // Payment succeeded
            if (string.IsNullOrEmpty(stripeCharge.FailureCode))
            {
                // Send message to the user
                var message = new MessageSendModel()
                {
                    UserFrom  = order.UserReceiver,
                    UserTo    = order.UserProvider,
                    Subject   = order.Listing.Title,
                    ListingID = order.ListingID,
                    Body      = HttpContext.ParseAndTranslate(string.Format(
                                                                  "[[[Order Requested - %0 - Total Price %1 %2. <a href=\"%3\">See Details</a>|||{0}|||{1}|||{2}|||{3}]]]",
                                                                  order.Description,
                                                                  order.Price,
                                                                  order.Currency,
                                                                  Url.Action("Orders", "Payment")))
                };

                await MessageHelper.SendMessage(message);

                TempData[TempDataKeys.UserMessage] = "[[[Thanks for your order! You payment will not be charged until the provider accepted your request.]]]";
                return(RedirectToAction("Orders", "Payment"));
            }
            else
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = stripeCharge.FailureMessage;

                return(RedirectToAction("Payment"));
            }
        }
Esempio n. 28
0
        public async Task <ActionResult> Review(ListingReview listingReview)
        {
            var currentUserId = User.Identity.GetUserId();

            var orderQuery = await _orderService.Query(x => x.ID == listingReview.OrderID)
                             .Include(x => x.Listing)
                             .SelectAsync();

            var order = orderQuery.FirstOrDefault();

            var userTo = order.UserProvider == currentUserId ? order.UserReceiver : order.UserProvider;

            // User cannot comment himself
            if (currentUserId == userTo)
            {
                return(RedirectToAction("Orders", "Payment"));
            }

            // check if user has right to review the order
            if (order == null || (order.UserProvider != currentUserId && order.UserReceiver != currentUserId))
            {
                return(RedirectToAction("Orders", "Payment"));
            }

            // update review id on the order
            var review = new ListingReview()
            {
                UserFrom    = currentUserId,
                UserTo      = userTo,
                OrderID     = listingReview.OrderID,
                Description = listingReview.Description,
                Rating      = listingReview.Rating,
                Spam        = false,
                Active      = true,
                Enabled     = true,
                ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added,
                Created     = DateTime.Now
            };

            // Set listing id if it's service receiver
            if (order.UserReceiver == currentUserId)
            {
                review.ListingID = order.ListingID;
            }

            _listingReviewService.Insert(review);

            await _unitOfWorkAsync.SaveChangesAsync();

            // update rating on the user
            var listingReviewQuery = await _listingReviewService.Query(x => x.UserTo == userTo).SelectAsync();

            var rating = listingReviewQuery.Average(x => x.Rating);

            var user = await UserManager.FindByIdAsync(userTo);

            user.Rating = rating;
            await UserManager.UpdateAsync(user);

            // Notify the user with the rating and comment
            var message = new MessageSendModel()
            {
                UserFrom  = review.UserFrom,
                UserTo    = review.UserTo,
                Subject   = review.Title,
                Body      = string.Format("{0} <span class=\"score s{1} text-xs\"></span>", review.Description, review.RatingClass),
                ListingID = order.ListingID
            };

            await MessageHelper.SendMessage(message);

            TempData[TempDataKeys.UserMessage] = "[[[Thanks for your feedback!]]]";
            return(RedirectToAction("Orders", "Payment"));
        }
Esempio n. 29
0
 public void sendMessageLogic(int userId, MessageSendModel model, string keyDialog)
 {
     dataAccess.sendMessage(userId, model, keyDialog);
 }
Esempio n. 30
0
 public int StoreSendToManage(MessageSendModel msm)
 {
     //MessageSendDAL dao = new MessageSendDAL();
     return(MessageSendDAL.StoreSendToManage(msm));
 }