Example #1
0
        private void ReadNoticeSql(string uid, int noticeId, JObject responseData)
        {
            UserNotice userNotice = NHibernateHelper.userNoticeManager.getUserNotice(uid, noticeId);

            if (userNotice == null)
            {
                MySqlService.log.Warn("该用户没有这条通知");
                OperatorFail(responseData);
            }
            else
            {
                if (userNotice.State == 0)
                {
                    userNotice.State = 1;
                    if (NHibernateHelper.userNoticeManager.Update(userNotice))
                    {
                        OperatorSuccess(responseData);
                    }
                    else
                    {
                        MySqlService.log.Warn("更新用户通知数据库失败");
                        OperatorFail(responseData);
                    }
                }
                else
                {
                    MySqlService.log.Warn("该通知已读过");
                    OperatorFail(responseData);
                }
            }
        }
        public ActionResult Visualize(long noticeId, Guid userId)
        {
            var noticeRepository = new NoticeRepository(_context);
            var notSeenNotices   = noticeRepository.ListNotSeenNotices(userId);

            var userNotice = new UserNotice
            {
                VisualizationDateTime = DateTime.Now,
                NoticeId = noticeId,
                UserId   = userId
            };

            _context.GetList <UserNotice>().Add(userNotice);
            _context.Save();

            var dateTimeHumanizerStrategy = new DefaultDateTimeHumanizeStrategy();
            var nextNotice = noticeRepository.ListNotSeenNotices(userId).Except(notSeenNotices).FirstOrDefault();

            if (nextNotice != null)
            {
                return(Json(NoticeViewModel.FromEntity(nextNotice, dateTimeHumanizerStrategy)));
            }

            return(new EmptyResult());
        }
Example #3
0
        /// <summary>
        /// 主动触发获取用户通知事件
        /// </summary>
        /// <param name="notice">用户通知</param>
        public void RaiseGetUserNotice(UserNotice notice)
        {
            if (Config.IsLogin == false)
            {
                return;
            }
            if (this.OnGetUserNotice != null)
            {
                this.OnGetUserNotice(this, new TagEventArgs {
                    Tag = notice
                });
            }
            //Toast通知
            UserNotice inPhone = Config.UserNoticeInPhone;

            if (notice.atMeCount > inPhone.atMeCount ||
                notice.reviewCount > inPhone.reviewCount ||
                notice.msgCount > inPhone.msgCount)
            {
                StringBuilder sb = new StringBuilder( );
                sb.Append("        ");
                if (notice.atMeCount > 0)
                {
                    sb.AppendFormat("{0} 条提到我", notice.atMeCount);
                }
                if (notice.reviewCount > 0)
                {
                    sb.AppendFormat("  {0} 条评论", notice.reviewCount);
                }
                if (notice.msgCount > 0)
                {
                    sb.AppendFormat("  {0} 条留言", notice.msgCount);
                }
                ToastPrompt toast = ToastMessage("您有新的消息", sb.ToString( ));
                if (toast != null)
                {
                    //注意进入 ActivesPage 后,该显示哪一个我们根据 Config.UserNoticeInPhone 来决定
                    toast.Tap += (s, e) =>
                    {
                        if (notice.atMeCount > 0)
                        {
                            Tool.To(string.Format("/ActivesPage.xaml?catalog={0}", ( int )ActiveType.AtMe));
                        }
                        //如果是留言类型通知
                        else if (notice.msgCount > 0)
                        {
                            Tool.To("/MsgsPage.xaml");
                        }
                        else if (notice.reviewCount > 0)
                        {
                            Tool.To(string.Format("/ActivesPage.xaml?catalog={0}", ( int )ActiveType.Comment));
                        }
                    };
                }
            }
            Config.UserNoticeInPhone = notice;
        }
        protected override void ProcessChatMessage(UserNotice subNotice)
        {
            if (m_twitchClient == null)
            {
                m_twitchClient = TwitchClient.GetInstance();
            }

            if (m_subSettings != null)
            {
                string sMessage = m_subSettings.GetMessage(subNotice);

                m_twitchClient.SendChatMessage(subNotice.Channel, sMessage);
            }
        }
Example #5
0
        /// <summary>
        /// 获取到 UserNotice 后的处理
        /// </summary>
        void Instance_OnGetUserNotice(object sender, TagEventArgs e)
        {
            UserNotice notice = e.Tag as UserNotice;

            if (notice != null)
            {
                if (notice.atMeCount != 0)
                {
                    this.notice_AtMe.Visibility = System.Windows.Visibility.Visible;
                    this.notice_AtMe.Content    = notice.atMeCount.ToString( );
                }
                else
                {
                    this.notice_AtMe.Visibility = System.Windows.Visibility.Collapsed;
                }
                if (notice.reviewCount != 0)
                {
                    this.notice_Review.Visibility = System.Windows.Visibility.Visible;
                    this.notice_Review.Content    = notice.reviewCount.ToString( );
                }
                else
                {
                    this.notice_Review.Visibility = System.Windows.Visibility.Collapsed;
                }
                if (notice.msgCount != 0)
                {
                    this.notice_Msg.Content = new TextBlock
                    {
                        Text       = string.Format("{0} 未读消息", notice.msgCount),
                        Foreground = new SolidColorBrush(Colors.Black),
                        FontWeight = FontWeights.Bold,
                        FontFamily = new FontFamily("Arial"),
                    };
                }
                else
                {
                    this.notice_Msg.Content = new TextBlock
                    {
                        Text       = "无未读消息",
                        Foreground = new SolidColorBrush(Colors.Black)
                    };
                }
            }
        }
Example #6
0
        static DerSequence CreatePolicyInformationsSequence(string cps, string org, string oid, string desc)
        {
            Asn1EncodableVector av = new Asn1EncodableVector();

            av.Add(new DerInteger(1));
            DerSequence noticeNumbers = new DerSequence(av);

            Asn1EncodableVector qualifiers = new Asn1EncodableVector();

            if (cps != null)
            {
                PolicyQualifierInfo cpsnotice = new PolicyQualifierInfo(cps);
                qualifiers.Add(cpsnotice);
            }
            if (org != null && desc != null)
            {
                UserNotice un = new UserNotice(
                    new NoticeReference(DisplayText.ContentTypeIA5String, org, noticeNumbers), // OPTIONAL Orgname
                    new DisplayText(DisplayText.ContentTypeVisibleString, desc
                                    )
                    );

                PolicyQualifierInfo pqiUNOTICE = new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, un);


                qualifiers.Add(pqiUNOTICE);
            }

            DerObjectIdentifier policy = null;

            policy = new DerObjectIdentifier(oid);


            PolicyInformation policyInformation =
                new PolicyInformation(policy, new DerSequence(qualifiers));

            return(new DerSequence(policyInformation));
        }
Example #7
0
        static bool Gen(string summoner, string region, string password, string file)
        {
            try
            {
                //Later in your Code

                //Requested Certificate Name
                X509Name name = new X509Name("CN=" + summoner + " - " + region + ", OU=Ghostblade Replays, O=Arsslensoft");

                //Key generation 2048bits
                RsaKeyPairGenerator rkpg = new RsaKeyPairGenerator();
                rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
                AsymmetricCipherKeyPair ackp   = rkpg.GenerateKeyPair();
                X509Certificate2        caCert = new X509Certificate2(GBReplay.Properties.Resources.GBSGN, "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6");
                //PKCS #10 Certificate Signing Request
                Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA256WITHRSA", name, ackp.Public, null, ackp.Private);


                AsymmetricKeyParameter publicKey = csr.GetPublicKey();

                // Build a Version1 (No Extensions) Certificate
                DateTime   startDate    = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
                DateTime   expiryDate   = startDate.AddYears(5);
                BigInteger serialNumber = new BigInteger(32, new Random());


                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

                X509Name dnName = new X509Name(caCert.Subject);

                certGen.SetSerialNumber(serialNumber);
                certGen.SetIssuerDN(dnName);
                certGen.SetNotBefore(startDate);
                certGen.SetNotAfter(expiryDate);
                certGen.SetSubjectDN(name);
                certGen.SetSignatureAlgorithm("SHA256WITHRSA");
                certGen.SetPublicKey(publicKey);

                UserNotice          unotice    = new UserNotice(null, "This certificate must be only used with Ghostblade replays files. This certificate is a property of Arsslensoft any usage of its content without prior request is prohibited.");
                PolicyQualifierInfo pqiunotice = new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, unotice);
                PolicyInformation   p          = new PolicyInformation(new DerObjectIdentifier("1.3.6.1.4.1.44215.1.3"), new DerSequence(new PolicyQualifierInfo[1] {
                    pqiunotice
                }));
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(DotNetUtilities.FromX509Certificate(caCert).GetPublicKey()));
                certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey));
                certGen.AddExtension(X509Extensions.KeyUsage, false, new  KeyUsage(KeyUsage.DigitalSignature));
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new  ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPCodeSigning }));

                certGen.AddExtension(X509Extensions.CertificatePolicies, false, new DerSequence(p));



                Pkcs12Store pfx   = new Pkcs12Store(new MemoryStream(GBReplay.Properties.Resources.GBSGN), "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6".ToCharArray());
                string      alias = null;
                foreach (string al in pfx.Aliases)
                {
                    if (pfx.IsKeyEntry(al) && pfx.GetKey(al).Key.IsPrivate)
                    {
                        alias = al;
                        break;
                    }
                }

                //get our Private Key to Sign with

                //   AsymmetricCipherKeyPair caPair = DotNetUtilities.GetKeyPair(caCert.PrivateKey);
                AsymmetricKeyParameter caPair = pfx.GetKey(alias).Key;

                Al.Security.X509.X509Certificate cert = certGen.Generate(caPair);

                Pkcs12Store pk = new Pkcs12StoreBuilder().Build();
                // Add a Certificate entry
                X509CertificateEntry certEntry = new X509CertificateEntry(cert);
                pk.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

                AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(ackp.Private);
                pk.SetKeyEntry(cert.SubjectDN.ToString(), keyEntry, new X509CertificateEntry[] { certEntry }); // Note that we only have 1 cert in the 'chain'

                using (var filestream = new FileStream(file, FileMode.Create, FileAccess.ReadWrite))
                    pk.Save(filestream, password.ToCharArray(), new SecureRandom());

                X509Certificate2 cer = new X509Certificate2(File.ReadAllBytes(file), password);
                cer.Verify();
            }
            catch
            {
                return(false);
            }
            return(true);
        }
        private void GetUseNoticeSql(string uid, JObject responseData)
        {
            List <Notice> notices = NHibernateHelper.noticeManager.GetAll().ToList().OrderByDescending(i => i.StartTime).ToList();

            List <UserNotice>        userNotices = NHibernateHelper.userNoticeManager.GetListByUid(uid);
            List <UserNoticeJsonObj> tempList    = new List <UserNoticeJsonObj>();

            if (notices.Count != 0)
            {
                if (userNotices.Count != notices.Count)
                {
                    for (int i = 0; i < notices.Count; i++)
                    {
                        Notice     notice     = notices[i];
                        UserNotice userNotice = new UserNotice()
                        {
                            Uid      = uid,
                            NoticeId = notice.NoticeId,
                            State    = 0
                        };
                        if (!NHibernateHelper.userNoticeManager.Add(userNotice))
                        {
//                            OperatorFail(responseData);
                            MySqlService.log.Info($"添加用户通知错误:{userNotice.Uid},{userNotice.NoticeId},{userNotice.State}");
//                            return;
                        }
                    }
                    userNotices = NHibernateHelper.userNoticeManager.GetListByUid(uid);
                }
            }

            for (int i = 0; i < notices.Count; i++)
            {
                Notice notice = notices[i];
                for (int j = 0; j < userNotices.Count; j++)
                {
                    UserNotice userNotice = userNotices[j];

                    //维护通知
                    if (userNotice.NoticeId == 9)
                    {
                        continue;
                    }
                    if (userNotice.NoticeId == 4)
                    {
                        continue;
                    }

                    if (notice.NoticeId == userNotice.NoticeId)
                    {
                        UserNoticeJsonObj userNoticeJsonObj = new UserNoticeJsonObj()
                        {
                            notice_id    = notice.NoticeId,
                            title        = notice.Title,
                            content      = notice.Content,
                            type         = notice.Type,
                            state        = userNotice.State,
                            start_time   = notice.StartTime.ToLongDateString(),
                            end_time     = notice.EndTime.ToLongDateString(),
                            title_limian = notice.TitleLiMian,
                            from         = notice.From
                        };
                        tempList.Add(userNoticeJsonObj);
                    }
                }
            }
            OperatorSuccess(tempList, responseData);
        }
Example #9
0
 public OnSubscriptionEventArgs(UserNotice usernotice)
 {
     UserNotice = usernotice;
 }
Example #10
0
 protected abstract void ProcessChatMessage(UserNotice subNotice);
        private string CreateMessage(SubscriberMessage subscriberMessage, UserNotice twitchNotice)
        {
            string username = twitchNotice.Username;

            UserNotice.SubscriptionType subscriptionType = twitchNotice.MessageID;
            UserNotice.SubscriptionPlan subscriptionPlan = twitchNotice.SubPlan;

            string message = "";

            switch (subscriptionType)
            {
            case UserNotice.SubscriptionType.Gift:
            {
                message = subscriberMessage.GiftingMessage;
                break;
            }

            case UserNotice.SubscriptionType.Sub:
            case UserNotice.SubscriptionType.Resub:
            {
                switch (subscriptionPlan)
                {
                case UserNotice.SubscriptionPlan.Prime:
                {
                    message = subscriberMessage.PrimeMessage;
                    break;
                }

                case UserNotice.SubscriptionPlan.Tier1:
                {
                    message = subscriberMessage.TierOneMessage;
                    break;
                }

                case UserNotice.SubscriptionPlan.Tier2:
                {
                    message = subscriberMessage.TierTwoMessage;
                    break;
                }

                case UserNotice.SubscriptionPlan.Tier3:
                {
                    message = subscriberMessage.TierThreeMessage;
                    break;
                }
                }
                break;
            }
            }

            if (subscriptionType == UserNotice.SubscriptionType.Resub)
            {
                message += subscriberMessage.SubStreakMessage;
            }

            message = message.Replace(USERNAME_VARIABLE, subscriberMessage.Username);
            message = message.Replace(SUB_STREAK_VARIABLE, twitchNotice.ResubConsecutiveMonths.ToString());
            message = message.Replace(GIFT_RECIPIENT, twitchNotice.GiftedSubscriptionRecipientName);
            message = message.Replace(GIFTED_SUB_COUNT, twitchNotice.GiftedSubscriptionsCount.ToString());
            message = message.Replace(SUB_TYPE, twitchNotice.SubscriptionPlanName);

            return(message);
        }
        public string GetMessage(UserNotice twitchNotice)
        {
            string sUsername = twitchNotice.Username;

            return(CreateMessage(m_subscriberMessages.ContainsKey(sUsername.ToLower()) ? m_subscriberMessages[sUsername.ToLower()] : m_subscriberMessages["default"], twitchNotice));
        }
Example #13
0
        public async Task Seed()
        {
            var user1 = new User()
            {
                Username = "******",
                Email    = "*****@*****.**"
            };

            var user2 = new User()
            {
                Username = "******",
                Email    = "*****@*****.**"
            };

            var user3 = new User()
            {
                Username = "******",
                Email    = "*****@*****.**"
            };

            var user4 = new User()
            {
                Username = "******",
                Email    = "*****@*****.**"
            };

            await _userRepo.AddAsync(user1);

            await _userRepo.AddAsync(user2);

            await _userRepo.AddAsync(user3);

            await _userRepo.AddAsync(user4);

            var tag1 = new Tag()
            {
                Name = "Buy"
            };

            var tag2 = new Tag()
            {
                Name = "Sell"
            };

            var tag3 = new Tag()
            {
                Name = "Parking"
            };

            var tag4 = new Tag()
            {
                Name = "Party"
            };

            var tag5 = new Tag()
            {
                Name = "Food"
            };

            await _tagRepo.AddAsync(tag1);

            await _tagRepo.AddAsync(tag2);

            await _tagRepo.AddAsync(tag3);

            await _tagRepo.AddAsync(tag4);

            await _tagRepo.AddAsync(tag5);

            var userSubscr1 = new UserUserSubscription()
            {
                IsBlacklisted  = false,
                SubscribedUser = user2,
                User           = user1
            };

            var userSubscr2 = new UserUserSubscription()
            {
                IsBlacklisted  = false,
                SubscribedUser = user2,
                User           = user1
            };

            var userSubscr3 = new UserUserSubscription()
            {
                IsBlacklisted  = false,
                SubscribedUser = user3,
                User           = user1
            };

            await _userUserSubscribtionRepo.AddAsync(userSubscr1);

            await _userUserSubscribtionRepo.AddAsync(userSubscr2);

            await _userUserSubscribtionRepo.AddAsync(userSubscr3);

            var tagSubscr1 = new UserTagSubscription()
            {
                IsBlacklisted = false,
                Tag           = tag1,
                User          = user1
            };

            var tagSubscr2 = new UserTagSubscription()
            {
                IsBlacklisted = false,
                Tag           = tag2,
                User          = user1
            };

            var tagSubscr3 = new UserTagSubscription()
            {
                IsBlacklisted = false,
                Tag           = tag3,
                User          = user1
            };

            await _userTagSubscribtionRepo.AddAsync(tagSubscr1);

            await _userTagSubscribtionRepo.AddAsync(tagSubscr2);

            await _userTagSubscribtionRepo.AddAsync(tagSubscr3);

            var notice1 = new Notice()
            {
                Creator          = user1,
                CreationDateTime = DateTime.Now,
                Name             = "Lubie placki",
                Description      = "Lubie placki, chetnie kupie"
            };

            var notice2 = new Notice()
            {
                Creator          = user1,
                CreationDateTime = DateTime.Now,
                Name             = "Przeparkuj DW 666",
                Description      = "Krzywo zaparkowales, prosze przeparkuj"
            };

            await _noticeRepo.AddAsync(notice1);

            await _noticeRepo.AddAsync(notice2);

            var noticeTag1 = new NoticeTag()
            {
                Notice = notice1,
                Tag    = tag5
            };

            var noticeTag2 = new NoticeTag()
            {
                Notice = notice1,
                Tag    = tag1
            };

            var noticeTag3 = new NoticeTag()
            {
                Notice = notice2,
                Tag    = tag3
            };

            await _noticeTagRepo.AddAsync(noticeTag1);

            await _noticeTagRepo.AddAsync(noticeTag2);

            await _noticeTagRepo.AddAsync(noticeTag3);

            var userNotice1 = new UserNotice()
            {
                User   = user1,
                Notice = notice1,
                IsRead = false,
                IsSent = false
            };

            var userNotice2 = new UserNotice()
            {
                User   = user1,
                Notice = notice2,
                IsRead = false,
                IsSent = false
            };

            await _userNoticeRepo.AddAsync(userNotice1);

            await _userNoticeRepo.AddAsync(userNotice2);

            await _unitOfWork.CompleteAsync();
        }
Example #14
0
        private void HandleChannelMessage(string ircRawMessage, string channelName, IRCParser.TwitchChannelMessageType channelMessageType)
        {
            switch (channelMessageType)
            {
            case IRCParser.TwitchChannelMessageType.Usernotice:
            {
                UserNotice usernotice = new UserNotice(ircRawMessage);
                if (usernotice.MessageID != UserNotice.SubscriptionType.None)
                {
                    OnSubscriptionEventArgs subEvent = new OnSubscriptionEventArgs(usernotice);
                    OnSubscriptionReceived?.Invoke(this, subEvent);
                }

                return;
            }

            case IRCParser.TwitchChannelMessageType.ChannelMessage:
            {
                ChatMessage chatMessage = new ChatMessage(ircRawMessage);
                OnChatMessageReceivedEventArgs onChatReceivedEvent = new OnChatMessageReceivedEventArgs(chatMessage);
                OnChatMessageReceived?.Invoke(this, onChatReceivedEvent);
                return;
            }

            case IRCParser.TwitchChannelMessageType.LeftChannel:
            {
                // USER LEFT CHANNEL
                //:[email protected] PART #sirtucx
                string sUsername = ircRawMessage.Substring(1, ircRawMessage.IndexOf('!') - 1);
                OnUserLeaveEventArgs onUserLeaveEventArgs = new OnUserLeaveEventArgs(sUsername, channelName);
                OnUserLeaveEvent?.Invoke(this, onUserLeaveEventArgs);
                return;
            }

            case IRCParser.TwitchChannelMessageType.Mode:
            {
                string[] sModeSplit = ircRawMessage.Split(' ');

                if (sModeSplit[3] == "+o")
                {
                    // TODO: MOD JOINED CHANNEL
                }
                else if (sModeSplit[3] == "-o")
                {
                    // TODO: MOD LEFT CHANNEL
                }
                else
                {
                    // TODO: UNKNOWN
                }

                return;
            }

            case IRCParser.TwitchChannelMessageType.Notice:
            {
                if (ircRawMessage.Contains("Improperly formatted auth"))
                {
                    // TODO: AUTH ERROR
                }
                else if (ircRawMessage.Contains("has gone offline"))
                {
                    // TODO: HOST LEFT
                }
                else if (ircRawMessage.Contains("The moderators of this room are:"))
                {
                    // TODO: LIST ALL MODERATORS
                }
                else if (ircRawMessage.Contains("Your color has been changed."))
                {
                    // TODO: DETECT COLOR CHANGE
                }
                return;
            }

            case IRCParser.TwitchChannelMessageType.RoomState:
            {
                // TODO: ROOM STATE CHANGED
                return;
            }

            case IRCParser.TwitchChannelMessageType.UserState:
            {
                // USER JOINED CHANNEL
                // Example:  @badges=staff/1;color=#0D4200;display-name=ronni;emote-sets=0,33,50,237,793,2126,3517,4578,5569,9400,10337,12239;mod=1;subscriber=1;turbo=1;user-type=staff :tmi.twitch.tv USERSTATE #dallas
                UserState             userState             = new UserState(ircRawMessage);
                OnUserJoinedEventArgs onUserJoinedEventArgs = new OnUserJoinedEventArgs(userState);
                OnUserJoinedEvent?.Invoke(this, onUserJoinedEventArgs);
                return;
            }

            case IRCParser.TwitchChannelMessageType.ClearChat:
            {
                // TODO: HANDLE BANS/TIMEOUTS
                return;
            }
            }
        }
Example #15
0
        public ActionResult SendOrder(OrderHeader orderHeader, List <CartItem> cartItems)
        {
            int uid = int.Parse(Request.Cookies["upid"].Value);

            orderHeader.OrderNum      = $"GD{DateTime.Now:yyyyMMddHHmmss}{uid}";
            orderHeader.OrderDate     = DateTime.Now;
            orderHeader.UserID        = uid;
            orderHeader.ShippingID    = 1;
            orderHeader.OrderStatusID = 1;
            orderHeader.CreateDate    = DateTime.Now;

            db.OrderHeaders.Add(orderHeader);
            db.SaveChanges();

            var orderid  = db.OrderHeaders.OrderByDescending(o => o.OrderID).FirstOrDefault().OrderID;
            var ordernum = db.OrderHeaders.OrderByDescending(o => o.OrderID).FirstOrDefault().OrderNum;

            string tempmail = System.IO.File.ReadAllText(Server.MapPath(@"~/Areas/CheckProcess/Email/ordersucess.html"));//讀取html

            UriBuilder ValidateUrl = new UriBuilder(Request.Url)
            {
                Path = Url.Action("Account", "Detail", new
                {
                    area = "Members",
                    ad   = "ord"
                })
            };
            string email = db.Users.Find(uid).Email;

            CheckMethod.SendEmail(email, CheckMethod.VerificationCodeMailBody(tempmail, orderHeader, ValidateUrl.ToString().Replace("%3F", "?")));

            List <OrderDetail> orderDetails = new List <OrderDetail>();
            OrderDetail        orderDetail;

            foreach (var cartItem in cartItems)
            {
                orderDetail = new OrderDetail()
                {
                    OrderID        = orderid,
                    ProductID      = cartItem.ProductID,
                    ProductColorID = cartItem.ProductColorID,
                    ProductSizeID  = cartItem.ProductSizeID,
                    UnitPrice      = cartItem.UnitPrice,
                    OrderQTY       = cartItem.OrderQTY,
                    CreateDate     = DateTime.Now,
                    DiscountID     = cartItem.DiscountID
                };
                orderDetails.Add(orderDetail);
                var stockqty = db.ProductStocks.Where(s => s.ProductID == orderDetail.ProductID && s.ProductColorID == orderDetail.ProductColorID && s.ProductSizeID == orderDetail.ProductSizeID).FirstOrDefault().StockQTY;
                if (orderDetail.OrderQTY > stockqty)
                {
                    string     productname = db.Products.Find(orderDetail.ProductID).ProductName;
                    UserNotice notice      = new UserNotice()
                    {
                        UserID     = uid,
                        Comment    = $"訂單 [ {ordernum } ] 中 [ {productname} ] 已經為您完成預購,預購商品預計14~30天完成追加到貨,後續將會依序安排出貨,還請留意出貨通知",
                        IsRead     = false,
                        NoticeDate = DateTime.Now
                    };
                    db.UserNotices.Add(notice);
                    db.SaveChanges();
                }
            }
            db.OrderDetails.AddRange(orderDetails);
            db.SaveChanges();
            var carts = db.Carts.Where(c => c.UserID == uid).ToList();

            foreach (var cart in carts)
            {
                db.Carts.Remove(cart);
            }
            db.SaveChanges();
            Session.Remove("orderHeader");
            Session.Remove("cartItems");
            TempData.Add("ordernum", ordernum);
            return(Json(ordernum, JsonRequestBehavior.AllowGet));
        }