/// <summary>
        /// The button login click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void BtnLoginClick(object sender, RoutedEventArgs e)
        {
            var user = new UserClass(this.TxtUsername.Text, this.TxtPassword.Password, false);
            var result = false;
            var networking = new Networking(user);
            // AsyncNetworkCaller asyncNetwork = LoginThread;
            // asyncNetwork.BeginInvoke(networking, Callback, null);
            //asyncNetwork.Invoke()
            var login = new Thread(() =>
                {
                    result = LoginThread(networking);
                }) { Name = "Login thread" };
            login.Start();
            login.Join();

            // Networking networking = new Networking();
            if (!result)
            {
                return;
            }

            var main = new MainWindow(networking);
            main.Show();
            this.Close();
        }
Exemple #2
0
		public string FormatUserClass(UserClass userClass)
		{
			var uc = JanusFormatMessage
				.FormatUserClass(userClass, true);

			return uc.Length != 0 ? "&nbsp;" + uc : string.Empty;
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="ChatWindow"/> class.
 /// </summary>
 /// <param name="user">
 /// The user to chat with.
 /// </param>
 /// <param name="networking">
 /// The networking.
 /// </param>
 public ChatWindow(UserClass user, ref Networking networking)
 {
     InitializeComponent();
     this.friend = user;
     UserLabel.Content += user.UserName;
     this.net = networking;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="Networking"/> class. 
        /// Default constructor
        /// </summary>
        /// <param name="user">
        /// The user.
        /// </param>
        public Networking(UserClass user)
        {
            this.TheUser = user.Clone() as UserClass;
            // Creates the connection
            // var time = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
            this.tcpClient = new TcpClient(Settings.Default.Server, Settings.Default.Port);

            if (!this.tcpClient.Connected)
            {
                //throw this.failedConnect;
            }

            this.loggedIn = true;

            // this.Ping(tcpClient);
            this.stream = this.tcpClient.GetStream();
            this.ssl = new SslStream(this.stream, false, ValidateCert);
            this.ssl.AuthenticateAsClient(Settings.Default.Cert_Owner);
            this.writer = new BinaryWriter(this.ssl, Encoding.UTF8);
            this.reader = new BinaryReader(this.ssl, Encoding.UTF8);

            // Get the hello from the server
            var hello = this.reader.ReadInt32();
            if (hello == ImStatuses.ImHello)
            {
                // Send a hello to the server
                this.writer.Write(ImStatuses.ImHello);

                // var threadStart = new ParameterizedThreadStart(o => this.Listen(user));
                // var listenMeth = new Thread(threadStart);
                // listenMeth.Start();
            }
        }
Exemple #5
0
		/// <summary>
		/// Возвращает путь к иконке, ассоциированной с классом пользователя.
		/// </summary>
		/// <param name="provider"></param>
		/// <param name="userClass">Класс пользователя.</param>
		/// <returns>Путь к иконке, ассоциированной с классом пользователя.</returns>
		public static string GetUserImagePath(
			IServiceProvider provider,
			UserClass userClass)
		{
			var name = userClass != UserClass.User ? userClass.ToString() : string.Empty;
			return GetImageUri(provider, @"MessageTree\User" + name, StyleImageType.ConstSize);
		}
        private bool CreateUser(UserClass user)
        {
            var connection = new SqlCeConnection(this.path);
            try
            {
                var eng = new SqlCeEngine(this.path);
                var cleanup = new System.Threading.Tasks.Task(eng.Dispose);
                eng.CreateDatabase();
                cleanup.Start();
            }
            catch (Exception e)
            {
                EventLogging.WriteError(e);
            }
            connection.Open();

            var taco = new SqlCeDataAdapter();
            var userIdParam = new SqlCeParameter("userId", SqlDbType.Int, 60000, "UserID") { Value = user.UserId };
            var userNameParam = new SqlCeParameter("userName", SqlDbType.NVarChar, 128, "UserName") { Value = user.UserName };
            var passHashParam = new SqlCeParameter("passHash", SqlDbType.NVarChar, 128, "PassHash") { Value = user.PasswordHash };
            var friendsParam = new SqlCeParameter("friends", SqlDbType.VarBinary, 5000, "Friends") { Value = user.Friends };
            var dbCommand = new SqlCeCommand();
            dbCommand.Connection = connection;
            dbCommand.Parameters.Add(userNameParam);
            taco.InsertCommand.Parameters.Add(userNameParam);
            taco.InsertCommand.Parameters.Add(passHashParam);
            taco.InsertCommand.Parameters.Add(friendsParam);
            taco.InsertCommand.Parameters.Add("UserName", SqlDbType.NVarChar, 128);
            return false;
        }
Exemple #7
0
        protected void ButtonClick(object sender, EventArgs e)
        {
            UserClass objUser = new UserClass();

            if (objUser.Logout())
                PageHelper.Redirect("~/");
        }
        //end get user has id

        public static int append_to_user_log(UserClass thisuser)
        {
            int _logged = 0; 

            try
            {
                UserLog _newlog = new UserLog();

                if (thisuser.CompanyId == -1)
                { //employee
                    _newlog.ContactID = 0;
                    _newlog.EmployeeID = thisuser.UserId;
                }
                else
                {
                    _newlog.ContactID = thisuser.UserId;
                    _newlog.EmployeeID = 0;
                }

                _newlog.LogDate = DateTime.Now;
                _newlog.Save();
                _logged = 1;

            }
            catch 
            {
                _logged = 0;
            }
            return _logged; 
        }
Exemple #9
0
 public ReceiptView(RootPage parent, Object obj)
 {
     InitializeComponent ();
     mParent = parent;
     mObject = obj;
     mUserModel = mUserModel.GetUser ();
     NavigationPage.SetHasNavigationBar (this, false);
     InitializeLayout (obj);
 }
Exemple #10
0
        protected void btnGetPassword_Click(object sender, EventArgs e)
        {
            int teamid = Convert.ToInt32(txtteamid.Text);
            string username = txtusername.Text.ToString();
            int securityque = Convert.ToInt32(ddlSecurityQuestion.SelectedValue);
            string securityans=txtsecans.Text.ToString();

            UserClass objUser = new UserClass();

            string password = objUser.GetPassword(teamid, username, securityque,securityans);


        }
Exemple #11
0
 //添加用户
 public int addUser(User user, int classId)
 {
     int result = 0;
     if (Bll.ExistsName(user.LoginId)<=0)
     {
         result = userDao.addUser(user);
         string userType = user.UserType;
         if ("3".Equals(userType))               //如果是学生的话
         {
             UserClass userClass = new UserClass();
             userClass.UserId = user.UserId;
             userClass.ClassId = classId;
             userClassDao.addUserClass(userClass);
         }
     }
     return result;
 }
Exemple #12
0
		//public static int ActiveOrderStatus = OrderStatus.WAITING_CONFIRMATION;

		public static async Task<bool> SendOrderToRemote(UserClass user)
		{	
			AddressClass address = mAddressModel.GetActiveAddress (user.ActiveRegion);
			var fullname = address.Name.Split (' ');
			List<OrderObject> OrderList = new List<OrderObject> ();

			foreach (var product in Cart.ProductsInCart) {				
				string quantity = product.ProductNumberInCart.ToString();
				string productName = product.Name;
				string description = product.Quantity;
				string cost = (product.ProductNumberInCart * product.Price).ToString ();
				OrderObject orderObject;
				orderObject.Quantity = quantity;
				orderObject.Product = productName;
				orderObject.Description = description;
				orderObject.Price = cost;
				OrderList.Add (orderObject);
				//OrderList.Add("Quantity:" + quantity + "," + "Product:" + productName + "," + "Description:" + description + "," + "Price:" + cost);
			}	


			ParseObject order= new ParseObject(ParseConstants.ORDERS_CLASS_NAME);

			order [ParseConstants.ORDERS_ATTRIBUTE_ADDRESS] = address.Address;
			order [ParseConstants.ORDERS_ATTRIBUTE_ADDRESSDESC] = address.AddressDescription;
			order [ParseConstants.ORDERS_ATTRIBUTE_ADDRESSLINE3] = address.AddressLine3;
			order [ParseConstants.ORDERS_ATTRIBUTE_REGION] = user.ActiveRegion;
			order [ParseConstants.ORDERS_ATTRIBUTE_USERNAME] = fullname[0];
			order [ParseConstants.ORDERS_ATTRIBUTE_SURNAME] = fullname[1];
			order [ParseConstants.ORDERS_ATTRIBUTE_PHONE] = address.PhoneNumber;
			order [ParseConstants.ORDERS_ATTRIBUTE_STORE] = RegionHelper.DecideShopNumber (user.ActiveRegion);
			order [ParseConstants.ORDERS_ATTRIBUTE_STATUS] = (int)OrderStatus.WAITING_CONFIRMATION;
			order [ParseConstants.ORDERS_ATTRIBUTE_USERID] =  MyDevice.DeviceID;
			order [ParseConstants.ORDERS_ATTRIBUTE_ORDERARRAY] = Newtonsoft.Json.JsonConvert.SerializeObject (OrderList);

			bool bIsSucceeded = false;
			var tokenSource = new CancellationTokenSource ();
			var ct = tokenSource.Token;
			var task = order.SaveAsync (ct);
			bIsSucceeded = task.Wait (5000);
			tokenSource.Cancel ();
				

			return bIsSucceeded;
		}
Exemple #13
0
        protected void ButtonClick(object sender, EventArgs e)
        {
            var objUser = new UserClass();

            //Username: northbay
            //Password: 123
            string redirectUrl;

            //Authenticate User
            if (!objUser.AuthenticateUser(txt_user.Text, txt_password.Text, out redirectUrl))
            {
                lit_error.Text = "<div style=\"font-size:11px; font-style: italic; color: red; padding-bottom:5px;\">The email or password you've entered does not belong to any account.</div>";
            }
            else
            {
                Response.Redirect(redirectUrl);
            }
        }
        public string GetUserHasId(string UserName, string Password)
        {

            //return JSON serialised encrypted user info

            int _saved = 0;
            string _ids = ""; //user id and company id seperated by #
            UserClass _authLogin = new UserClass();

            _authLogin = UserClass.crypto1Login(UserName, Password);
            if (_authLogin != null && _authLogin.ID != Guid.Empty)
            {
                JavaScriptSerializer _js = new JavaScriptSerializer();
                _saved = Service_Security.append_to_user_log(_authLogin);
                _ids = _saved != 0 ? wwi_security.EncryptString(_authLogin.UserId + "#" + _authLogin.CompanyId, "publiship") : "";
            }

            return _ids;
        }
Exemple #15
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            //UserDBI .AddUser
            UserClass u = GetUserClass();
            if (u == null)
            {
                u = new UserClass();
            }

            u.Name = this.txtUserName.Text.Trim();
            u.Pwd = this.txtPwd.Text;
            u.WaterUserID = Convert.ToInt32(this.ddlWaterUser.SelectedValue);
            u.AllowEditData = this.cbAllowEdit.Checked;
            u.EditPassword = this.txtEditPassword.Text;
            u.Role = GetRole();
            u.Save();

            Response.Redirect("~/pLoginList.aspx");
        }
Exemple #16
0
 protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
 {
     try
     {
         Login loginControl = (Login)LoginView1.FindControl("Login1");
         String username = loginControl.UserName.ToString();
         String password = loginControl.Password.ToString();
         UserClass user = new UserClass();
         int idUser = user.ValidateAccess(username, password);
         if (idUser > 0)
         {
             Session.Add("idUser", idUser);
             FormsAuthentication.SetAuthCookie(username, true);
             //FormsAuthentication.RedirectFromLoginPage(username,true);
             //Response.Redirect("../UserPages/UserMain.aspx");
         }
     }
     catch (Exception ex) {}
 }
        public string GetUserAuth(string UserName, string Password)
        {
           
            //return JSON serialised encrypted user info
            
            int _saved = 0;
            string _json = "";
            UserClass _authLogin = new UserClass();
 
            _authLogin = UserClass.crypto1Login(UserName, Password);
            if (_authLogin != null && _authLogin.ID != Guid.Empty)
            {
                JavaScriptSerializer _js = new JavaScriptSerializer();
                _saved = Service_Security.append_to_user_log(_authLogin);
                _json += _saved != 0? wwi_security.EncryptString(_js.Serialize(_authLogin),"publiship"): ""; 
            }

            return _json;
        }
 public void LoadGridNormal()
 {
     UserClass objUser = new UserClass();
     int intCurrentUserId = objUser.GetCurrentUserByApp().Id;
     string CurrentUserLoginName = objUser.GetCurrentUserByApp().LoginName;
     TimeOffRequests objTOR = new TimeOffRequests();
     List<TimeOffRequests> objTORList = objTOR.GetMyProcessingRequests( intCurrentUserId, CurrentUserLoginName);
     //ProcessDateOnFulldays(ref objTOR);
     if (objTORList.Count > 0)
     {
         lvNormal.DataSource = objTORList;
         lvNormal.DataBind();
         lvNormal.Visible = true;
         this.dummyTable2.Visible = false;
     }
     else
     {
         this.lvNormal.Visible = false;
         this.dummyTable2.Visible = true;
     }                
 }
Exemple #19
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            bool loginStatus = false;

            int teamid=Convert.ToInt32(txtteamid.Text);
            string username = txtusername.Text.ToString();
            string password = txtpswd.Text.ToString();

               UserClass objlogin = new UserClass();

            loginStatus = objlogin.CheckUser(teamid,username,password);

            if (loginStatus)
            {
                Response.Redirect("Home.aspx");
            }
            else
            {
                Response.Redirect("login.aspx");
            }
        }
        private async void GetFavouriteBoxVideo()
        {
            pr_Load.Visibility = Visibility.Visible;
            loading = true;
            try
            {
                getLogin = new UserClass();
                List<GetFavouriteBoxsVideoModel> lsModel = await getLogin.GetFavouriteBoxVideo(fid, pageNum);
                if (lsModel != null)
                {
                    foreach (GetFavouriteBoxsVideoModel item in lsModel)
                    {
                        MaxPage = item.pages;
                        User_ListView_FavouriteVideo.Items.Add(item);
                    }
                    //为下一页做准备
                    pageNum++;
                    if (pageNum > MaxPage)
                    {
                        User_load_more.Visibility = Visibility.Collapsed;
                    }
                }
                else
                {
                    MessageDialog md = new MessageDialog("信息获取失败!");
                    await md.ShowAsync();
                    User_load_more.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                await new MessageDialog("读取收藏夹信息失败", ex.Message).ShowAsync();
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
                loading = false;
            }

        }
Exemple #21
0
		/// <summary>
		/// Преобразовывает тип пользователя в строку.
		/// </summary>
		/// <param name="userClass">Тип пользователя. <see cref="UserClass"/></param>
		/// <param name="isHtml">Использовать подсветку.</param>
		/// <returns>Строковое представление ипа пользователя.</returns>
		public static string FormatUserClass(UserClass userClass, bool isHtml)
		{
			var result = string.Empty;

			switch (userClass)
			{
				case UserClass.Admin:
					result = "admin";
					if (isHtml)
						result = "<font color='darkred'>" + result + "</font>";
					break;

				case UserClass.Moderator:
					result = "moderator";
					if (isHtml)
						result = "<font color='red'>" + result + "</font>";
					break;

				case UserClass.Team:
					result = "rsdn";
					if (isHtml)
						result = "<font color='blue'>" + result + "</font>";
					break;

				case UserClass.Expert:
					result = "expert";
					if (isHtml)
						result = "<font color='green'>" + result + "</font>";
					break;
			}

			return result.Length > 0 ? "[" + result + "]" : result;
		}
Exemple #22
0
 /// <summary>
 /// 登录,亦为其他接口提供权限验证服务
 /// </summary>
 /// <param name="username"></param>
 /// <param name="password"></param>
 /// <returns></returns>
 public static UserLoginResponse Login(string username, string password)
 {
     return(UserClass.Login(username, password, System.Web.HttpContext.Current.Request.UserHostAddress));
 }
        public bool IsConcernedApprover(TimeOffRequests objTOR)
        {
            //GetCurrentuser and check is he among 3 approver
            // validate is he concern approver
            string concernedApprover="";
            UserClass objUser = new UserClass();         
            User CurrentUser= objUser.GetCurrentUserByApp();
            if (objTOR.Approver3 != null || objTOR.Approver3 != "")
                concernedApprover = objTOR.Approver3;
            else if (objTOR.Approver2 != null || objTOR.Approver2 != "")
                 concernedApprover = objTOR.Approver2;
                 else if (objTOR.Approver1 != null || objTOR.Approver1 != "")
                       concernedApprover = objTOR.Approver1;

            if (concernedApprover == "")
                return false;
            else
            {
                if (CurrentUser.Title == objTOR.Approver1)
                    return true;
                else
                    return false;
            }
        }
 public void Insert(UserClass entitiy)
 {
     _userDAL.Add(entitiy);
 }
 public void Update(UserClass entitiy)
 {
     _userDAL.Update(entitiy);
 }
Exemple #26
0
 void Start()
 {
     _user = GetComponent <UserClass>();
 }
Exemple #27
0
        public ActionResult AddUser(UserClass uc)
        {
            Membership.CreateUser(uc.UserName, uc.Password, uc.Email, uc.PasswordQuestion, uc.PasswordAnswer, true, out MembershipCreateStatus status);
            string createMessage = "";

            switch (status)
            {
            case MembershipCreateStatus.Success:
                break;

            case MembershipCreateStatus.InvalidUserName:
                createMessage = "Geçersiz kullanıcı adı.";
                break;

            case MembershipCreateStatus.InvalidPassword:
                createMessage = "Geçersiz parola";
                break;

            case MembershipCreateStatus.InvalidEmail:
                createMessage = "Geçersiz e-mail";
                break;

            case MembershipCreateStatus.DuplicateUserName:
                createMessage = "Kullanılmış kullanıcı adı";
                break;

            case MembershipCreateStatus.DuplicateEmail:
                createMessage = "Kullanılmış email";
                break;

            case MembershipCreateStatus.UserRejected:
                createMessage = "Kullanıcı engellendi";
                break;

            case MembershipCreateStatus.ProviderError:
                createMessage = "Sağlayıcı hatası";
                break;

            case MembershipCreateStatus.InvalidQuestion:
                createMessage = "Geçersili gizli soru";
                break;

            case MembershipCreateStatus.InvalidAnswer:
                createMessage = "Geçersiz gizli cevap";
                break;

            case MembershipCreateStatus.InvalidProviderUserKey:
                createMessage = "Geçersiz kullanıcı anahtarı";
                break;

            case MembershipCreateStatus.DuplicateProviderUserKey:
                createMessage = "Kullanılmmış kullanıcı anahtarı";
                break;

            default:
                break;
            }

            ViewBag.createMessage = createMessage;
            if (createMessage == "")
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                return(View());
            }
        }
Exemple #28
0
        public HttpResponseMessage Rechargeuser(dynamic SearchForm)
        {
            try
            {
                string RegID    = string.Empty;
                string Amt      = string.Empty;
                string Mode     = string.Empty;
                string modeType = string.Empty;
                string UserID   = string.Empty;
                string SKey     = string.Empty;
                SKey = (string)SearchForm.SKey;

                string AddressBTC = string.Empty;
                AddressBTC = (string)SearchForm.AddressBTC;



                UserID = (string)SearchForm.UserID;
                string MobileNo  = string.Empty;
                string FileName  = string.Empty;
                string ConverAmt = string.Empty;


                RegID    = (string)SearchForm.RegID;
                Amt      = (string)SearchForm.Amt;
                Mode     = (string)SearchForm.Mode;
                modeType = (string)SearchForm.modeType;
                MobileNo = (string)SearchForm.MobileNo;

                ConverAmt = (string)SearchForm.CAmt;



                UserClass Obj = new UserClass();
                DataTable DT  = new DataTable();

                if (Mode == "FUND")
                {
                    Obj.Rechargeuser(RegID, Amt, UserID, SKey);
                    string OUtMsg = "";
                    if (Obj.OutMsg == "1")
                    {
                        OUtMsg = Obj.OutMsg;
                    }
                    else
                    {
                        OUtMsg = Obj.OutMsg;
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK, OUtMsg));
                }

                else
                {
                    Obj.RechargeuserBTC(RegID, Amt, UserID, modeType, ConverAmt, SKey, AddressBTC, "1");
                    string OUtMsg = "";
                    string OutID  = "";
                    if (Obj.OutMsg == "1")
                    {
                        OUtMsg = Obj.OutMsg;
                    }
                    else
                    {
                        OUtMsg = Obj.OutMsg;
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, new { SeatArragement = OUtMsg, OutID = Obj.OutID }));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "500_INTERNAL_SERVER_ERROR"));
            }
        }
 public void TestInitialize()
 {
     user = new UserClass(name, age, primaryTransportCurrent);
     car  = new CarClass("TestCar", "Benzin", "20.5", user);
 }
Exemple #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Page.User.Identity.IsAuthenticated)
                {
                    Log.Warn("User " + User.Identity.Name + " already logged in. Redirecting to login page.");
                    Response.Redirect("~/Dashboard", false);
                }

                if (!(Request.IsAuthenticated))
                {
                    GoogleConnect.ClientId     = "947447230315-5lfekj88qber9m9pgq8g8t7oo7g4ih3h.apps.googleusercontent.com";
                    GoogleConnect.ClientSecret = "eSBeVilwnaDm7Rk8LDh-_SY4";
                    GoogleConnect.RedirectUri  = Request.Url.AbsoluteUri.Split('?')[0];

                    if (!string.IsNullOrEmpty(Request.QueryString["code"]))
                    {
                        var code    = Request.QueryString["code"];
                        var json    = GoogleConnect.Fetch("me", code);
                        var profile = new JavaScriptSerializer().Deserialize <GoogleProfile>(json);
                        _userEmail = profile.Emails.Find(email => email.Type == "account").Value;
                        UserId     = 0;
                        var strUserId = new UserClass().ValidateUser(_userEmail);

                        Log.Info("User [" + _userEmail + "] is not authenticated.");
                        Log.Info("User [" + _userEmail + "] login process is started.");
                        Log.Info("Google Auth Code: " + code);
                        Log.Info("Google Auth Redirect Uri: " + GoogleConnect.RedirectUri);

                        if (strUserId != "")
                        {
                            UserId = int.Parse(strUserId);
                        }

                        if (UserId != 0)
                        {
                            Log.Info("User Id: " + UserId);
                            new UserClass().UpdateLastLoginDate(UserId.ToString());
                            Log.Info("User [" + _userEmail + "] Last Login Date is updated");
                            FormsAuthentication.SetAuthCookie(UserId.ToString(), false);
                            Response.Redirect("~/Dashboard", false);
                            Log.Info("User [" + _userEmail + "] redirecting to Dashboard Page");
                        }
                        else
                        {
                            Log.Warn("User [" + _userEmail + "] is not valid or active.");
                            var warningMessage = Language == "tr"
                                ? "[" + _userEmail + "] kullanıcısı geçersiz ya da aktif değil."
                                : @"User [" + _userEmail + @"] is not valid or active.";

                            WarningText.Text = warningMessage;

                            FormsAuthentication.SignOut();
                            Session.Abandon();
                        }
                    }
                    if (Request.QueryString["error"] == "access_denied")
                    {
                        Log.Warn("Google Auth Access Denied! " + Request.QueryString["error"]);
                        ClientScript.RegisterClientScriptBlock(GetType(), "alert", "alert('Access denied.')", true);
                    }
                }
            }

            catch (Exception ex)
            {
                Log.Error("Exception: " + ex);
            }
        }
Exemple #31
0
 public void TestInitialize()
 {
     user = new UserClass(name, age, primaryTransportStart, primaryTransportCurrent, totalXP);
     car  = new CarClass("Benzin", "20.5", user);
 }
Exemple #32
0
 public void TestInitialize()
 {
     user = new UserClass(name, age, primaryTransportStart, primaryTransportCurrent, totalXP);
 }
Exemple #33
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //if (!Page.IsPostBack)
            //{
            if (isLoggedIn())
            {
                //orderid and title id are passed through - remove semi-colon?
                //check querystring or default to label where order id might have been passed back from order search form
                string _orderno = Request.QueryString["pod"] != null?wwi_security.DecryptString(Request.QueryString["pod"].Replace(",", ""), "publiship") : null;

                if (!string.IsNullOrEmpty(_orderno))
                {
                    //100112 check to see if attached to a document folder other than it's order number
                    string _docfolder = Request.QueryString["dfd"] != null?wwi_security.DecryptString(Request.QueryString["dfd"].Replace(",", ""), "publiship") : null;

                    //100112 check to see folder status
                    string _cdir = Request.QueryString["cd"] != null ? Request.QueryString["cd"].Replace(",", "") : null;
                    if (!string.IsNullOrEmpty(_cdir))
                    {
                        this.dxhfmanager.Set("cdir", _cdir);
                    }
                    //160112 get house b/l
                    string _housebl = Request.QueryString["hbl"] != null?wwi_security.DecryptString(Request.QueryString["hbl"].Replace(",", ""), "publiship") : null;

                    //if (_orderno != null)

                    //{
                    //this.dxhfmanager.Set("ord", _orderno);
                    //this.dxlblorderno1.Text = wwi_security.DecryptString(_orderno, "publiship");

                    //}
                    //else
                    //{
                    //    this.dxlblorderno1.Text = "";
                    //}


                    //role based security
                    //companyid-1 internal users can upload/edit/delete
                    //other users are view only
                    //this DOES NOT Work!
                    //UserClass _thisuser = (UserClass)HttpContext.Current.Session["user"];
                    //this.dxfmpod.SettingsPermissions.Role = _thisuser.CompanyId!=-1? "editor": "viewer";

                    UserClass _thisuser = (UserClass)HttpContext.Current.Session["user"];
                    bool      _iseditor = _thisuser.CompanyId == -1 ? true : false; //full rights for internal users only (companyid=-1)
                    this.dxhfmanager.Set("uid", wwi_security.EncryptString(_thisuser.UserId.ToString(), "publiship"));
                    set_fm_permissions(_iseditor);
                    set_visible_folder(_iseditor, _orderno, _docfolder);


                    //datatable of selected orderno's
                    bind_order_data(wwi_func.vint(_orderno), _housebl);

                    this.dxfmpod.ClientVisible = true;

                    this.dxpnlerr.Visible  = false;
                    this.dxpnlinfo.Visible = false;
                }
                else
                {
                    Response.Redirect("../tracking/shipment_tracking.aspx?");
                }
            }
            else
            {
                Response.Redirect("../user_account/signin.aspx?" + "rp=" + wwi_security.EncryptString("tracking/file_manager", "publiship"));
            }
            //}
        }
        catch (Exception ex)
        {
            this.dxlblerr.Text    = ex.Message.ToString();
            this.dxpnlerr.Visible = true;
        }
    }
    /// <summary>
    /// check user name/password combination
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cmdLogin_Click(object sender, System.EventArgs e)
    {
        UserClass  _userlogin = new UserClass();
        HttpCookie _acookie   = new HttpCookie("user");
        string     _message   = null;

        try
        {
            string _username = txtUserName.Text.Replace("'", "''");
            string _pass     = wwi_security.EncryptString(txtPassword.Text.Replace("'", "''"), "publiship");

            _userlogin = _userlogin.Login(_username, _pass);

            if (_userlogin != null && _userlogin.loginValue != 0)
            //if (_userlogin != null && _userlogin.ID != Guid.Empty)
            {
                Session["user"] = _userlogin;


                if (Request.Browser.Cookies)
                {
                    if (dxchbSavePassword.Checked)
                    {
                        _acookie["userlogin"] = txtUserName.Text;
                        _acookie["userpwd"]   = _pass; //txtPassword.Text;
                        //expires  after 1 year
                        _acookie.Expires = DateTime.Now.AddYears(1);
                    }
                    else
                    {
                        //expires  midnight
                        //DateTime _dt = Convert.ToDateTime(DateTime.Now.ToShortDateString() + " 00:00:00");

                        //expires in 1 hour
                        DateTime _dt = DateTime.Now.AddMinutes(10);  //DateTime.Now + new TimeSpan(1, 0, 0);
                        _acookie.Expires = _dt;
                    }
                    Response.Cookies.Add(_acookie);
                }
            }
            else
            {
                if (_userlogin == null)
                //if (_userlogin == null || _userlogin.ID == Guid.Empty)
                {
                    //this.lblMsg.Text = "<div class='fberrorbox'>Null login</div>";
                    _message = " Invalid user name or password";
                }
                else //userLogin.loginValue = 0 to indicate error
                {
                    _message = " Not able to verify user due to a technical error";
                    //this.lblMsg.Text = "<div class='fberrorbox'>Invalid Login</div>";
                }
            }
        }
        catch
        {
            _userlogin = null;
            Session.Remove("user");
        }
        finally {
            //if (_userlogin != null)
            if (_message == null)
            {
                Redirect(true);
            }
            else
            {
                _userlogin = null;
                Session.Remove("user");
                this.lblmsg.Text      = _message;
                this.dxpnlmsg.Visible = true;
            }
        }//end finally
    }
Exemple #35
0
        /// <summary>
        /// 出单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="isExternal">是否外部(第三方机构)调用</param>
        /// <returns></returns>
        public static PurchaseResponseEntity Purchase(PurchaseRequestEntity request, bool isExternal, bool isSync)
        {
            PurchaseResponseEntity response = new PurchaseResponseEntity();

            if (Common.CheckIfSystemFailed(response))
            {
                return(response);
            }

            try
            {
                DateTime dtNow = Common.GetDatetime();//DateTime.Now;

                if (!isSync)
                {
                    #region  效性验证
                    if (request.flightDate < dtNow.AddMinutes(Common.IssuingDeadline)) //如果填写的起飞时间已过
                    {
                        if (request.flightDate.Date == dtNow.Date)                     //当日起飞,则进行时间部分的验证
                        {
                            if (request.flightDate.TimeOfDay.Ticks > 0)
                            {
                                response.Trace.ErrorMsg = "请输入准确的起飞时间!";
                            }
                            else//时间部分为零(PNR未能导入)
                            {
                                response.Trace.ErrorMsg = "请输入起飞时间!";
                            }
                            return(response);
                        }
                        else//日期是昨天、昨天以前
                        {
                            response.Trace.ErrorMsg = "请输入正确的乘机日期!";
                            return(response);
                        }
                    }
                    else if ((request.flightDate - dtNow) > new TimeSpan(180, 0, 0, 0, 0))
                    {
                        response.Trace.ErrorMsg = "乘机时间太过遥远(已超过180天)!";
                        return(response);
                    }

                    if (string.IsNullOrEmpty(request.flightNo))
                    {
                        response.Trace.ErrorMsg = "航班号不能为空!";
                        return(response);
                    }

                    if (string.IsNullOrEmpty(request.customerID))
                    {
                        response.Trace.ErrorMsg = "乘客证件号码不能为空!";
                        return(response);
                    }
                    else
                    {
                        request.customerID = request.customerID.ToUpper();
                        request.customerID = StringHelper.MiscelHelper.Full2Half(request.customerID);

                        if (request.customerIDType == IdentityType.身份证 && !Common.CheckIDCard(request.customerID))
                        {
                            response.Trace.ErrorMsg = "身份证号码填写有误,请核对!";
                            return(response);
                        }
                    }

                    if (string.IsNullOrEmpty(request.customerName))
                    {
                        response.Trace.ErrorMsg = "乘客姓名不能为空!";
                        return(response);
                    }
                    else
                    {
                        if (request.customerName.Contains("  "))
                        {
                            response.Trace.ErrorMsg = "客户名称不合法: 姓名不能有连续空格!";
                            return(response);
                        }
                    }

                    if (!string.IsNullOrEmpty(request.customerPhone))
                    {
                        if (!Regex.IsMatch(request.customerPhone, "^1[3458][0-9]{9}$"))
                        {
                            response.Trace.ErrorMsg = "手机号码格式不正确!";
                            return(response);
                        }
                    }
                    #endregion
                }

                UserLoginResponse userLogin = UserClass.AccessCheck(request.username, request.password);

                if (string.IsNullOrEmpty(userLogin.Trace.ErrorMsg))
                {
                    if (UserClass.IsParentDisabled(request.username))
                    {
                        response.Trace.ErrorMsg = "由于您的上级账号已被冻结,所以您无法出单,请联系您的上级用户!";
                        return(response);
                    }

                    if (Common.PaymOnline)
                    {
                        if (userLogin.Balance <= 0)
                        {
                            response.Trace.ErrorMsg = "账户余额不足,请充值或联系您的上级用户!";
                            return(response);
                        }
                    }

                    //if (Case.IsIssued(request.flightDate, request.customerName, request.customerID))
                    //{
                    //    response.Trace.ErrorMsg = "该旅客信息已经入库,请勿重复打印!";
                    //    return response;
                    //}

                    DataSet dsProduct = Product.GetProduct(request.InsuranceCode);

                    if (dsProduct.Tables[0].Rows.Count == 0)
                    {
                        response.Trace.ErrorMsg = "找不到您所指定的产品,或者该产品已停用,请重新选择!";
                        return(response);
                    }

                    DataRow drProduct            = dsProduct.Tables[0].Rows[0];
                    bool    isIssuingRequired    = Convert.ToBoolean(drProduct["IsIssuingRequired"]);
                    bool    isIssuingLazyEnabled = Convert.ToBoolean(drProduct["IsIssuingLazyEnabled"]);
                    bool    isMobileNoRequired   = Convert.ToBoolean(drProduct["IsMobileNoRequired"]);
                    if (isMobileNoRequired)
                    {
                        if (Regex.IsMatch(request.customerPhone, "^1[3458][0-9]{9}$"))
                        {
                            //处理销售点仅用一个手机号给所有乘客出保险的偷懒行为
                            if (Case.CountMobile(request.customerPhone, request.username) > 5)
                            {
                                response.Trace.ErrorMsg = "该手机号已重复使用多次,请如实填写以提供短信服务!";
                                return(response);
                            }
                        }
                        else
                        {
                            response.Trace.ErrorMsg = "该款产品必须提供手机号,请检查是否正确!";
                            return(response);
                        }
                    }
                    else if (!string.IsNullOrEmpty(request.customerPhone))
                    {
                        if (Regex.IsMatch(request.customerPhone, "^1[3458][0-9]{9}$"))
                        {
                            //处理销售点仅用一个手机号给所有乘客出保险的偷懒行为
                            if (Case.CountMobile(request.customerPhone, request.username) > 5)
                            {
                                response.Trace.ErrorMsg = "该手机号已重复使用多次,请如实填写,或者不填!";
                                return(response);
                            }
                        }
                        else
                        {
                            response.Trace.ErrorMsg = "请正确填写手机号,或者不填!";
                            return(response);
                        }
                    }

                    int    interface_Id = isIssuingRequired ? Convert.ToInt32(drProduct["interface_Id"]) : 0;//若非对接产品,接口ID置为0,以免影响接口出单统计
                    object caseSupplier = drProduct["productSupplier"];
                    int    caseDuration = Convert.ToInt32(drProduct["productDuration"]);
                    object productName  = drProduct["productName"];

                    //基于产品的 IP 过滤
                    string include           = drProduct["FilterInclude"].ToString().Trim();
                    string exclude           = drProduct["FilterExclude"].ToString().Trim();
                    string comment           = drProduct["FilterComment"].ToString();
                    string ip                = System.Web.HttpContext.Current.Request.UserHostAddress;
                    string ipLocation        = string.Empty;
                    bool   isValidIpLocation = true;
                    try
                    {
                        Ip2Location.Ip2Location ip2lo = new Ip2Location.Ip2Location();
                        ipLocation = ip2lo.GetLocation(ip);
                        if (!IsIpChecked(ipLocation, include, exclude))
                        {
                            string strLog = "ProductFilter User:{0} IP:{1} Location:{2} Include:{3} Exclude:{4}";
                            strLog = string.Format(strLog, request.username, ip, ipLocation, include, exclude);
                            Common.LogIt(strLog);
                            response.Trace.Detail   = comment;
                            response.Trace.ErrorMsg = "无法出单!(e001)";// "产品区域限制,禁止出单!";
                            return(response);
                        }
                    }
                    catch (Exception ee)
                    {
                        isValidIpLocation = false;
                        ipLocation        = ee.Message.Substring(0, 20);
                    }

                    response.AgentName = userLogin.DisplayName;
                    //response.ValidationPhoneNumber = UserClass.GetValidationPhoneNumber(request.username);

                    #region 数据库事务
                    //2008.4.19 改用全手工方式 因为 Nbear 的事务处理似乎不能及时释放掉connection,越来越的连接…满负荷…导致客户端访问webservice连接超时
                    using (SqlConnection cnn = new SqlConnection(Common.ConnectionString))
                    {
                        cnn.Open();
                        using (SqlTransaction tran = cnn.BeginTransaction())
                        {
                            string strSql = "";

                            try
                            {
                                //有限的行级排它锁with(rowlock,xlock,readpast),保证该行不会被其他进程读取,同时不会阻塞其他行的读取和主键更新
                                //2011.9.28 日志发现该语句依然可能导致死锁 原因:该语句除了对那一行上X锁之外,对top2、top3…(满足where条件的行)上IX锁
                                //而X和IX锁是互斥的,
                                //                                strSql = @"
                                //select top 1 * from t_serial with(rowlock,xlock,readpast)
                                //where caseOwner = '{0}' and caseSupplier = '{1}'
                                //order by caseNo asc";
                                strSql = @"
  delete top(1)
  from t_serial WITH (rowlock, READPAST)
  output deleted.caseNo, deleted.caseSupplier,
  deleted.locationInclude, deleted.locationExclude, deleted.locationComment
  where caseOwner = '{0}' and caseSupplier = '{1}'";
                                strSql = string.Format(strSql, request.username, caseSupplier);
                                DataSet    dsSerial = new DataSet();
                                SqlCommand cmm      = new SqlCommand("", cnn, tran);
                                cmm.CommandText = strSql;
                                SqlDataAdapter sda = new SqlDataAdapter(cmm);
                                sda.Fill(dsSerial);

                                if (dsSerial.Tables[0].Rows.Count == 0)
                                {
                                    tran.Rollback();
                                    response.Trace.ErrorMsg = "没有可用的单证号,请联系相关业务人员!";
                                    return(response);
                                }

                                DataRow drSerial = dsSerial.Tables[0].Rows[0];
                                string  caseNo   = drSerial["caseNo"].ToString();
                                response.CaseNo = caseNo;

                                if (isValidIpLocation)//上面验证若通过则此处继续审查
                                {
                                    //基于号段的 IP 过滤
                                    include = drSerial["locationInclude"].ToString();
                                    exclude = drSerial["locationExclude"].ToString();
                                    comment = drSerial["locationComment"].ToString();
                                    if (!IsIpChecked(ipLocation, include, exclude))
                                    {
                                        tran.Rollback();
                                        string strLog = "SerialFilter User:{0} IP:{1} Location:{2} Include:{3} Exclude:{4}";
                                        strLog = string.Format(strLog, request.username, ip, ipLocation, include, exclude);
                                        Common.LogIt(strLog);
                                        response.Trace.Detail   = comment;
                                        response.Trace.ErrorMsg = "无法出单!(e002)";//"号段区域限制,禁止出单!";
                                        return(response);
                                    }
                                }

                                //insert 语句本身不会阻塞,但是却引起其他线程的select阻塞
                                /*用MsSql2005的 output inserted.caseID 新语法代替原来的 SELECT CAST(scope_identity() AS int) 以返回自增列ID;*/
                                strSql = @"
insert into t_Case
(caseNo,caseOwner,caseSupplier,productID,customerFlightDate,customerFlightNo,customerID,customerName,customerPhone,
    parentPath,datetime,isPrinted,enabled,caseDuration, ip, IpLocation, reserved, customerGender, customerBirth, interface_Id)
output inserted.caseID
values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}', '{16}', '{17}', '{18}', '{19}');";

                                string parentPath = userLogin.ParentPath + request.username + "/";//用于判定单证的层级归属
                                string gender     = request.customerGender == Gender.Female ? "女" : "男";
                                //if (interface_Id == null)//无需判断,空值、空格使用单引号括起插入到int型字段的时候,数据库会自动转成0值
                                //    interface_Id = 0;

                                strSql = string.Format(strSql, caseNo, request.username, drSerial["caseSupplier"], request.InsuranceCode.Trim(),
                                                       request.flightDate, request.flightNo.Trim(), request.customerID.Trim(), request.customerName.Trim(), request.customerPhone.Trim(), parentPath, dtNow.ToString(),
                                                       0, 1, caseDuration, ip, ipLocation, request.PNR, gender, request.customerBirth, interface_Id);
                                cmm.CommandText = strSql;
                                int caseId = Convert.ToInt32(cmm.ExecuteScalar()); //返回自增列id
                                //cmm.ExecuteNonQuery();
                                strSql = string.Empty;                             //清空SQL语句,以防干扰下面的语句合并

                                if (isIssuingRequired)
                                {
                                    #region 投保数据对接
                                    string      IOC_Class_Alias      = drProduct["IOC_Class_Alias"].ToString();
                                    string      IOC_Class_Parameters = drProduct["IOC_Class_Parameters"].ToString();
                                    IssueEntity entity = new IssueEntity();
                                    entity.Name     = request.customerName;
                                    entity.ID       = request.customerID;
                                    entity.IDType   = request.customerIDType;
                                    entity.Gender   = request.customerGender;
                                    entity.Birthday = request.customerBirth;
                                    //如果是今天之后的乘机日期,则时间部分置为0
                                    entity.EffectiveDate = request.flightDate.Date > DateTime.Today ? request.flightDate.Date : request.flightDate;
                                    entity.ExpiryDate    = request.flightDate.AddDays(caseDuration - 1);
                                    entity.PhoneNumber   = request.customerPhone;
                                    entity.FlightNo      = request.flightNo;

                                    entity.IsLazyIssue          = isIssuingLazyEnabled;
                                    entity.DbCommand            = cmm;
                                    entity.IOC_Class_Alias      = IOC_Class_Alias;
                                    entity.IOC_Class_Parameters = IOC_Class_Parameters;
                                    entity.CaseNo      = caseNo;
                                    entity.CaseId      = caseId.ToString();
                                    entity.InterfaceId = interface_Id;
                                    entity.Title       = productName.ToString();

                                    TraceEntity validate = Case.Validate(entity);
                                    if (string.IsNullOrEmpty(validate.ErrorMsg))
                                    {
                                        if (entity.IsLazyIssue && !isExternal)
                                        {
                                            //Thread th = new Thread(Case.IssueAsync);
                                            //th.Start(entity);
                                            entity.ConnectionString = Common.ConnectionString;
                                            //entity.MaxRedelivery = 3;
                                            Common.AQ_Issuing.EnqueueObject(entity);
                                        }
                                        else
                                        {
                                            IssuingResultEntity result = Case.Issue(entity);
                                            if (string.IsNullOrEmpty(result.Trace.ErrorMsg))
                                            {
                                                response.SerialNo              = result.PolicyNo;//暂借用该SerialNo字段
                                                response.PolicyNo              = result.PolicyNo;
                                                response.Insurer               = result.Insurer;
                                                response.AmountInsured         = result.AmountInsured;
                                                response.ValidationWebsite     = result.Website;
                                                response.ValidationPhoneNumber = result.CustomerService;
                                                //如果中途转投了别的接口
                                                if (entity.InterfaceId != interface_Id)
                                                {
                                                    strSql = "UPDATE [t_Case] SET [interface_Id] = {0} WHERE caseNo = '{1}'; ";
                                                    strSql = string.Format(strSql, entity.InterfaceId, caseNo);
                                                }
                                            }
                                            else
                                            {
                                                tran.Rollback();

                                                StringBuilder sbLog = new StringBuilder();
                                                sbLog.AppendLine(Common.XmlSerialize <IssueEntity>(entity));
                                                sbLog.Append(result.Trace.ErrorMsg);
                                                Common.LogIt(sbLog.ToString());

                                                response.Trace = result.Trace;
                                                return(response);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        tran.Rollback();
                                        response.Trace = validate;
                                        return(response);
                                    }

                                    #endregion
                                    if (Common.Debug)
                                    {
                                        //Test.TestIt(entity);
                                    }
                                }

                                //修改出单量 主键更新 合并到下面的SQL语句一起执行
                                strSql += "update t_user set CountConsumed = CountConsumed + 1 where username = '******'; ";

                                #region 扣款
                                string[] parentArray = parentPath.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);//形如:/admin/tianzhi/bcaaa/bcaaa0150/
                                string   root        = parentArray[0];
                                string   distributor = "";
                                if (parentArray.Length > 1)
                                {
                                    distributor = parentArray[1];//第二级用户名既是一级分销商
                                    strSql     += "update t_User set balance = balance - price where username = '******'; update t_User set balance = balance - price where username = '******'";
                                    strSql      = string.Format(strSql, root, distributor);
                                }
                                else//管理员自己出单
                                {
                                    strSql += "update t_User set balance = balance - price where username = '******'";
                                    strSql  = string.Format(strSql, root);
                                }
                                cmm.CommandText = strSql;
                                cmm.ExecuteNonQuery();
                                #endregion

                                tran.Commit();//提交事务
                            }
                            catch
                            {
                                tran.Rollback();
                                Common.LogIt(strSql);
                                throw;
                            }
                        }
                    }
                    #endregion
                    return(response);
                }
                else
                {
                    response.Trace = userLogin.Trace;
                    return(response);
                }
            }
            catch (System.Exception ex)
            {
                StringBuilder sbLog = new StringBuilder();
                sbLog.AppendLine(Common.XmlSerialize <PurchaseRequestEntity>(request));
                sbLog.Append(ex.ToString());
                Common.LogIt(sbLog.ToString());

                response.Trace.ErrorMsg = "下单未成功,请稍后重试。";
                return(response);
            }
        }
        private void Button_modify_Click(object sender, RoutedEventArgs e)
        {
            if (DataView.SelectedItem == null)
            {
                return;
            }

            UserClass itemInfo = DataView.SelectedItem as UserClass;

            if (itemInfo == null || !(itemInfo is UserClass))
            {
                MessageBox.Show("获取选中项出现问题");
                return;
            }

            TcpClient     tcpClient     = null;
            NetworkStream networkStream = null;

            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connect(ip_address, port); //建立与服务器的连接
                networkStream = tcpClient.GetStream();
                if (networkStream.CanWrite)
                {
                    float fBalance = 0;
                    if (!float.TryParse(Text_balance_Copy.Text, out fBalance))
                    {
                        fBalance = -1;
                    }

                    var package = new TTS_Core.UserOperationPackage(user, ip_address + ":" + listen_port.ToString(), "server",
                                                                    TTS_Core.UserOperationPackage.Enum_USER_OP.K_MODIFY,
                                                                    itemInfo.userid, Text_accounttype_Copy.Text, Text_phone_Copy.Text, Text_username_Copy.Text, fBalance);

                    byte[] sendBytes = package.DataPackageToBytes(); //注册数据包转化为字节数组
                    networkStream.Write(sendBytes, 0, sendBytes.Length);

                    var newClient   = tcp_listener.AcceptTcpClient();
                    var bytes       = ReadFromTcpClient(newClient); //获取数据
                    var package_rec = new TTS_Core.DataSetPackage(bytes);

                    if (package_rec.forbid != 0 && package_rec.forbid != 1)
                    {
                        MessageBox.Show("出大问题");
                    }

                    if (package_rec.forbid == 1)
                    {
                        MessageBox.Show("修改失败,请检查完整性约束或者是服务器故障");
                    }
                    else
                    {
                        itemInfo.accounttype = Text_accounttype_Copy.Text;
                        itemInfo.phone       = Text_phone_Copy.Text;
                        itemInfo.username    = Text_username_Copy.Text;
                        itemInfo.balance     = Text_balance_Copy.Text;
                        DataView.Items.Insert(DataView.SelectedIndex, itemInfo);
                        DataView.Items.Remove(DataView.SelectedItem);
                    }
                }
            }
            catch
            {
                MessageBox.Show("无法连接到服务器!");
                return;
            }
            finally
            {
                if (networkStream != null)
                {
                    networkStream.Close();
                }
                tcpClient.Close();
            }
        }
Exemple #37
0
        public IActionResult Dashboard()
        {
            try
            {
                string username = null;

                if (HttpContext.Session.GetString("LoggedIn") != null)
                {
                    username = HttpContext.Session.GetString("Username");
                }
                else
                {
                    return(RedirectToAction("Index"));
                }



                DashboardFunctions loadUser = new DashboardFunctions(username);
                UserClass          thisUser = new UserClass(username);
                ViewBag.TodayAct = loadUser.GetDailyActivityList();
                var      TrackerList  = db.ProgressTracker.ToList();
                var      exerciseList = db.ExercisesListTable.ToList();
                var      existFood    = db.FoodData.OrderBy(z => z.Id).ToList();
                DateTime dt           = DateTime.Now;
                var      latestMonth  = TrackerList.Where(z => z.UserName.ToLower() == username.ToLower()).Max(x => x.Month); //latest week since update

                //get Current date in the format specified
                ViewBag.date = dt.ToString("MMMM dd, yyyy", CultureInfo.CreateSpecificCulture("en-US"));

                ViewBag.TimeExceeded = loadUser.TimeOverdue(dt, latestMonth);
                var      RecordedWeeks = TrackerList.Where(z => z.UserName.ToLower() == username.ToLower()).Count();
                string[] weeks         = new string[RecordedWeeks];

                for (int i = 0; i < RecordedWeeks; i++)
                {
                    weeks[i] = "Month " + (i + 1);
                }

                var       WeeklyBMI        = TrackerList.Where(z => z.UserName.ToLower() == username.ToLower()).OrderBy(k => k.Month).Select(x => x.Bmi).ToArray();
                var       exercisesArray   = exerciseList.OrderBy(f => f.ExerciseList).Select(s => s.ExerciseList.Substring(0, s.ExerciseList.Length - 1)).ToArray();
                var       exercisesIDArray = exerciseList.OrderBy(f => f.ExerciseList).Select(s => s.ExerciseId).ToArray();
                var       FoodsDBArray     = existFood.Select(z => z.Food).ToArray();
                var       FoodsIDArray     = existFood.Select(z => z.Id).ToArray();
                var       proteins         = existFood.Select(z => Math.Round((double)z.Protein, 2)).ToArray();
                var       Cal         = existFood.Select(z => Math.Round((double)z.Calorie, 2)).ToArray();
                var       Carb        = existFood.Select(z => Math.Round((double)z.Carbs, 2)).ToArray();
                var       Fat         = existFood.Select(z => Math.Round((double)z.Fat, 2)).ToArray();
                string [] macroString = new string[Cal.Length];
                for (int k = 0; k < Cal.Length; k++)
                {
                    macroString[k] = "   |Calorie:" + Cal[k] + "  |Protein:" + proteins[k] + "  |Carb:" + Carb[k] + "  |Fats:" + Fat[k] + "|";
                }
                ViewBag.MacroString = macroString;


                var WeeklyW2H = TrackerList.Where(z => z.UserName.ToLower() == username.ToLower()).OrderBy(k => k.Month).Select(x => x.Wc).ToArray();
                ViewBag.BMI    = Math.Round(TrackerList.Where(z => z.UserName.ToLower() == username.ToLower() && z.Month == latestMonth).Select(x => x.Bmi).FirstOrDefault(), 2);
                ViewBag.Weight = TrackerList.Where(z => z.UserName.ToLower() == username.ToLower() && z.Month == latestMonth).Select(x => x.MonthlyWeight).FirstOrDefault();
                var newValues = exercisesArray.Select(x => x.Substring(0, x.Length - 1)).ToArray();

                ViewBag.Consumption = thisUser.CalConsumption();

                ViewBag.ExerciseIDArr = exercisesIDArray;
                ViewBag.ExerciseArr   = exercisesArray;

                ViewBag.FoodsArr   = FoodsDBArray;
                ViewBag.FoodsIDArr = FoodsIDArray;

                ViewBag.WeeklyW2Hs = WeeklyW2H;
                ViewBag.WeeklyBMIs = WeeklyBMI;
                ViewBag.weeks      = weeks;

                ViewBag.username = username;

                var dietuser = db.DietUsers.Find(username);

                ViewBag.NewUser = dietuser.NewUser; //display model if its a new user

                ViewBag.Macros          = db.UserMacros.Where(z => z.Username.ToLower() == username.ToLower()).FirstOrDefault();
                ViewBag.ChoosenAllegies = loadUser.GetAllergiesList();


                ViewBag.ChoosenPreferences = loadUser.GetPreferencesList();

                return(View());
            }
            catch (SqlException)
            {
                string action     = this.ControllerContext.RouteData.Values["action"].ToString();
                string controller = this.ControllerContext.RouteData.Values["controller"].ToString();
                return(RedirectToAction("Error", new { controllerName = controller, actionName = action }));
            }
        }
Exemple #38
0
        public DataTable getUserTestDataTable(UserClass user)
        {
            TestService service = new TestService();

            return(service.getUserTestDataTable(user));
        }
Exemple #39
0
        public ActionResult CreateNewAccount(UserClass uc, string ConfirmPassword)
        {
            if (uc.Password == ConfirmPassword)
            {
                Membership.CreateUser(uc.UserName, uc.Password, uc.Email, uc.PasswordQuestion, uc.PasswordAnswer,
                                      true, out MembershipCreateStatus status);

                string createmessage = "";

                switch (status)
                {
                case MembershipCreateStatus.Success:     //basarılı
                    break;

                case MembershipCreateStatus.InvalidUserName:
                    createmessage = "Gerçersiz kullanıcı adı.";
                    break;

                case MembershipCreateStatus.InvalidPassword:
                    createmessage = "Gerçersiz şifre adı.";
                    break;



                case MembershipCreateStatus.InvalidQuestion:
                    createmessage = "Gerçersiz gizli soru ";
                    break;

                case MembershipCreateStatus.InvalidAnswer:
                    createmessage = "Gerçersiz gizli cevap";
                    break;

                case MembershipCreateStatus.InvalidEmail:
                    createmessage = "Gerçersiz email";
                    break;

                case MembershipCreateStatus.DuplicateUserName:
                    createmessage = "Kullanılmıs kullanıcı adı.";
                    break;

                case MembershipCreateStatus.DuplicateEmail:
                    createmessage = "Kullanılmış email adresi";
                    break;

                case MembershipCreateStatus.UserRejected:
                    createmessage = "Kullanıcı engellendi";
                    break;

                case MembershipCreateStatus.InvalidProviderUserKey:
                    createmessage = "Geçersiz kullanıcı anahtarı";
                    break;

                case MembershipCreateStatus.DuplicateProviderUserKey:
                    createmessage = "Tekrarlanmış kullanıcı anahtarı";
                    break;

                case MembershipCreateStatus.ProviderError:
                    createmessage = "Sağlayıcı hatası.";
                    break;

                default:
                    break;
                }


                ViewBag.createMessage = createmessage;

                if (createmessage == "")
                {
                    ViewBag.Message = "Kullanıcı kaydedildi.";
                    return(View()); //hata yoksa kullanıcı giriş sayfasına gelicek.
                }
                else
                {
                    return(View());
                    //eger hata varsa oldugu sayfada kalsın
                }
            }

            else
            {
                ViewBag.createMessage = "Şifreler uyuşmuyor.";
                return(View());
            }
        }
Exemple #40
0
        public void updateTest(UserClass user, TestClass test)
        {
            TestService service = new TestService();

            service.updateTest(user, test);
        }
Exemple #41
0
        public string login(UserClass user)
        {
            UserManager manager = new UserManager();

            return(manager.login(user));
        }
    /// <summary>
    /// The serialize.
    /// </summary>
    /// <param name="obj">
    /// The user
    /// </param>
    /// <returns>
    /// The byte array of the user
    /// </returns>
    internal static byte[] Serialize(UserClass obj)
    {
        if (obj == null)
        {
            return null;
        }

        var bf = new BinaryFormatter() { AssemblyFormat = FormatterAssemblyStyle.Simple };
        var ms = new MemoryStream();
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
        public void DeleteById(int entitiyID)
        {
            UserClass userClass = _userDAL.Get(a => a.ID == entitiyID);

            Delete(userClass);
        }
    /// <summary>
    /// check user name/password combination 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cmdLogin_Click(object sender, System.EventArgs e)
    {
        
        UserClass _userlogin = new UserClass();
        HttpCookie _acookie = new HttpCookie("user");

        try
        {
            string _username = txtUserName.Text.Replace("'", "''");
            string _pass = wwi_security.EncryptString(txtPassword.Text.Replace("'", "''"),"publiship");

            _userlogin = _userlogin.Login(_username, _pass);

            if (_userlogin != null && _userlogin.ID != Guid.Empty)
            {
               
                Session["user"] = _userlogin;
                
                if (Request.Browser.Cookies)
                {
                    if (chbSavePassword.Checked)
                    {
                        _acookie["userlogin"] = txtUserName.Text;
                        _acookie["userpwd"] = _pass; //txtPassword.Text;
                        //expires  after 1 year
                        _acookie.Expires = DateTime.Now.AddYears(1);
                    }
                    else
                    {
                        //expires  midnight
                        //DateTime _dt = Convert.ToDateTime(DateTime.Now.ToShortDateString() + " 00:00:00");
                        
                        //expires in 1 hour
                        DateTime _dt = DateTime.Now.AddHours(1);  //DateTime.Now + new TimeSpan(1, 0, 0);
                        _acookie.Expires = _dt;
                    }
                    Response.Cookies.Add(_acookie);
                }
            }
            else
            {
                if (_userlogin == null)
                {
                    //this.lblMsg.Text = "<div class='fberrorbox'>Null login</div>";
                }
                else if (_userlogin.ID == Guid.Empty)
                {
                    //this.lblMsg.Text = "<div class='fberrorbox'>No guid</div>";
                }
                else
                {
                    //this.lblMsg.Text = "<div class='fberrorbox'>Invalid Login</div>";
                }
                _userlogin = null;
                Session.Remove("user");
            }
        }
        catch
        {
            _userlogin = null;
            Session.Remove("user");
            //this.lblMsg.Text = "<div class='fberrorbox'>Invalid Login</div>";
        }
        if (_userlogin != null)
        {
            Redirect(true);
           

        }
        else
        {

            this.lblmsg.Visible = true;
        }
     }
        public void VerifyApprover()
        {
            GroupsClass objTOR = new GroupsClass();
            if (Request.QueryString[Config.ListURL] != null)
                sharepointUrl = new Uri(Request.QueryString[Config.ListURL]);

            string siteApproverGroupname = Config.TimeOffApprovers;//default from web.config

            //Get from App Config (custom)
            ConfigListValues objConfigAppList = new ConfigListValues();
            objConfigAppList.GetConfigValues(null);
            if (objConfigAppList.items != null)
            {
                if (objConfigAppList.items[Config.TimeOffApprovers] != null)
                    siteApproverGroupname = objConfigAppList.items[Config.TimeOffApprovers].ToString();
            }

            UserClass objUser = new UserClass();
            string strCurrentUserTitle = objUser.GetCurrentUserByApp().LoginName;
            if (!objTOR.IsCurrentUserExistInGroup( siteApproverGroupname, strCurrentUserTitle))
            {
                lblerrmsg.Text = " You do not have Access Permission";
            }
            else
            {
                string deptCalName = Config.DepartmentCalendar;//default from web.config
                //Get from App Config (custom)
                ConfigListValues objConfAppList = new ConfigListValues();
                objConfAppList.GetConfigValues(null);
                if (objConfAppList.items != null)
                {
                    if (objConfAppList.items[deptCalName] != null)
                    {
                        deptCalName = objConfAppList.items[deptCalName].ToString();
                    }
                }
                Response.Redirect(Request.QueryString["SPHostUrl"] + "/_layouts/15/start.aspx#/Lists/" + deptCalName, false);
            }
        }
Exemple #46
0
        public bool deleteTest(UserClass user, TestClass test)
        {
            TestService service = new TestService();

            return(service.deleteTest(user, test));
        }
        /// <summary>
        /// The button reg_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void BtnRegClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.TxtUsername.Text))
            {
                MessageBox.Show("Username cannot be empty.");
            }
            else if (string.IsNullOrEmpty(this.TxtPassword.Password))
            {
                MessageBox.Show("Password cannot be empty.");
            }
            else
            {
                user = new UserClass(this.TxtUsername.Text, this.TxtPassword.Password, false);
                var regTask = new Task<bool>(Reg);
                regTask.Start();
                var progress = 0;
                while (running)
                {
                    progressBar1.Value = progress;
                    ++progress;
                    if (progress > 10)
                    {
                        progress = 0;
                    }
                }

                var result = regTask.Result;

                switch (result)
                {
                    case false:
                        MessageBox.Show("Unfortunately the registration was not successful, please try again.");
                        break;
                    case true:
                        MessageBox.Show("Registration was successful! You will now be returned to the main screen where you can log in.");
                        this.DialogResult = true;
                        break;
                }
            }
        }
Exemple #48
0
        public int addTest(UserClass user, ref TestClass test)
        {
            TestService service = new TestService();

            return(service.addTest(user, ref test));
        }
        private void Button_delete_Click(object sender, RoutedEventArgs e)
        {
            if (DataView.SelectedItem == null)
            {
                return;
            }

            string    selected_userid;
            UserClass itemInfo = DataView.SelectedItem as UserClass;

            if (itemInfo != null && itemInfo is UserClass)
            {
                selected_userid = itemInfo.userid;
            }
            else
            {
                MessageBox.Show("获取选中项出现问题");
                return;
            }
            TcpClient     tcpClient     = null;
            NetworkStream networkStream = null;

            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connect(ip_address, port); //建立与服务器的连接
                networkStream = tcpClient.GetStream();
                if (networkStream.CanWrite)
                {
                    var package = new TTS_Core.UserOperationPackage(user, ip_address + ":" + listen_port.ToString(), "server",
                                                                    TTS_Core.UserOperationPackage.Enum_USER_OP.K_DELETE,
                                                                    selected_userid, "",
                                                                    "", "", 0);

                    byte[] sendBytes = package.DataPackageToBytes();
                    networkStream.Write(sendBytes, 0, sendBytes.Length);

                    var newClient   = tcp_listener.AcceptTcpClient();
                    var bytes       = ReadFromTcpClient(newClient); //获取数据
                    var package_rec = new TTS_Core.DataSetPackage(bytes);

                    if (package_rec.forbid != 0 && package_rec.forbid != 1)
                    {
                        MessageBox.Show("出大问题");
                    }

                    if (package_rec.forbid == 1)
                    {
                        MessageBox.Show("删除失败,请检查完整性约束或者是服务器故障");
                    }
                    else
                    {
                        DataView.Items.Remove(DataView.SelectedItem);
                    }
                }
            }
            catch
            {
                MessageBox.Show("无法连接到服务器!");
                return;
            }
            finally
            {
                if (networkStream != null)
                {
                    networkStream.Close();
                }
                tcpClient.Close();
            }
        }
Exemple #50
0
        public int setUserMark(UserClass user, int mValue)
        {
            TestService service = new TestService();

            return(service.setUserMark(user, mValue));
        }
Exemple #51
0
    protected void btnSend_Click(object sender, EventArgs e)
    {
        ltrMessage.Text      = "";
        ltrMessageGreen.Text = "";

        FeedbackClass    fc  = new FeedbackClass();
        LogFeedbackClass lfc = new LogFeedbackClass();
        UserClass        uc  = new UserClass();

        int    feedbackByUserId, feedbackToUserId;
        String feedbackSubject, feedbackDescription;
        String feedbackCheckUserType = "";
        String feedbackToUsername;

        String feedbackDate;

        /*Current date and time calculated*/
        DateTime currentDateNTime = DateTime.Now;

        feedbackDate = currentDateNTime.ToString("dd/MM/yyyy hh:mm:ss tt");

        feedbackSubject     = txtboxSubject.Text;
        feedbackDescription = txtboxMessage.Text;
        feedbackToUsername  = dropdownlistUsername.SelectedValue;
        dropdownlistUsername.Items.Insert(0, feedbackToUsername);

        /*Getting feedbackBy userId from Session*/
        String userIdString = Session["userId"].ToString();
        int    userId       = Convert.ToInt32(userIdString);

        feedbackByUserId = userId;

        try
        {
            /*Getting feedbackToUserId from feedbackToUsername*/
            DataTable dt = uc.SelectAllUsersFromUsername(feedbackToUsername);
            if (dt.Rows.Count > 0)
            {
                feedbackCheckUserType = dt.Rows[0]["userType"].ToString();

                if (feedbackCheckUserType == "Patient")
                {
                    Session["feedbackToUserId"] = dt.Rows[0]["userId"].ToString();
                    String feedbackToUserIdString = dt.Rows[0]["userId"].ToString();
                    feedbackToUserId = Convert.ToInt32(feedbackToUserIdString);

                    /*Inserting and putting the values in Log*/
                    fc.InsertFeedback(feedbackByUserId, feedbackToUserId, feedbackSubject, feedbackDescription);
                    lfc.insertOn_Log_FeedbackWholeField_WithInsertOperation(feedbackDate);

                    /*Refreshing*/
                    Response.Redirect("Inform_EntryUserMaster.aspx");
                    dropdownlistUsername.Focus();
                }
                else
                {
                    ltrMessage.Text = "Invalid Username!";
                }
            }
        }
        catch (Exception ex)
        {
            ltrMessage.Text = ex.Message;
        }
    }
Exemple #52
0
 public ActionResult ForgotMyPassword(UserClass cs)
 {
     return(View());
 }
    protected void append_to_user_log(UserClass thisuser)
    {
        try
        {
            UserLog _newlog = new UserLog();

            if (thisuser.CompanyId == -1)
            { //employee
                _newlog.ContactID = 0;
                _newlog.EmployeeID = thisuser.UserId;
            }
            else
            {
                _newlog.ContactID = thisuser.UserId;
                _newlog.EmployeeID = 0;
            }

            _newlog.LogDate = DateTime.Now;  
            _newlog.Save(); 

        }
        catch(Exception ex)
        {
            Response.Write(ex.Message.ToString()); 
        }
    }
Exemple #54
0
        public ActionResult CreateNewAccount(UserClass uc, string ConfirmPassword)
        {
            string createMessage = "";

            if (uc.Password != ConfirmPassword)
            {
                createMessage         = "Şifreler uyuşmuyor";
                ViewBag.createMessage = createMessage;
                return(View());
            }

            Membership.CreateUser(uc.UserName, uc.Password, uc.Email, uc.PasswordQuestion, uc.PasswordAnswer, true, out MembershipCreateStatus status);

            switch (status)
            {
            case MembershipCreateStatus.Success:
                createMessage = "Kayıt başarılı";
                break;

            case MembershipCreateStatus.InvalidUserName:
                createMessage = "Geçersiz kullanıcı adı";
                break;

            case MembershipCreateStatus.InvalidPassword:
                createMessage = "Geçersiz şifre";
                break;

            case MembershipCreateStatus.InvalidQuestion:
                createMessage = "Geçersiz gizli soru";
                break;

            case MembershipCreateStatus.InvalidAnswer:
                createMessage = "Geçersiz gizli cevap";
                break;

            case MembershipCreateStatus.InvalidEmail:
                createMessage = "Geçersiz email";
                break;

            case MembershipCreateStatus.DuplicateUserName:
                createMessage = "Kullanılmış kullanıcı adı";
                break;

            case MembershipCreateStatus.DuplicateEmail:
                createMessage = "Kullanılmış email adresi";
                break;

            case MembershipCreateStatus.UserRejected:
                createMessage = "Kullanıcı engellendi";
                break;

            case MembershipCreateStatus.InvalidProviderUserKey:
                createMessage = "Geçersiz kullanıcı anahtarı";
                break;

            case MembershipCreateStatus.DuplicateProviderUserKey:
                createMessage = "Tekrarlanmış kullanıcı anahtarı";
                break;

            case MembershipCreateStatus.ProviderError:
                createMessage = "Sağlayıcı hatası";
                break;

            default:
                createMessage = "Bilinmeyen bir hata oluştu";
                break;
            }

            ViewBag.createMessage = createMessage;

            if (status == MembershipCreateStatus.Success)
            {
                return(RedirectToAction("MemberLogin"));
            }

            return(View());
        }
 /// <summary>
 /// Write user to database
 /// </summary>
 /// <param name="user">
 /// The user to write
 /// </param>
 private void WriteUser(UserClass user)
 {
 }
    /// <summary>
    /// this code is used with LinqServerModePricer_Selecting so we can run in server mode
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinqServerModePricer_Selecting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs e)
    {
        //get user id to limit result set
        if (Session["user"] != null)
        {
            string _query = "";
            string _mode  = this.dxhfMethod.Contains("mode") ? this.dxhfMethod["mode"].ToString() : "0"; //only 0 or 1 (quick search)

            UserClass           _thisuser = (UserClass)Session["user"];
            Int32               _id       = _thisuser.UserId;
            ParameterCollection _params   = new ParameterCollection();

            //check quick search parameters
            if (_mode == "1")
            {
                _query = get_filter();
            }

            //020911 only show records where client_visible = true
            Parameter _p0 = new Parameter();
            _p0.Name         = "client_visible";
            _p0.DefaultValue = true.ToString();
            _params.Add(_p0);

            //check user id
            Parameter _p1 = new Parameter();
            _p1.Name         = "request_user_id";
            _p1.DefaultValue = _thisuser.UserId.ToString();
            _params.Add(_p1);

            //and company id
            Parameter _p2 = new Parameter();
            _p2.Name         = "request_company_id";
            _p2.DefaultValue = _thisuser.CompanyId.ToString();
            _params.Add(_p2);


            //now rebuild query with additional parameters
            string _f = "";
            if (_params.Count > 0)
            {
                foreach (Parameter p in _params)
                {
                    string _a = _f != "" ? " AND " : "";
                    _f += _a + "(" + p.Name.ToString() + "==" + p.DefaultValue.ToString() + ")";
                }

                if (_query != "")
                {
                    _query = _f + " AND " + _query;
                }
                else
                {
                    _query = _f;
                }
            }

            //dynamic queries using system.Linq.dynamic + Dynamic.cs library
            e.KeyExpression = "quote_Id"; //a key expression is required

            if (!string.IsNullOrEmpty(_query))
            {
                var _nquery = new linq.linq_pricer_view1DataContext().view_price_clients.Where(_query); //c => c.CompanyID == 7
                e.QueryableSource = _nquery;
                //Int32 _count = _nquery.Count();
            }
            else //default to display nothing in grid
            {
                var _nquery = new linq.linq_pricer_view1DataContext().view_price_clients.Where(c => c.quote_Id == -1);
                //_count = _nquery.Count();

                e.QueryableSource = _nquery;
            }
        }
    }//end linq server mode
        private async void btn_concern_Click(object sender, RoutedEventArgs e)
        {
            UserClass getLogin = new UserClass();
            wc = new WebClientClass();
            if (getLogin.IsLogin())
            {
                try
                {
                    if (btn_concern.Label == "订阅")
                    {
                        //http://www.bilibili.com/api_proxy?app=bangumi&action=/concern_season&season_id=779
                        string results = await wc.GetResults(new Uri("http://www.bilibili.com/api_proxy?app=bangumi&action=/concern_season&season_id=" + banID));
                        JObject json = JObject.Parse(results);
                        if ((int)json["code"] == 0)
                        {
                            font_icon.Glyph = "\uE00B";
                            btn_concern.Label = "取消订阅";
                            messShow.Show("订阅成功!", 3000);
                            //MessageDialog md = new MessageDialog("订阅成功!");
                            //  await md.ShowAsync();

                        }
                        else
                        {
                            messShow.Show("订阅失败!", 3000);
                        }
                    }
                    else
                    {
                        //http://www.bilibili.com/api_proxy?app=bangumi&action=/concern_season&season_id=779

                        string results = await wc.GetResults(new Uri("http://www.bilibili.com/api_proxy?app=bangumi&action=/unconcern_season&season_id=" + banID));
                        JObject json = JObject.Parse(results);
                        if ((int)json["code"] == 0)
                        {
                            font_icon.Glyph = "\uE006";
                            btn_concern.Label = "订阅";
                            messShow.Show("取消订阅成功!", 3000);
                            
                        }
                        else
                        {
                            messShow.Show("取消订阅失败!", 3000);
                        }
                    }
                }
                catch (Exception)
                {
                    MessageDialog md = new MessageDialog("订阅操作失败!");

                    await md.ShowAsync();
                }
            }
            else
            {
                MessageDialog md = new MessageDialog("先登录好伐", "(´・ω・`) ");
                await md.ShowAsync();
            }
        }
Exemple #58
0
    protected void SaveProBut_Click(object sender, EventArgs e)
    {
        RegEx.Validate();
        if (RegEx.IsValid == true & Email.Text != "")
        {
            Profile.EMail          = Email.Text;
            EmailValidBox.CssClass = "none";
        }
        else
        {
            EmailValidBox.CssClass = "validboxvizrt";
        }
        if (FirstName.Text == "")
        {
            FirstNameValid.CssClass = "validboxvizrt";
            FirstName.Text          = Profile.FirstName;
        }
        if (City.Text == "")
        {
            CityValidBox.CssClass = "validboxvizrt";
            City.Text             = Profile.Location.City;
        }
        if (Zip.Text == "" || Zip.Text.Length < 5)
        {
            ZipValidBox.CssClass = "validboxvizrt";
            Zip.Text             = Profile.Location.Zip;
        }
        int       zip;
        UserClass uc = new UserClass(Profile.UserName);

        if (Zip.Text != null & Zip.Text != "")
        {
            zip = Convert.ToInt32(Zip.Text);
        }
        else
        {
            zip = 0;
        }
        string phoneNum;

        phoneNum = AreaCode.Text + Num1.Text + Num2.Text;
        if (phoneNum.Length < 10)
        {
            phoneNum = "0";
        }

        string virtualPath    = "~/Images/";
        string physicalFolder = Server.MapPath(virtualPath);
        string fileName       = Guid.NewGuid().ToString();
        string extension      = System.IO.Path.GetExtension(PersImgUpload.FileName);
        string imgUrl         = System.IO.Path.Combine(virtualPath, fileName + extension);

        if (extension == ".jpg" || extension == ".jpeg")
        {
            PersImgUpload.SaveAs(System.IO.Path.Combine(physicalFolder, fileName + extension));
        }
        else
        {
            imgUrl = "";
        }

        uc.UpdateUserInfo(FirstName.Text, LastName.Text, Email.Text, City.Text, State.Text, zip, phoneNum, imgUrl);

        Profile.FirstName      = FirstName.Text;
        Profile.LastName       = LastName.Text;
        Profile.Location.City  = City.Text;
        Profile.Location.State = State.Text;
        Profile.Location.Zip   = Zip.Text;

        FirstName.Text = Profile.FirstName;
        LastName.Text  = Profile.LastName;
        Email.Text     = Profile.EMail;
        City.Text      = Profile.Location.City;
        State.Text     = Profile.Location.State;
        Zip.Text       = Profile.Location.Zip;

        if (uc.UserIsValid())
        {
            if (Profile.IsValidated != true)
            {
                Profile.IsValidated = true;
                Response.Redirect("~/MyProfile/MyProfile.aspx?isvalid=true");
            }
        }
        else
        {
            if (Profile.IsValidated == true)
            {
                Profile.IsValidated = false;
            }
        }
        UserControl ucx      = (UserControl)LoadControl("~/Controls/UserNoticeModal.ascx");
        Label       txtLabel = (Label)ucx.FindControl("TextLabel");

        txtLabel.Text = "Your updates have been saved!";
        Form.Controls.Add(ucx);
    }
Exemple #59
0
		/// <summary>
		/// Преобразовывает userclass число в строку с подсветкой или без.
		/// </summary>
		private static string FormatUserClass(UserClass userClass, bool isHtml)
		{
			return JanusFormatMessage.FormatUserClass(userClass, isHtml);
		}
Exemple #60
0
    public UserClass Login(string txtUser, string txtPassword)
    {
        UserClass UserLogin = new UserClass();

        string sLoginFrom = ConfigurationManager.AppSettings["LoginFrom"];

        if (sLoginFrom == "DB")
        { // User Name and Password from DB
            string sTable     = ConfigurationManager.AppSettings["UserListTable"];
            string sLogin     = ConfigurationManager.AppSettings["FieldUserLogin"];
            string sLoginType = ConfigurationManager.AppSettings["FieldUserLoginType"];
            string sPwd       = ConfigurationManager.AppSettings["FieldUserPwd"];
            string sPwdType   = ConfigurationManager.AppSettings["FieldUserPwdType"];

            if (sTable == "" || sLogin == "" || sPwd == "")
            {
                return(null);
            }
            string sUserID  = func.GetOptions("FieldUserOwnerID");
            string sGroupID = func.GetOptions("FieldUserGroupID");
            string sSQL     = "select [" + sLogin + "],[" + sPwd + "]";
            if (ConfigurationManager.AppSettings["TablesFile"] != string.Empty && sUserID != string.Empty)
            {
                sSQL += ", [" + sUserID + "]";
            }
            if (ConfigurationManager.AppSettings["TablesFile"] != string.Empty && sGroupID != string.Empty)
            {
                sSQL += ", [" + sGroupID + "]";
            }
            sSQL += " from " + sTable + " where [" + sLogin + "] = @Login and [" + sPwd + "] = @Password ";

            QueryCommand query = new QueryCommand(sSQL);

            try
            {
                query.AddParameter("Login", txtUser);
                query.AddParameter("Password", txtPassword);

                DbDataReader dbDr = (DbDataReader)DataService.GetReader(query);

                if (dbDr.HasRows && dbDr.Read())
                {
                    if (dbDr[sLogin].ToString() == txtUser && dbDr[sPwd].ToString() == txtPassword)
                    {
                        UserLogin.ID = Guid.NewGuid();
                        if (ConfigurationManager.AppSettings["TablesFile"] != "" && sUserID != string.Empty)
                        {
                            UserLogin.UserID = Convert.ToString(dbDr[sUserID]);
                        }
                        if (ConfigurationManager.AppSettings["TablesFile"] != "" && sGroupID != string.Empty)
                        {
                            UserLogin.GroupID = Convert.ToString(dbDr[sGroupID]);
                        }
                        UserLogin.UserID = Convert.ToString(dbDr[sLogin]);
                    }
                }
                dbDr.Dispose();
            }
            finally
            {
            }
        }
        else
        { // hardcoded
            if (txtUser == ConfigurationManager.AppSettings["UserLogin"] && txtPassword == ConfigurationManager.AppSettings["UserPassword"])
            {
                UserLogin.ID = Guid.NewGuid();
            }
        }


        if (UserLogin.ID == Guid.Empty)
        {
            return(null);
        }
        else
        {
            UserLogin.UserName = txtUser;
            return(UserLogin);
        }
    }