Example #1
0
        public void OnChannelModeChange( UserInfo who, string channel, ChannelModeInfo[] modes)
        {
            //+h bob +b -i *!*@* +e *!*@*.fi

            Assertion.AssertEquals("OnChannelModeChange: userInfo.Nick","Scurvy", who.Nick );
            Assertion.AssertEquals("OnChannelModeChange: userInfo.User","~Scurvy", who.User );
            Assertion.AssertEquals("OnChannelModeChange: userInfo.Host","pcp825822pcs.nrockv01.md.comcast.net", who.Hostname );

            Assertion.AssertEquals("OnChannelModeChange: channel", "#sharktest", channel );
            Assertion.AssertEquals("OnChannelModeChange: action", ModeAction.Add, modes[0].Action );
            Assertion.AssertEquals("OnChannelModeChange: size", 4, modes.Length );

            Assertion.AssertEquals("OnChannelModeChange: halfop", ChannelMode.HalfChannelOperator, modes[0].Mode );
            Assertion.AssertEquals("OnChannelModeChange: halfop", "bob", modes[0].Parameter );

            Assertion.AssertEquals("OnChannelModeChange: ban", ChannelMode.Ban, modes[1].Mode );
            Assertion.AssertEquals("OnChannelModeChange: param", "*!*@*", modes[1].Parameter );

            Assertion.AssertEquals("OnChannelModeChange: invite action", ModeAction.Remove, modes[2].Action );
            Assertion.AssertEquals("OnChannelModeChange: invite mode", ChannelMode.InviteOnly, modes[2].Mode );

            Assertion.AssertEquals("OnChannelModeChange: exception action", ModeAction.Add, modes[3].Action );
            Assertion.AssertEquals("OnChannelModeChange: exception mode", ChannelMode.Exception, modes[3].Mode );
            Assertion.AssertEquals("OnChannelModeChange: exception param", "*!*@*.fi", modes[3].Parameter );
            Console.WriteLine("OnChannelModeChange");
        }
        public void matches_credentials_negative()
        {
            var user1 = new UserInfo
            {
                UserName = "******",
                Password = "******",
                Roles = new string[] { "A", "B" }
            };

            var user2 = new UserInfo
            {
                UserName = "******",
                Roles = new string[] { "C", "D" }
            };

            theRepository.Write(new UserInfo[] { user1, user2 });

            theRepository.MatchesCredentials(new LoginRequest
            {
                UserName = "******",
                Password = "******"
            }).ShouldBeFalse();

            theRepository.MatchesCredentials(new LoginRequest
            {
                UserName = "******",
                Password = "******"
            }).ShouldBeFalse();
        }
Example #3
0
		private async Task<FetchReturnValue> Fetch() {
			UserInfo userInfo = new UserInfo();
			switch ( comboBoxService.Text ) {
				case "Twitch (Recordings)": userInfo.Service = ServiceVideoCategoryType.TwitchRecordings; break;
				case "Twitch (Highlights)": userInfo.Service = ServiceVideoCategoryType.TwitchHighlights; break;
				case "Hitbox": userInfo.Service = ServiceVideoCategoryType.HitboxRecordings; break;
				default: return new FetchReturnValue { Success = false, HasMore = false };
			}
			userInfo.Username = textboxUsername.Text.Trim();

			var rv = await Fetch( TwitchAPI, userInfo, Offset );

			if ( rv.Success && rv.Videos.Count > 0 ) {
				Offset += rv.Videos.Count;
				textboxUsername.Enabled = false;
				comboBoxService.Enabled = false;
				comboBoxKnownUsers.Enabled = false;
				if ( rv.HasMore && rv.TotalVideos != -1 ) {
					buttonFetch.Text = "Fetch More (" + ( rv.TotalVideos - Offset ) + " left)";
				} else {
					buttonFetch.Text = "Fetch More";
				}
				buttonFetch.Enabled = rv.HasMore;
				buttonClear.Enabled = true;

				objectListViewVideos.BeginUpdate();
				foreach ( var v in rv.Videos ) {
					objectListViewVideos.AddObject( v );
				}
				objectListViewVideos.EndUpdate();
			}

			return rv;
		}
 /// <summary>
 /// Updates all gestures.
 /// </summary>
 /// <param name="data">The skeleton data.</param>
 public virtual void UpdateAllGestures(Skeleton data, UserInfo userInfo = null)
 {
     foreach (Gesture gesture in this.gestures)
     {
         gesture.UpdateGesture(data, userInfo);
     }
 }
Example #5
0
        protected override void PrivateHandle(UserInfo info, List<string> args)
        {
            if (args.Count == 0)
            {
                info.AwayMessage = null;
                info.Modes.RemoveMode<ModeAway>();
                IrcDaemon.Replies.SendUnAway(info);
            }
            else
            {
                info.AwayMessage = args [0];
                info.Modes.Add (new ModeAway());
                IrcDaemon.Replies.SendNowAway(info);
            }

            foreach (var channel in info.Channels)
            {
                foreach (var user in  channel.Users)
                {
                    if (user.Capabilities.Contains("away-notify"))
                    {

                        Send (new AwayArgument (info, user, (args.Count == 0) ? null : args[0]));
                    }
                }
            }
        }
 private void GetOrganizationAndRoleName()
 {
     UserInfo objUser = new UserInfo(LoginMemberId);
     lblRoleName.Text = objUser.SubRoleName;
     //lblCompanyName.Text = OrganizationInfo.GetOrgLegalNameByOrgId(UserOrganizationId);
     lblCompanyName.Text = objUser.FirstName + " " + objUser.LastName;
 }
Example #7
0
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="_userinfo"></param>
        /// <returns></returns>
        public int InsertUser(UserInfo _userinfo)
        {
            string cmdText = @" insert into [loachs_users](
                                [Type],[UserName],[Name],[Password],[Email],[SiteUrl],[AvatarUrl],[Description],[displayorder],[Status],[PostCount],[CommentCount],[CreateDate])
                                values (
                                @Type,@UserName,@Name,@Password,@Email,@SiteUrl,@AvatarUrl,@Description,@Displayorder,@Status, @PostCount,@CommentCount,@CreateDate )";
            SqliteParameter[] prams = {
                                        SqliteDbHelper.MakeInParam("@Type", DbType.Int32,4, _userinfo.Type),
                                        SqliteDbHelper.MakeInParam("@UserName", DbType.String,50, _userinfo.UserName),
                                        SqliteDbHelper.MakeInParam("@Name", DbType.String,50, _userinfo.Name),
                                        SqliteDbHelper.MakeInParam("@Password", DbType.String,50, _userinfo.Password),
                                        SqliteDbHelper.MakeInParam("@Email", DbType.String,50, _userinfo.Email),
                                        SqliteDbHelper.MakeInParam("@SiteUrl", DbType.String,255, _userinfo.SiteUrl),
                                        SqliteDbHelper.MakeInParam("@AvatarUrl", DbType.String,255, _userinfo.AvatarUrl),
                                        SqliteDbHelper.MakeInParam("@Displayorder", DbType.String,255, _userinfo.Description),
                                        SqliteDbHelper.MakeInParam("@Status", DbType.Int32,4, _userinfo.Displayorder),
                                        SqliteDbHelper.MakeInParam("@Status", DbType.Int32,4, _userinfo.Status),
                                        SqliteDbHelper.MakeInParam("@PostCount", DbType.Int32,4, _userinfo.PostCount),
                                        SqliteDbHelper.MakeInParam("@CommentCount", DbType.Int32,4, _userinfo.CommentCount),
                                        SqliteDbHelper.MakeInParam("@CreateDate", DbType.Date,8, _userinfo.CreateDate),

                                    };
            int r = SqliteDbHelper.ExecuteNonQuery(CommandType.Text, cmdText, prams);
            if (r > 0)
            {
                return Convert.ToInt32(SqliteDbHelper.ExecuteScalar("select   [UserId] from [loachs_users]  order by [UserId] desc limit 1"));
            }
            return 0;
        }
 public User ChangeUserInfo(UserInfo userInfo)
 {
     // ...
     // end::UserService[]
     return new User();
     // tag::UserService[]
 }
    protected void Page_Load(object sender, EventArgs e)
    {

        
        if (!IsPostBack)
        {

            DataTable dt = OrganizationInfo.GetLogoPath(UserOrganizationId);
            if (dt != null && dt.Rows.Count > 0)
            {
                string str = ConfigurationManager.AppSettings["LogoUploadLocation"] + dt.Rows[0]["vchLogoPath"].ToString();
                if (!string.IsNullOrEmpty(dt.Rows[0]["vchLogoPath"].ToString()))
                {
                    str = str.Replace("//", "/");
                    logoimg.Src = str;
                }
            }
            UserInfo obj = UserInfo.GetCurrentUserInfo();
            UserInfo objUser = new UserInfo(obj.UserId);
            if (objUser.UserProfileImage != null)
            {
                profileimage.Src = "data:image/(gif|png|jpeg|jpg);base64," + Convert.ToBase64String(objUser.UserProfileImage);
            }
        }
        GetMenuPermission();
        GetOrganizationAndRoleName();
        //lblProduct.Text = CatName; 
    }
Example #10
0
        public void ProcessRequest(HttpContext context)
        {
            using (UserOperateClient insUserBLL = new UserOperateClient())
            {
                //context.Response.ContentType = "text/plain";
                //context.Response.Write("Hello World");
                UserInfo user = new UserInfo();

                user.LoginName = System.Web.HttpUtility.UrlDecode(context.Request["username"]);
                user.Password = CommonFunction.StringToMD5(System.Web.HttpUtility.UrlDecode(context.Request["password"]), 16);
                user.Mail = System.Web.HttpUtility.UrlDecode(context.Request["email"]);
                user.QuestionID = Convert.ToInt32(System.Web.HttpUtility.UrlDecode(context.Request["question"]));
                user.QuestionAnswer = System.Web.HttpUtility.UrlDecode(context.Request["answer"]);
                try
                {
                    if (insUserBLL.UserRegist(user) == "注册成功")
                    {
                        context.Session.Add("loginname", user.LoginName);
                        context.Application.Add("loginName", user.LoginName);
                        context.Response.Write("success");
                    }
                    else
                    {
                        context.Response.Write("fail");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Example #11
0
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="userinfo"></param>
        /// <returns></returns>
        public int InsertUser(UserInfo userinfo)
        {
            string cmdText =string.Format(@" insert into [{0}users](
                                [UserType],[UserName],[NickName],[Password],[Email],[SiteUrl],[AvatarUrl],[Description],[sortnum],[Status],[PostCount],[CommentCount],[CreateTime])
                                values (
                                @UserType,@UserName,@NickName,@Password,@Email,@SiteUrl,@AvatarUrl,@Description,@SortNum,@Status, @PostCount,@CommentCount,@CreateTime )",ConfigHelper.Tableprefix);
            SqliteParameter[] prams = {
                                        SqliteHelper.MakeInParam("@UserType", DbType.Int32,4, userinfo.UserType),
                                        SqliteHelper.MakeInParam("@UserName", DbType.String,50, userinfo.UserName),
                                        SqliteHelper.MakeInParam("@NickName", DbType.String,50, userinfo.NickName),
                                        SqliteHelper.MakeInParam("@Password", DbType.String,50, userinfo.Password),
                                        SqliteHelper.MakeInParam("@Email", DbType.String,50, userinfo.Email),
                                        SqliteHelper.MakeInParam("@SiteUrl", DbType.String,255, userinfo.SiteUrl),
                                        SqliteHelper.MakeInParam("@AvatarUrl", DbType.String,255, userinfo.AvatarUrl),
                                        SqliteHelper.MakeInParam("@Description", DbType.String,255, userinfo.Description),
                                        SqliteHelper.MakeInParam("@SortNum", DbType.Int32,4, userinfo.SortNum),
                                        SqliteHelper.MakeInParam("@Status", DbType.Int32,4, userinfo.Status),
                                        SqliteHelper.MakeInParam("@PostCount", DbType.Int32,4, userinfo.PostCount),
                                        SqliteHelper.MakeInParam("@CommentCount", DbType.Int32,4, userinfo.CommentCount),
                                        SqliteHelper.MakeInParam("@CreateTime", DbType.Date,8, userinfo.CreateTime),

                                    };
            int r = SqliteHelper.ExecuteNonQuery(CommandType.Text, cmdText, prams);
            if (r > 0)
            {
                return Convert.ToInt32(SqliteHelper.ExecuteScalar(string.Format("select [UserId] from [{0}users]  order by [UserId] desc limit 1",ConfigHelper.Tableprefix)));
            }
            return 0;
        }
    public string ValidateUser(string UserName, string Passsword)
    {
        string _UserType = string.Empty;
        try
        {
            GenralUserInfo objGenralUserInfo = new GenralUserInfo();
            UserInfo objUserInfo = new UserInfo();

            objUserInfo.UserName = UserName;
            objUserInfo.UserPassword = Passsword;
            objGenralUserInfo.RecentUsers = objUserInfo;
            _presenter.OnLogin(objGenralUserInfo);

            if (objGenralUserInfo.CustomError == null)
            {
                //ShowMessage(objGenralUserInfo.CustomError.ErrorMessage.ToString());
                _UserType = objGenralUserInfo.RecentUsers.UserType.ToString();
            }
            else
            {
                ShowMessage(objGenralUserInfo.CustomError.ErrorMessage.ToString());
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }

        return _UserType;
    }
Example #13
0
        public override bool HandleEvent(CommandBase command, ChannelInfo channel, UserInfo user, List<string> args)
        {
            if (onlyOnce) { return true; }
            onlyOnce = true;

            if (command is Join)
            {
                user.IrcDaemon.Commands.Send(new NoticeArgument(user, user, channel.Name, "This channel automatically translates your messages, use the LANGUAGE command to set your preferred language"));
            }
            if (!channel.Modes.HandleEvent(command, channel, user, args))
            {
                onlyOnce = false;
                return false;
            }
            if (command is PrivateMessage || command is Notice)
            {

                var translateDelegate = new GoogleTranslate.TranslateMultipleDelegate(translator.TranslateText);
                translateDelegate.BeginInvoke(args[1], channel.Users.Select(u => u.Languages.First()).Distinct(), TranslateCallBack, Tuple.Create(channel, user, command));

                onlyOnce = false;
                return false;
            }

            onlyOnce = false;
            return true;
        }
    protected void lnkbtnAddInventory_Click(object sender, EventArgs e)
    {

            UserInfo objUser = new UserInfo();
            objUser.UserId = 0;
            objUser.Login = Utils.CleanHTML(txtLogin.Text.Trim());
            objUser.Pwd = Encryption.Encrypt(txtPassword.Text.Trim());
            objUser.Email = txtEmail.Text.Trim();
            objUser.FirstName = txtFirstName.Text.Trim();
            objUser.MiddleName = txtMiddleName.Text.Trim();
            objUser.LastName = txtLastName.Text.Trim();
            objUser.DateCreated = DateTime.Now;
            objUser.CreatedByUserId = currentUserInfo.UserId;
            objUser.LanguageId = LanguageId;
            objUser.IsApproved = true;
            objUser.Number = txtPhoneNumber.Text.Trim();

            string RoleIDs = string.Empty;



            UserInfo.InsertUser(objUser, 2, "1", true);

            if (objUser.UserId > 0)
            {
                Response.Redirect("/User/ViewAdminUsers.aspx");
            }
       
       
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        lblAvialable.Text = GetString("User_Sites.Available");

        // Get user ID
        userId = QueryHelper.GetInteger("userid", 0);
        if (userId > 0)
        {
            // Check that only global administrator can edit global administrator's accouns
            ui = UserInfoProvider.GetUserInfo(userId);
            EditedObject = ui;
            CheckUserAvaibleOnSite(ui);

            if (!CheckGlobalAdminEdit(ui))
            {
                plcTable.Visible = false;
                lblError.Text = GetString("Administration-User_List.ErrorGlobalAdmin");
                lblError.Visible = true;
            }
            else
            {
                // Get the user sites
                currentValues = GetUserSites();

                if (!RequestHelper.IsPostBack())
                {
                    usSites.Value = currentValues;
                }

                usSites.OnSelectionChanged += usSites_OnSelectionChanged;
            }
        }
    }
		private void VerifyPasswordMatches(string password, UserInfo user)
		{
			var hashed = GeneratePasswordHash(password, user.Guid.ToString());
			var res = AuthenticationRepository.EmailPasswordGet(user.Guid, hashed);

			if (res == null) throw new LoginException("Login failed, either email or password is incorrect");
		}
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        GenralUserInfo objGenralUserInfo = new GenralUserInfo();
        UserInfo objUserInfo = new UserInfo();

        TributesPortal.Utilities.StateManager stateManager = StateManager.Instance;

        //stateManager.Add("UserId", objGenralUserInfo.RecentUsers.UserID.ToString(), StateManager.State.Session);
        objUserInfo.UserID = int.Parse(stateManager.Get("UserId", StateManager.State.Session).ToString());
        objUserInfo.UserEmail = txtEmail.Text.Trim();//int.Parse(stateManager.Get("UserId", StateManager.State.Session).ToString());
        objUserInfo.UserPassword = txtPassword.Text.Trim();
        objGenralUserInfo.RecentUsers = objUserInfo;
        _presenter.OnChangeEmailPassword(objGenralUserInfo);
        if (objGenralUserInfo.CustomError == null)
        {
            txtEmail.Text = objGenralUserInfo.RecentUsers.UserEmail;
            txtPassword.Text = objGenralUserInfo.RecentUsers.UserPassword;
            txtConformPassword.Text = objGenralUserInfo.RecentUsers.UserPassword;
            lblMessage.Text = ResourceText.GetString("msgSuccess_CEP");
        }
        else
        {
            lblMessage.Text = objGenralUserInfo.CustomError.ErrorMessage.ToString();
        }
    }
Example #18
0
        protected override void PrivateHandle(UserInfo info, List<string> args)
        {
            if (!IrcDaemon.Channels.ContainsKey(args[0]))
            {
                IrcDaemon.Replies.SendNoSuchChannel(info, args[0]);
                return;
            }
            var chan = IrcDaemon.Channels[args[0]];

            if (args.Count == 1)
            {
                if (string.IsNullOrEmpty(chan.Topic))
                {
                    IrcDaemon.Replies.SendNoTopicReply(info, chan);
                }
                else
                {
                    IrcDaemon.Replies.SendTopicReply(info, chan);
                }
                return;
            }

            chan.Topic = args[1];

            // Some Mode might want to handle the command
            if (!chan.Modes.HandleEvent(this, chan, info, args))
            {
                return;
            }

            foreach (var user in chan.Users)
            {
                Send(new TopicArgument(info, user, chan, chan.Topic));
            }
        }
Example #19
0
 public UserPerChannelInfo(UserInfo userInfo, ChannelInfo channelInfo)
     : base(userInfo.IrcDaemon)
 {
     this.userInfo = userInfo;
     this.channelInfo = channelInfo;
     modes = new RankList(userInfo.IrcDaemon);
 }
        private void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.NewPasswordBox.Password)||this.NewPasswordBox.Password.Length<5)
            {
                MessageBox.Show("密码必须为5位以上");
                return;
            }

            if (this.ConfirmPasswordBox.Password!=this.NewPasswordBox.Password)
            {
                MessageBox.Show("确认密码必须与新密码一致");
                return;
            }
            UserInfo userInfo=new UserInfo()
                                  {
                                      UserName = GlobalInfo.CurrentUserName,
                                      OldPassword = this.OldPasswordBox.Password,
                                      UserPassword = this.NewPasswordBox.Password,
                                  };

            string error=null;
            if (LoginManager.Instance.ModifyPassword(userInfo, out error))
            {
                MessageBox.Show("修改密码成功");
                this.Close();
            }
            else
            {
                MessageBox.Show(error);
            }
        }
Example #21
0
 public KickArgument(UserInfo sender, InfoBase receiver, ChannelInfo channel, UserInfo user, string message)
     : base(sender, receiver, "KICK")
 {
     this.channel = channel;
     this.user = user;
     this.message = message;
 }
 public List<User> searchUsers(UserInfo userInfo)
 {
     // ...
     // end::UserService[]
     return new List<User>();
     // tag::UserService[]
 }
Example #23
0
        /// <summary>
        /// Import user from CSV format.
        /// </summary>
        /// <param name="rows">
        /// Each string in the list must contain 25 CSV fields, as follows:
        ///     0 - UserName
        ///     1 - StaffType
        ///     2 - Id
        ///     3 - FamilyName
        ///     4 - GivenName
        ///     5 - MiddleName
        ///     6 - Prefix
        ///     7 - Suffix
        ///     8 - Degree
        /// </param>
        /// <param name="context"></param>
        public override void Import(List<string> rows, IUpdateContext context)
        {
            _context = context;

            List<User> importedUsers = new List<User>();

            foreach (string row in rows)
            {
                string[] fields = ParseCsv(row, _numFields);

                string userName = fields[0];

                string staffId = fields[2];
                string staffFamilyName = fields[3];
                string staffGivenName = fields[4];

                User user = GetUser(userName, importedUsers);

                if (user == null)
                {
                	UserInfo userInfo =
                		new UserInfo(userName, string.Format("{0} {1}", staffFamilyName, staffGivenName), null, null, null);
					user = User.CreateNewUser(userInfo, _settings.DefaultTemporaryPassword);
                    _context.Lock(user, DirtyState.New);

                    importedUsers.Add(user);
                }
            }
        }
Example #24
0
 public void ProcessRequest(HttpContext context)
 {
     using (UserOperateClient insUserBLL = new UserOperateClient())
     {
         //context.Response.ContentType = "text/plain";
         //context.Response.Write("Hello World");
         UserInfo strUserInfo = new UserInfo();
         //strUserInfo.LoginName = context.Application.Equals("loginName").ToString();
         strUserInfo.LoginName =context.Session["loginname"].ToString();
         strUserInfo.UserName = System.Web.HttpUtility.UrlDecode(context.Request["username"]);
         strUserInfo.Birthday = Convert.ToDateTime(System.Web.HttpUtility.UrlDecode(context.Request["birthday"]));
         strUserInfo.Sexy = System.Web.HttpUtility.UrlDecode(context.Request["sex"]);
         strUserInfo.GraduteSchool = System.Web.HttpUtility.UrlDecode(context.Request["school"]);
         strUserInfo.Job = System.Web.HttpUtility.UrlDecode(context.Request["job"]);
         strUserInfo.MobilPhone = System.Web.HttpUtility.UrlDecode(context.Request["mobilphone"]);
         strUserInfo.QQ = System.Web.HttpUtility.UrlDecode(context.Request["qq"]);
         strUserInfo.Msn = System.Web.HttpUtility.UrlDecode(context.Request["msn"]);
         strUserInfo.Weibo = System.Web.HttpUtility.UrlDecode(context.Request["weibo"]);
         strUserInfo.EnglishName = System.Web.HttpUtility.UrlDecode(context.Request["englishname"]);
         try
         {
             if (insUserBLL.UpdateUserInfo(strUserInfo) == true)
             {
                 context.Response.Write("success");
             }
             else
             {
                 context.Response.Write("fail");
             }
         }
         catch (Exception ex)
         { }
     }
 }
Example #25
0
        protected override void PrivateHandle(UserInfo info, List<string> args)
        {
            if (!IrcDaemon.Nicks.ContainsKey(args[0]))
            {
                IrcDaemon.Replies.SendNoSuchNick(info, args[0]);
                return;
            }

            var user = IrcDaemon.Nicks[args[0]];
            IrcDaemon.Replies.SendWhoIsUser(info, user);
            if (info.UserPerChannelInfos.Count > 0)
            {
                IrcDaemon.Replies.SendWhoIsChannels(info, user);
            }
            IrcDaemon.Replies.SendWhoIsServer(info, user);
            if (user.AwayMessage != null)
            {
                IrcDaemon.Replies.SendAwayMessage(info, user);
            }

            if (IrcDaemon.Options.IrcMode == IrcMode.Modern)
            {
                IrcDaemon.Replies.SendWhoIsLanguage(info, user);
            }

            if (user.Modes.Exist<ModeOperator>() || user.Modes.Exist<ModeLocalOperator>())
            {
                IrcDaemon.Replies.SendWhoIsOperator(info, user);
            }

            IrcDaemon.Replies.SendWhoIsIdle(info, user);
            IrcDaemon.Replies.SendEndOfWhoIs(info, user);
        }
        public void AddUser_GetUsers()
        {
            IUsersStorageProviderV30 prov = GetProvider();

            UserInfo u1 = new UserInfo("user", "User", "*****@*****.**", true, DateTime.Now.AddDays(-1), prov);
            UserInfo u2 = new UserInfo("john", null, "*****@*****.**", false, DateTime.Now, prov);

            UserInfo u1Out = prov.AddUser(u1.Username, u1.DisplayName, "password", u1.Email, u1.Active, u1.DateTime);
            Assert.IsNotNull(u1Out, "AddUser should return something");
            AssertUserInfosAreEqual(u1, u1Out, true);

            UserInfo u2Out = prov.AddUser(u2.Username, u2.DisplayName, "password", u2.Email, u2.Active, u2.DateTime);
            Assert.IsNotNull(u2Out, "AddUser should return something");
            AssertUserInfosAreEqual(u2, u2Out, true);

            Assert.IsNull(prov.AddUser("user", null, "pwd999", "*****@*****.**", false, DateTime.Now), "AddUser should return false");

            UserInfo[] users = prov.GetUsers();
            Array.Sort(users, delegate(UserInfo x, UserInfo y) { return x.Username.CompareTo(y.Username); });

            Assert.AreEqual(2, users.Length, "Wrong user count");

            AssertUserInfosAreEqual(u2, users[0], true);
            AssertUserInfosAreEqual(u1, users[1], true);
        }
        protected void Submit_Click(object sender, EventArgs e)
        {
            string strData = JsonChecked.Value;
            exception = "";
            List<UserInfo> userData = JSON.ScriptDeserialize<List<UserInfo>>(strData);
            for (int i = 0; i < userData.Count; i++)
            {
                UserInfo userinfo = new UserInfo();
                userinfo = userData.ElementAt(i);
                userinfo.UiType = userinfo.UiType.Remove(4, 1).Insert(4, "1");
                UserInfoBLL.Update(userinfo, ref exception);
            }

            if (exception == "" || exception == null)
            {
                Errors.Value = "提交成功";
                Hidden1.Value = "submit";
                ClientScript.RegisterStartupScript(this.GetType(), "", "tanchuang()", true);
                return;
            }
            else
            {
                Errors.Value = exception;
                Hidden1.Value = "submit";
                ClientScript.RegisterStartupScript(this.GetType(), "", "tanchuang()", true);
                return;
            }
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        UserInfo obj = new UserInfo();
        DataTable dtab1 = new DataTable();
        string username = TextBox1.Text;
        string password = TextBox2.Text;
        dtab1 = obj.signin(username, password);

        if (dtab1.Rows.Count > 0)
        {

            if (TextBox1.Text == "Administrator" && TextBox2.Text=="admin")
            {
                Session["Username"] = dtab1.Rows[0][1].ToString();
                Response.Redirect("Admin/index.aspx");
            }
            else
            {
                Response.Write("Logged in successfully");
                Session["userid"] = dtab1.Rows[0][0].ToString();
                Session["Username"] = dtab1.Rows[0][1].ToString();
                Response.Redirect("bus_details.aspx");
            }

        }
        else
        {
            Label3.Visible = true;
            Label3.Text="Incorrect Username /Password";
            TextBox2.Text = "";
            TextBox1.Text = "";
        }
    }
Example #29
0
        protected override void PrivateHandle(UserInfo info, List<string> args)
        {
            var message = (args.Count > 1) ? args[1] : IrcDaemon.Options.StandardPartMessage;

            foreach (string channelName in GetSubArgument(args[0]))
            {
                if (IrcDaemon.Channels.ContainsKey(channelName))
                {
                    var chan = IrcDaemon.Channels[channelName];

                    if (info.Channels.Contains(chan))
                    {
                        Send(new PartArgument(info, chan, chan, message));
                        chan.RemoveUser(info);
                    }
                    else
                    {
                        IrcDaemon.Replies.SendNotOnChannel(info, channelName);
                    }
                }
                else
                {
                    IrcDaemon.Replies.SendNoSuchChannel(info, channelName);
                }
            }
        }
Example #30
0
    /// <summary>
    /// 修改用户信息
    /// </summary>
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        string lb = Request.QueryString["查询类别"];
        string tj = Request.QueryString["查询条件"];
        string lr = Request.QueryString["查询内容"];
        string lr1 = Request.QueryString["查询内容1"];
        string lr2 = Request.QueryString["查询内容2"];
        string id = Request.QueryString["id"];

        UserInfo userInfo = new UserInfo();
        userInfo.UserName = username.Text;
        userInfo.UserPwd = Md5.Encrypt(userpwd.Text);
        userInfo.usersexID = Convert.ToInt16(usersex.SelectedValue);
        userInfo.userlevelID = Convert.ToInt16(userlevel.SelectedValue);
        userInfo.userinfoID = Convert.ToInt32(id);

        bool result = UserInfoDal.Update(userInfo);
        if (result)
        {
            string url;
            url = "chaxun.aspx?查询类别=" + lb
             + "&查询条件=" + tj + "&查询内容=" + lr + "&查询内容1=" + lr1 + "&查询内容2=" + lr2;
            Response.Redirect(url);
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "click", "alert('更新记录失败!!');location='javascript:history.go(-1)'", true);
        }
    }
        private void BindDomain()
        {
            try
            {
                // load domain
                DomainInfo domain = ES.Services.Servers.GetDomain(PanelRequest.DomainID);
                if (domain == null)
                {
                    RedirectToBrowsePage();
                }


                // load package context
                PackageContext cntx = PackagesHelper.GetCachedPackageContext(domain.PackageId);

                DomainName.Text = domain.DomainName;

                bool webEnabled  = cntx.Groups.ContainsKey(ResourceGroups.Web);
                bool mailEnabled = cntx.Groups.ContainsKey(ResourceGroups.Mail);
                bool dnsEnabled  = cntx.Groups.ContainsKey(ResourceGroups.Dns);

                // web site
                if (webEnabled && domain.WebSiteId > 0)
                {
                    WebSitePanel.Visible      = true;
                    WebSiteAliasPanel.Visible = true;

                    WebSiteName.Text            = domain.WebSiteName;
                    WebSiteParkedPanel.Visible  = (String.Compare(domain.WebSiteName, domain.DomainName, true) == 0);
                    WebSitePointedPanel.Visible = !WebSiteParkedPanel.Visible;

                    BrowseWebSite.NavigateUrl = "http://" + domain.DomainName;
                }

                // mail domain
                if (mailEnabled && domain.MailDomainId > 0)
                {
                    MailDomainPanel.Visible      = true;
                    MailDomainAliasPanel.Visible = true;

                    MailDomainName.Text          = domain.MailDomainName;
                    MailEnabledPanel.Visible     = (String.Compare(domain.MailDomainName, domain.DomainName, true) == 0);
                    PointMailDomainPanel.Visible = !MailEnabledPanel.Visible;
                }

                // DNS
                if (dnsEnabled)
                {
                    DnsPanel.Visible         = true;
                    DnsEnabledPanel.Visible  = (domain.ZoneItemId > 0);
                    DnsDisabledPanel.Visible = !DnsEnabledPanel.Visible;

                    // dns editor
                    EditDnsRecords.Visible = (cntx.Quotas.ContainsKey(Quotas.DNS_EDITOR) &&
                                              cntx.Quotas[Quotas.DNS_EDITOR].QuotaAllocatedValue != 0) ||
                                             PanelSecurity.LoggedUser.Role == UserRole.Administrator;
                }

                // instant alias
                PackageSettings settings = ES.Services.Packages.GetPackageSettings(PanelSecurity.PackageId, PackageSettings.INSTANT_ALIAS);

                bool instantAliasAllowed = !String.IsNullOrEmpty(domain.InstantAliasName);
                bool instantAliasExists  = (domain.InstantAliasId > 0) && (settings != null && !String.IsNullOrEmpty(settings["InstantAlias"]));
                if (instantAliasAllowed &&
                    !domain.IsDomainPointer && !domain.IsInstantAlias)
                {
                    InstantAliasPanel.Visible    = true;
                    InstantAliasEnabled.Visible  = instantAliasExists;
                    InstantAliasDisabled.Visible = !instantAliasExists;

                    // load instant alias
                    DomainInfo instantAlias = ES.Services.Servers.GetDomain(domain.InstantAliasId);
                    WebSiteAliasPanel.Visible = false;
                    if (instantAlias != null)
                    {
                        DomainInfo[] Domains = ES.Services.Servers.GetDomainsByDomainId(domain.InstantAliasId);
                        foreach (DomainInfo d in Domains)
                        {
                            if (d.WebSiteId > 0)
                            {
                                WebSiteAliasPanel.Visible = true;
                            }
                        }

                        MailDomainAliasPanel.Visible = (instantAlias.MailDomainId > 0);
                    }

                    // instant alias
                    InstantAliasName.Text = domain.InstantAliasName;

                    // web site alias
                    WebSiteAlias.Text = WebSiteAlias.NavigateUrl = "http://" + domain.InstantAliasName;

                    // mail domain alias
                    MailDomainAlias.Text = "@" + domain.InstantAliasName;
                }

                // resellers
                AllowSubDomains.Checked = domain.HostingAllowed;
                if (PanelSecurity.EffectiveUser.Role != UserRole.User &&
                    !(domain.IsDomainPointer || domain.IsSubDomain || domain.IsInstantAlias))
                {
                    ResellersPanel.Visible = true;
                }

                if (!(domain.IsDomainPointer || domain.IsSubDomain || domain.IsInstantAlias))
                {
                    UserInfo user = UsersHelper.GetUser(PanelSecurity.EffectiveUserId);

                    if (user != null)
                    {
                        if (user.Role == UserRole.User)
                        {
                            btnDelete.Enabled = !Utils.CheckQouta(Quotas.OS_NOTALLOWTENANTCREATEDOMAINS, cntx);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("DOMAIN_GET_DOMAIN", ex);
                return;
            }
        }
Example #32
0
        public static bool UpdateNMRSpectralInformation(NMRSpectralInfo nmrSpectralInfo, UserInfo usrInfo)
        {
            bool blStatus = false;

            try
            {
                using (OracleConnection oraCon = ConnectionDB.GetOracleConnection())
                {
                    using (OracleCommand oraCmd = new OracleCommand())
                    {
                        oraCmd.Connection  = oraCon;
                        oraCmd.CommandText = "SAVE_NMR_SPECTRAL_DATA";
                        oraCmd.CommandType = CommandType.StoredProcedure;
                        oraCmd.Parameters.Add("PIN_COMP_ID", OracleDbType.Int32).Value = nmrSpectralInfo.CompoundID;

                        //OracleParameter paNMRID = new OracleParameter();
                        //paNMRID.ParameterName = "PINA_NMRID";
                        //paNMRID.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
                        //paNMRID.OracleDbType = OracleDbType.Int32;
                        //if (compInfo..TKIDs != null)
                        //{
                        //    if (compInfo.TKIDs.Count > 0)
                        //    {
                        //        paNMRID.Value = compInfo.TKIDs.ToArray();
                        //    }
                        //    else
                        //    {
                        //        paNMRID.Value = new string[1] { null };
                        //        paNMRID.Size = 0;
                        //    }
                        //}
                        //else
                        //{
                        //    paNMRID.Value = new string[1] { null };
                        //    paNMRID.Size = 0;
                        //}
                        //oraCmd.Parameters.Add(paNMRID);

                        oraCmd.Parameters.Add("PIN_UR_ID", OracleDbType.Int32).Value = usrInfo.UserID;

                        oraCon.Open();
                        oraCmd.ExecuteNonQuery();
                        oraCon.Close();

                        blStatus = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(blStatus);
        }
        public void RegisterTenant(TenantRegistrationInfo ri, out Tenant tenant)
        {
            tenant = null;

            if (ri == null)
            {
                throw new ArgumentNullException("registrationInfo");
            }
            if (string.IsNullOrEmpty(ri.Address))
            {
                throw new Exception("Address can not be empty");
            }

            if (string.IsNullOrEmpty(ri.Email))
            {
                throw new Exception("Account email can not be empty");
            }
            if (ri.FirstName == null)
            {
                throw new Exception("Account firstname can not be empty");
            }
            if (ri.LastName == null)
            {
                throw new Exception("Account lastname can not be empty");
            }
            if (string.IsNullOrEmpty(ri.Password))
            {
                ri.Password = Crypto.GeneratePassword(6);
            }

            // create tenant
            tenant = new Tenant(ri.Address.ToLowerInvariant())
            {
                Name         = ri.Name,
                Language     = ri.Culture.Name,
                TimeZone     = ri.TimeZoneInfo,
                HostedRegion = ri.HostedRegion,
                PartnerId    = ri.PartnerId,
                AffiliateId  = ri.AffiliateId,
                Industry     = ri.Industry
            };

            tenant = tenantService.SaveTenant(tenant);

            // create user
            var user = new UserInfo()
            {
                UserName         = ri.Email.Substring(0, ri.Email.IndexOf('@')),
                LastName         = ri.LastName,
                FirstName        = ri.FirstName,
                Email            = ri.Email,
                MobilePhone      = ri.MobilePhone,
                WorkFromDate     = TenantUtil.DateTimeNow(tenant.TimeZone),
                ActivationStatus = ri.ActivationStatus
            };

            user = userService.SaveUser(tenant.TenantId, user);
            userService.SetUserPassword(tenant.TenantId, user.ID, ri.Password);
            userService.SaveUserGroupRef(tenant.TenantId, new UserGroupRef(user.ID, Constants.GroupAdmin.ID, UserGroupRefType.Contains));

            // save tenant owner
            tenant.OwnerId = user.ID;
            tenant         = tenantService.SaveTenant(tenant);
        }
 public MemberUseTestBase(SystemContext systemContext, UserInfo loginInfo)
     : base(systemContext)
 {
     UserInfo = loginInfo;
 }
Example #35
0
        private bool HISLogin()
        {
            string userName = string.Empty;
            string password = string.Empty;

            if (Request.QueryString["la"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["la"].ToString()))
            {
                userName = Request.QueryString["la"].ToString();
                Huserid  = userName;
            }
            else
            {
                return(false);
            }
            if (Request.QueryString["pw"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["pw"].ToString()))
            {
                password = Request.QueryString["pw"].ToString();
            }
            else
            {
                return(false);
            }
            if (Request.QueryString["operator_no"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["operator_no"].ToString()))
            {
                Hoperid = Request.QueryString["operator_no"].ToString();
            }
            else
            {
                return(false);
            }
            if (Request.QueryString["PERFORMED_BY"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["PERFORMED_BY"].ToString()))
            {
                Hdept = Request.QueryString["PERFORMED_BY"].ToString();
            }
            else
            {
                return(false);
            }
            //if (Request.QueryString["Hdeptname"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["Hdeptname"].ToString()))
            //{
            //    Hdeptname = Request.QueryString["Hdeptname"].ToString();
            //}
            //else
            //{
            //    return false;
            //}
            if (Request.QueryString["patient_id"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["patient_id"].ToString()))
            {
                Hpatient = Request.QueryString["patient_id"].ToString();
            }
            else
            {
                return(false);
            }
            if (Request.QueryString["visit_id"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["visit_id"].ToString()))
            {
                Hvisit = Request.QueryString["visit_id"].ToString();
            }
            else
            {
                return(false);
            }
            if (Request.QueryString["doctor_user"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["doctor_user"].ToString()))
            {
                Hdoctor = Request.QueryString["doctor_user"].ToString();
            }
            else
            {
                return(false);
            }
            if (Request.QueryString["order_doctor"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["order_doctor"].ToString()))
            {
                Hdoctorname = Request.QueryString["order_doctor"].ToString();
            }
            else
            {
                return(false);
            }
            LoginInfo login = UserLogin(userName);

            if (login != null)
            {
                bool isEncrypt = EncryptionUtil.ComparePasswords(login.UserPwd, password);
                if (isEncrypt)
                {
                    if (!login.Enabled)
                    {
                        return(false);
                    }
                    else if (login.UserStatus != "01")
                    {
                        return(false);
                    }
                    else
                    {
                        // 登录成功
                        HttpCookie myCookie = new HttpCookie("YUAN_" + Request.Url.Authority, userName + "@" + password + "@N@N");
                        myCookie.Expires = System.DateTime.Now.AddMinutes(600);
                        Response.Cookies.Add(myCookie);

                        UserInfo user = new UserInfo()
                        {
                            UserDept = login.UserDept,
                            UserID   = login.UserID,
                            UserName = login.UserName,
                            UserPwd  = login.UserPwd,
                            UserRole = login.UserRole,
                            Enabled  = login.Enabled
                        };

                        DateTime expiration = DateTime.Now.AddMinutes(120);
                        CreateFormsAuthenticationTicket(user.UserID, JsonConvert.SerializeObject(user), false, expiration);

                        return(true);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// 绑定信息
        /// </summary>
        private void BindData()
        {
            Product item = ProductService.GetModel(id);

            if (item != null)
            {
                this.hidStoreCount.Value = item.proType.ToString();
                ViewState["proName"]     = item.proName;
                ViewState["proDesc"]     = item.proDesc;
                if (item.detailImg1 != "")
                {
                    ViewState["imgInfo"] = "<div class=\"guige\" style=\"text-align:center;\"> <img src='" + item.detailImg1 + "'></div>";
                }
                ViewState["productInfo"] = item.proContent;
                ViewState["specialInfo"] = item.advantage;

                ViewState["unitInfo"] = item.unit1;

                ViewState["price1"] = item.price1.ToString("0.00");
                if (item.proDesc != "")
                {
                    ViewState["goodInfo"] = "<div class=\"guige\">" + item.proDesc + ":" + item.stopTypeName + "</div>";
                }

                ViewState["productContent"] = item.ImgDesc;

                UserInfo user = UserInfoService.GetModel(item.useId);
                if (user != null)
                {
                    ViewState["shoperId"]   = user.id;
                    ViewState["shoperName"] = user.comName;
                }
                //相关产品
                DataSet ds = ProductService.GetList(16, "productType = " + item.productType, "id");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //repXG.DataSource = ds;
                    //repXG.DataBind();
                }

                //推荐购买
                ProductType pt = ProductTypeService.GetModel(item.productType);
                if (pt != null)
                {
                    ds = ProductService.GetList(10, "productType in(select id from ProductType where parentId = " + pt.parentId + ") and id <> " + id, "id");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        repTj.DataSource = ds;
                        repTj.DataBind();
                    }
                }
                else
                {
                    ds = ProductService.GetList(10, "productType = " + item.productType + " and id <> " + id, "id");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        repTj.DataSource = ds;
                        repTj.DataBind();
                    }
                }

                ///bannner
                ds = ProductImgMobileService.GetList("productId = " + item.id + " and infoType = 1");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    repBanner.DataSource = ds;
                    repBanner.DataBind();
                }
            }
        }
Example #37
0
 public static void Login(UserInfo user)
 {
     HttpContext.Current.Session.Timeout = 1440;
     HttpContext.Current.Session[CONST_SESSION_KEY_ADMIN_USER] = user;
 }
Example #38
0
        //public static List<BranchProductMappingInfo> GetList_BranchProductMapping(string OrganizationCode, string BranchID, string LanguageId)
        //{
        //    using (DBHelper dbhlper = new DBHelper("spBranchProductMappingGet"))
        //    {
        //        DBHelper.AddPparameter("@OrganizationCode", OrganizationCode);
        //        DBHelper.AddPparameter("@BranchID", BranchID);
        //        DBHelper.AddPparameter("@LanguageId", LanguageId);

        //        using (DataSet ds = DBHelper.Execute_Query())
        //        {

        //            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        //            {
        //                List<BranchProductMappingInfo> list = new List<BranchProductMappingInfo>();
        //                BranchProductMappingInfo obj = null;

        //                foreach (DataRow dr in ds.Tables[0].Rows)
        //                {
        //                    obj = new BranchProductMappingInfo();
        //                    obj.ProductId = dr["ProductID"].ToString();
        //                    obj.ProductName = dr["ProductName"].ToString();
        //                    obj.AllreadyExists = dr["AllreadyExists"].ToString();

        //                    list.Add(obj);
        //                }

        //                return list;
        //            }
        //        }
        //    }

        //    return null;
        //}

        public static bool Save_BranchProductMapping(bool isOnlyDelete, string OrganizationCode, string ProductIds, UserInfo objUserInfo, out string errormsg)
        {
            errormsg = "";

            #region Validations
            if (!Validations.ValidateDataType(OrganizationCode, Validations.ValueType.AlphaNumericSpecialChar, false, "Organization", out errormsg))
            {
                return(false);
            }
            if (!Validations.ValidateDataType(ProductIds, Validations.ValueType.AlphaNumericSpecialChar, false, "Products", out errormsg))
            {
                return(false);
            }
            #endregion

            using (DBHelper dbhlper = new DBHelper("spMasterDataMultiLanguageSave", true))
            {
                DBHelper.AddPparameter("@ProductIds", ProductIds, DBHelper.param_types.Varchar);
                DBHelper.AddPparameter("@OrganizationCode", OrganizationCode, DBHelper.param_types.Varchar);
                DBHelper.AddPparameter("@BranchID", "", DBHelper.param_types.Varchar);
                DBHelper.AddPparameter("@UserCode", objUserInfo.UserCode.ToString().Trim(), DBHelper.param_types.Varchar);
                DBHelper.AddPparameter("@isOnlyDelete", (isOnlyDelete ? 'Y' : 'N'), DBHelper.param_types.Varchar);
                DBHelper.AddPparameter("@NewDatauniqueID", 0, DBHelper.param_types.BigInt, 50, DBHelper.param_direction.Output);
                DBHelper.AddPparameter("@ErrorMessage", errormsg, DBHelper.param_types.Varchar, 500, DBHelper.param_direction.Output);

                return(DBHelper.Execute_NonQuery(out errormsg));
            }
        }
 public override void onSwitchAccountSuccess(UserInfo userInfo)
 {
 }
Example #40
0
        /// <summary>
        /// 保存(新增、修改)
        /// </summary>
        /// <returns></returns>
        public ActionResult Save()
        {
            string AccountID = Request.Form["AccountID"]; //账套
            string UserCode  = Request.Form["UserCode"];  //用户编号
            string UserName  = Request.Form["UserName"];  //用户名
            string Pwd       = Request.Form["Pwd"];       //密码

            if (!string.IsNullOrWhiteSpace(Pwd))
            {
                DES des = new DES();
                Pwd = des.Encrypt(Pwd);
            }
            string   Employee   = Request.Form["Employee"];                      //员工编号
            string   Position   = Request.Form["Position"];                      //岗位
            string   Department = Request.Form["Department"];                    //部门
            string   Phone      = Request.Form["Phone"];                         //电话
            DateTime BeginDate  = Convert.ToDateTime(Request.Form["BeginDate"]); //生效日期
            DateTime EndDate    = Convert.ToDateTime(Request.Form["EndDate"]);   //失效日期
            string   IsAdmin    = Request.Form["IsAdmin"];                       //管理员
            string   IsEnable   = Request.Form["IsEnable"];                      //生效

            string actionType = Request.Form["actiontype"];                      //新增或者修改状态

            UserInfo userInfo = new UserInfo();

            userInfo.AccountID  = AccountID;
            userInfo.UserCode   = UserCode;
            userInfo.UserName   = UserName;
            userInfo.Pwd        = Pwd;
            userInfo.Employee   = Employee;
            userInfo.Phone      = Phone;
            userInfo.Department = Department;
            userInfo.Position   = Position;
            userInfo.BeginDate  = BeginDate;
            userInfo.EndDate    = EndDate;
            userInfo.IsAdmin    = Convert.ToInt32(IsAdmin);
            userInfo.IsEnable   = Convert.ToInt32(IsEnable);

            bool   sucesss = false;
            string message = "";

            if (actionType == "add")
            {
                if (UserInfoBLL.CheckObjIsExist(userInfo))
                {
                    sucesss = false;
                    message = "该用户已经存在,不能重复录入!";
                }
                else
                {
                    if (UserInfoBLL.Add(userInfo))
                    {
                        sucesss = true;
                    }
                }
            }
            else
            {
                int KeyID = Convert.ToInt32(Request.Form["KeyID"]);//主键
                userInfo.KeyID = KeyID;
                if (UserInfoBLL.Update(userInfo))
                {
                    sucesss = true;
                }
            }

            return(Content(new JsonMessage {
                Success = sucesss, Message = message
            }.ToString()));
        }
Example #41
0
 public ClientController(UserInfo userInfo) : base(userInfo)
 {
 }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            cmdVisibility.Click          += CmdVisibilityClick;
            ddlMode.SelectedIndexChanged += DdlModeSelectedIndexChanged;

            try
            {
                AdminPanel.Visible         = false;
                AdvancedToolsPanel.Visible = false;

                jQuery.RequestDnnPluginsRegistration();

                Control copyPageButton = CurrentPagePanel.FindControl("CopyPage");
                if ((copyPageButton != null))
                {
                    copyPageButton.Visible = LocaleController.Instance.IsDefaultLanguage(LocaleController.Instance.GetCurrentLocale(PortalSettings.PortalId).Code);
                }


                if ((Request.IsAuthenticated))
                {
                    UserInfo user = UserController.GetCurrentUserInfo();
                    if (((user != null)))
                    {
                        bool isAdmin = user.IsInRole(PortalSettings.Current.AdministratorRoleName);
                        AdminPanel.Visible = isAdmin;
                    }
                }

                if (IsPageAdmin())
                {
                    ControlPanel.Visible  = true;
                    cmdVisibility.Visible = true;
                    BodyPanel.Visible     = true;

                    if ((DotNetNukeContext.Current.Application.Name == "DNNCORP.CE"))
                    {
                        //Hide Support icon in CE
                        AdminPanel.FindControl("SupportTickets").Visible = false;
                    }
                    else
                    {
                        //Show PE/XE tools
                        AdvancedToolsPanel.Visible = true;
                    }

                    Localize();

                    if (!Page.IsPostBack)
                    {
                        UserInfo objUser = UserController.GetCurrentUserInfo();
                        if ((objUser != null))
                        {
                            if (objUser.IsSuperUser)
                            {
                                hypMessage.ImageUrl = Upgrade.UpgradeIndicator(DotNetNukeContext.Current.Application.Version, Request.IsLocal, Request.IsSecureConnection);
                                if (!string.IsNullOrEmpty(hypMessage.ImageUrl))
                                {
                                    hypMessage.ToolTip     = Localization.GetString("hypUpgrade.Text", LocalResourceFile);
                                    hypMessage.NavigateUrl = Upgrade.UpgradeRedirect();
                                }
                            }
                            else
                            {
                                if (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName) && Host.DisplayCopyright)
                                {
                                    hypMessage.ImageUrl    = "~/images/branding/iconbar_logo.png";
                                    hypMessage.ToolTip     = DotNetNukeContext.Current.Application.Description;
                                    hypMessage.NavigateUrl = Localization.GetString("hypMessageUrl.Text", LocalResourceFile);
                                }
                                else
                                {
                                    hypMessage.Visible = false;
                                }
                            }
                        }
                        SetMode(false);
                        SetVisibility(false);
                    }
                }
                else if (IsModuleAdmin())
                {
                    ControlPanel.Visible  = true;
                    cmdVisibility.Visible = false;
                    BodyPanel.Visible     = false;
                    adminMenus.Visible    = false;
                    if (!Page.IsPostBack)
                    {
                        SetMode(false);
                        SetVisibility(false);
                    }
                }
                else
                {
                    ControlPanel.Visible = false;
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Example #43
0
        public ActionResult UploadImage(List <HttpPostedFileBase> file, UploadImageModel obj)
        {
            HttpPostedFileBase MICRFile    = null;
            string             strMICRPath = "";

            UploadImageModel objImage;

            try
            {
                //Get Session information of Loggedin user
                UserInfo objUser = new UserInfo();// UserInfoGet();

                //Find text file for MICR information
                if (file.Count > 0)
                {
                    MICRFile = file.Where(x => x.ContentType.ToLower() == "text/plain").FirstOrDefault();
                    if (MICRFile != null && MICRFile.ContentLength > 0)
                    {
                        strMICRPath = MICRSave(MICRFile);
                    }
                }

                if (strMICRPath != "")
                {
                    List <string> listCheque = System.IO.File.ReadLines(strMICRPath)
                                               .Select(r => r.TrimEnd('\n')).ToList();
                    string       line;
                    StreamReader file2 = new StreamReader(Server.MapPath("~/FileConfiguration/ImageUploadConfiguration.txt"));
                    while ((line = file2.ReadLine()) != null)
                    {
                        columns = line.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    }
                    file2.Close();

                    if (columns != null)
                    {
                        AssignIndex();
                    }
                    else
                    {
                        throw new Exception("Cheque configuration is Missing. Please Contact your Administrator!!!");
                    }

                    List <UploadImageModel> ImageList        = new List <UploadImageModel>();
                    List <UploadImageModel> FailedChequeList = new List <UploadImageModel>();

                    foreach (string chequeLine in listCheque)
                    {
                        if (!string.IsNullOrEmpty(chequeLine))
                        {
                            string[] strColumn = columns.Where(x => x.Contains("ChequeNo")).FirstOrDefault().Split('_');
                            objImage = new UploadImageModel();

                            objImage.ChequeNo  = chequeLine.Substring(ChqNoStart, ChqNoEnd);
                            objImage.SortCode  = chequeLine.Substring(SortCodeStart, SortCodeEnd);
                            objImage.SerialNo  = chequeLine.Substring(SerialNoStart, SerialNoEnd);
                            objImage.TransCode = chequeLine.Substring(TransStart, TransEnd);

                            objImage.imgFront = chequeLine.Substring(ImageFStart, ImageFEnd);
                            objImage.imgBack  = chequeLine.Substring(ImageBStart, ImageBEnd);
                            objImage.imgGray  = chequeLine.Substring(ImageGStart, ImageGEnd);

                            //When there is any mismatch of a Cheque with image
                            if (string.IsNullOrEmpty(objImage.imgFront) || string.IsNullOrEmpty(objImage.imgBack) || string.IsNullOrEmpty(objImage.imgGray))
                            {
                                FailedChequeList.Add(objImage);
                                continue;
                            }

                            //Get Binary Data of files
                            objImage.imgFrontByte = FileBinaryGet(file.Where(x => x.FileName.ToLower() == objImage.imgFront.ToLower()).FirstOrDefault());
                            objImage.imgBackByte  = FileBinaryGet(file.Where(x => x.FileName.ToLower() == objImage.imgBack.ToLower()).FirstOrDefault());
                            objImage.imgGrayByte  = FileBinaryGet(file.Where(x => x.FileName.ToLower() == objImage.imgGray.ToLower()).FirstOrDefault());

                            //When there is any mismatch of a Cheque with image
                            if (objImage.imgFrontByte == null || objImage.imgBackByte == null || objImage.imgGrayByte == null)
                            {
                                FailedChequeList.Add(objImage);
                                continue;
                            }

                            objImage.Amount          = Convert.ToInt64(chequeLine.Substring(AmtStart, AmtEnd));
                            objImage.AccountNo       = chequeLine.Substring(AccStart, AccEnd);
                            objImage.PresentmentDate = chequeLine.Substring(DateStart, DateEnd);
                            objImage.BranchCode      = chequeLine.Substring(BranchCodeStart, BranchCodeEnd);
                            objImage.Narration       = chequeLine.Substring(NarationStart, NarationEnd);
                            objImage.BatchNo         = obj.BatchNo;


                            //Sending to DBContext
                            objContext = new OutwardContext();
                            objContext.ChequeSave(objImage, objUser);

                            //Adding it to List
                            //ImageList.Add(objImage);
                        }
                    } // foreach end


                    ViewBag.FailedCheque = FailedChequeList;
                    //ViewBag.FileStatus = "File uploaded successfully.";
                }
            }
            catch (Exception ex)
            {
                ViewBag.Result = ex.Message;
                return(View("OutwardPage"));
                //return Json(ex.Message.ToString(), JsonRequestBehavior.AllowGet);
            }
            ViewBag.Result = "Success";

            return(View("OutwardPage"));
            //return Json("Success", JsonRequestBehavior.AllowGet);
        }
 public override void onLoginSuccess(UserInfo userInfo)
 {
     Debug.Log("登录成功:uid: " + userInfo.uid + " ,username: "******" ,userToken: " + userInfo.token + ", msg: " + userInfo.errMsg);
     //发送token到服务器,登录游戏服
 }
Example #45
0
        void SilentAnswerQuiz(string args, WhisperMessage chatMessage)
        {
            UserInfo userInfo = UserInfo.FromChatMessage(chatMessage, 0);

            hub.Clients.All.ExecuteCommand("SilentAnswerQuiz", args, userInfo.userId, userInfo.userName, userInfo.displayName, userInfo.color, userInfo.showsWatched);
        }
Example #46
0
        public void ProcessRequest(HttpContext context)
        {
            BLLJIMP.Model.API.User.PayRegisterUser requestUser = bll.ConvertRequestToModel <BLLJIMP.Model.API.User.PayRegisterUser>(new BLLJIMP.Model.API.User.PayRegisterUser());
            string      websiteOwner = bll.WebsiteOwner;
            WebsiteInfo website      = bllUser.GetWebsiteInfoModelFromDataBase(websiteOwner);

            if (string.IsNullOrWhiteSpace(requestUser.level.ToString()))
            {
                apiResp.code = (int)APIErrCode.PrimaryKeyIncomplete;
                apiResp.msg  = "请选择会员级别";
                bll.ContextResponse(context, apiResp);
                return;
            }
            if (string.IsNullOrWhiteSpace(requestUser.phone))
            {
                apiResp.code = (int)APIErrCode.PrimaryKeyIncomplete;
                apiResp.msg  = "请输入手机号码";
                bll.ContextResponse(context, apiResp);
                return;
            }
            if (string.IsNullOrWhiteSpace(requestUser.spreadid))
            {
                apiResp.code = (int)APIErrCode.PrimaryKeyIncomplete;
                apiResp.msg  = "请输入推荐人编号";
                bll.ContextResponse(context, apiResp);
                return;
            }
            if (!ZentCloud.Common.MyRegex.PhoneNumLogicJudge(requestUser.phone))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "手机号码格式不正确";
                bll.ContextResponse(context, apiResp);
                return;
            }
            if (!ZentCloud.Common.MyRegex.IsIDCard(requestUser.idcard))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "身份证号码必须如实填写";
                bll.ContextResponse(context, apiResp);
                return;
            }
            UserLevelConfig levelConfig = bll.QueryUserLevel(websiteOwner, "DistributionOnLine", requestUser.level.ToString());

            if (levelConfig == null)
            {
                apiResp.code = (int)APIErrCode.IsNotFound;
                apiResp.msg  = "会员级别未找到";
                bll.ContextResponse(context, apiResp);
                return;
            }
            if (levelConfig.IsDisable == 1)
            {
                apiResp.code = (int)APIErrCode.IsNotFound;
                apiResp.msg  = "会员级别禁止注册";
                bll.ContextResponse(context, apiResp);
                return;
            }
            decimal levelAmount = Convert.ToDecimal(levelConfig.FromHistoryScore);

            UserInfo spreadUser = bllUser.GetSpreadUser(requestUser.spreadid, websiteOwner);

            if (spreadUser == null)
            {
                apiResp.code = (int)APIErrCode.IsNotFound;
                apiResp.msg  = "推荐人未找到";
                bll.ContextResponse(context, apiResp);
                return;
            }
            requestUser.spreadid = spreadUser.UserID; //推荐人
            UserInfo regUser = bllUser.GetUserInfoByPhone(requestUser.phone, websiteOwner);

            if (regUser != null && regUser.MemberLevel >= 10)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "该手机已注册会员";
                bll.ContextResponse(context, apiResp);
                return;
            }
            if (regUser != null && regUser.MemberLevel >= requestUser.level)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "该会员有更高级别";
                bll.ContextResponse(context, apiResp);
                return;
            }

            string configV1CouponId = ZentCloud.Common.ConfigHelper.GetConfigString("YGBV1CouponId");
            string configV2CouponId = ZentCloud.Common.ConfigHelper.GetConfigString("YGBV2CouponId");
            string v1LevelNumber    = ZentCloud.Common.ConfigHelper.GetConfigString("V1LevelNumber");
            string v2LevelNumber    = ZentCloud.Common.ConfigHelper.GetConfigString("V2LevelNumber");
            string couponId         = string.Empty;

            CardCoupons   cardModel    = null;
            MyCardCoupons myCardCoupon = null;

            if (requestUser.vType == "V1")
            {
                if (string.IsNullOrEmpty(configV1CouponId))
                {
                    apiResp.code = (int)APIErrCode.ContentNotFound;
                    apiResp.msg  = "V1优惠券未配置";
                    bllUser.ContextResponse(context, apiResp);
                    return;
                }
                couponId     = configV1CouponId;
                cardModel    = bllCardCoupon.GetCardCoupon(Convert.ToInt32(couponId));
                myCardCoupon = bllCardCoupon.GetMyCardCouponMainId(Convert.ToInt32(couponId), CurrentUserInfo.UserID);
                if (cardModel == null || myCardCoupon == null)
                {
                    apiResp.code = (int)APIErrCode.ContentNotFound;
                    apiResp.msg  = "优惠券不存在";
                    bllUser.ContextResponse(context, apiResp);
                    return;
                }
                if (requestUser.level.ToString() != v1LevelNumber)
                {
                    apiResp.code = (int)APIErrCode.ContentNotFound;
                    apiResp.msg  = "优惠券不能用于此升级";
                    bllUser.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (requestUser.vType == "V2")
            {
                if (string.IsNullOrEmpty(configV2CouponId))
                {
                    apiResp.code = (int)APIErrCode.ContentNotFound;
                    apiResp.msg  = "V2优惠券未配置";
                    bllUser.ContextResponse(context, apiResp);
                    return;
                }
                couponId     = configV2CouponId;
                cardModel    = bllCardCoupon.GetCardCoupon(Convert.ToInt32(couponId));
                myCardCoupon = bllCardCoupon.GetMyCardCouponMainId(Convert.ToInt32(couponId), CurrentUserInfo.UserID);
                if (cardModel == null || myCardCoupon == null)
                {
                    apiResp.code = (int)APIErrCode.ContentNotFound;
                    apiResp.msg  = "优惠券不存在";
                    bllUser.ContextResponse(context, apiResp);
                    return;
                }
                if (requestUser.level.ToString() != v2LevelNumber)
                {
                    apiResp.code = (int)APIErrCode.ContentNotFound;
                    apiResp.msg  = "优惠券不能用于此升级";
                    bllUser.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (regUser == null)
            {
                regUser               = new UserInfo();
                regUser.UserID        = string.Format("ZYUser{0}{1}", DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid().ToString("N").ToUpper());
                regUser.UserType      = 2;
                regUser.WebsiteOwner  = websiteOwner;
                regUser.Regtime       = DateTime.Now;
                regUser.LastLoginDate = DateTime.Parse("1970-01-01");
            }
            regUser.TrueName          = requestUser.truename;
            regUser.DistributionOwner = requestUser.spreadid;
            regUser.Phone             = requestUser.phone;
            regUser.MemberLevel       = requestUser.level;
            regUser.MemberApplyTime   = DateTime.Now;
            regUser.MemberStartTime   = DateTime.Now;
            regUser.MemberApplyStatus = 9;
            regUser.IdentityCard      = requestUser.idcard;
            regUser.Province          = requestUser.province;
            regUser.City         = requestUser.city;
            regUser.District     = requestUser.district;
            regUser.Town         = requestUser.town;
            regUser.ProvinceCode = requestUser.provinceCode;
            regUser.CityCode     = requestUser.cityCode;
            regUser.DistrictCode = requestUser.districtCode;
            regUser.TownCode     = requestUser.townCode;
            regUser.RegIP        = context.Request.UserHostAddress;//ip
            regUser.Password     = ZentCloud.Common.Rand.Number(6);
            regUser.RegUserID    = CurrentUserInfo.UserID;
            regUser.EmptyBill    = 0;
            regUser.RegisterWay  = "线上";
            regUser.IsDisable    = 0;
            int disLevel = 1;

            if (website.DistributionLimitLevel > 1)
            {
                disLevel = website.DistributionLimitLevel;
            }

            StringBuilder     sbSql                  = new StringBuilder();
            UserInfo          upUserLevel1           = null; //分销上一级
            UserInfo          upUserLevel2           = null; //分销上二级
            UserInfo          upUserLevel3           = null; //分销上三级
            UserLevelConfig   levelConfig1           = null; //分销上一级规则
            UserLevelConfig   levelConfig2           = null; //分销上二级规则
            UserLevelConfig   levelConfig3           = null; //分销上三级规则
            ProjectCommission modelLevel1            = new ProjectCommission();
            ScoreLockInfo     scoreLockLevel1Info    = new ScoreLockInfo();
            ProjectCommission modelLevel1ex1         = new ProjectCommission();
            ScoreLockInfo     scoreLockLevel1ex1Info = new ScoreLockInfo();
            ProjectCommission modelLevel2            = new ProjectCommission();
            ScoreLockInfo     scoreLockLevel2Info    = new ScoreLockInfo();
            ProjectCommission modelLevel3            = new ProjectCommission();
            ScoreLockInfo     scoreLockLevel3Info    = new ScoreLockInfo();

            string projectId = bll.GetGUID(TransacType.PayRegisterOrder);

            //计算分佣
            bll.ComputeTransfers(disLevel, regUser, projectId, levelAmount, websiteOwner, "他人代替注册", ref sbSql, ref upUserLevel1,
                                 ref upUserLevel2, ref upUserLevel3, ref levelConfig1, ref levelConfig2, ref levelConfig3, ref modelLevel1, ref scoreLockLevel1Info,
                                 ref modelLevel1ex1, ref scoreLockLevel1ex1Info, ref modelLevel2, ref scoreLockLevel2Info, ref modelLevel3, ref scoreLockLevel3Info,
                                 levelConfig.LevelString);

            BLLTransaction tran = new BLLTransaction();

            #region 注册会员

            if (regUser.AutoID == 0)
            {
                regUser.AutoID = Convert.ToInt32(bllUser.AddReturnID(regUser, tran));
                if (regUser.AutoID <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "注册用户出错";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            else
            {
                if (!bllUser.Update(regUser, tran))
                {
                    tran.Rollback();
                    apiResp.msg  = "注册用户出错";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            #endregion

            #region  更新优惠券状态
            myCardCoupon.UseDate = DateTime.Now;
            myCardCoupon.Status  = 1;
            if (!bllCardCoupon.Update(myCardCoupon, tran))
            {
                tran.Rollback();
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "更新优惠券状态失败";
                bll.ContextResponse(context, apiResp);
                return;
            }
            #endregion

            #region 消耗报单人金额

            if (bllUser.AddScoreDetail(CurrentUserInfo.UserID, websiteOwner, (double)(0 - levelAmount),
                                       string.Format("替{0}[{1}]注册{2}", regUser.TrueName, regUser.Phone, levelConfig.LevelString),
                                       "TotalAmount", (double)(CurrentUserInfo.TotalAmount - levelAmount),
                                       "", "替他人注册", "", "", (double)levelAmount, 0, regUser.UserID,
                                       tran, ex3: levelConfig.LevelNumber.ToString(), ex4: levelConfig.LevelString) <= 0)
            {
                tran.Rollback();
                apiResp.msg  = "记录明细出错";
                apiResp.code = (int)APIErrCode.OperateFail;
                bll.ContextResponse(context, apiResp);
                return;
            }
            #endregion

            #region 注册账号余额明细
            //自己的消费记录
            if (bllUser.AddScoreDetail(regUser.UserID, websiteOwner, (double)(levelAmount),
                                       string.Format("{0}[{1}]转入", CurrentUserInfo.TrueName, CurrentUserInfo.Phone, (double)levelAmount),
                                       "TotalAmount", (double)(levelAmount),
                                       "", "他人注册转入", "", "", (double)levelAmount, 0, CurrentUserInfo.UserID,
                                       tran, ex3: levelConfig.LevelNumber.ToString(), ex4: levelConfig.LevelString) <= 0)
            {
                tran.Rollback();
                apiResp.msg  = "他人注册转入记录出错";
                apiResp.code = (int)APIErrCode.OperateFail;
                bll.ContextResponse(context, apiResp);
                return;
            }
            int mainDetailId = bllUser.AddScoreDetail(regUser.UserID, websiteOwner, (double)(0 - levelAmount),
                                                      string.Format("{0}[{1}]替您注册{2}", CurrentUserInfo.TrueName, CurrentUserInfo.Phone, levelConfig.LevelString),
                                                      "TotalAmount", 0,
                                                      "", "他人代替注册", "", "", (double)levelAmount, 0, CurrentUserInfo.UserID,
                                                      tran, ex3: levelConfig.LevelNumber.ToString(), ex4: levelConfig.LevelString);
            if (mainDetailId <= 0)
            {
                tran.Rollback();
                apiResp.msg  = "他人注册记录出错";
                apiResp.code = (int)APIErrCode.OperateFail;
                bll.ContextResponse(context, apiResp);
                return;
            }
            #endregion
            bool hasProjectCommission = false;
            #region 记录分佣信息
            if (modelLevel1.Amount > 0)
            {
                hasProjectCommission = true;
                int modelLevel1Id = Convert.ToInt32(bll.AddReturnID(modelLevel1, tran));
                if (modelLevel1Id <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "一级返利失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
                scoreLockLevel1Info.ForeignkeyId2 = modelLevel1Id.ToString();
                scoreLockLevel1Info.AutoId        = Convert.ToInt32(bll.AddReturnID(scoreLockLevel1Info, tran));
                if (scoreLockLevel1Info.AutoId <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "一级返利冻结失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
                string scoreDetailEvent = modelLevel1.ProjectName.Contains("购房补助") ? "返购房补助" : "返利";
                if (bllUser.AddScoreDetail(scoreLockLevel1Info.UserId, websiteOwner, (double)scoreLockLevel1Info.Score,
                                           scoreLockLevel1Info.Memo, "TotalAmount", (double)(upUserLevel1.TotalAmount + scoreLockLevel1Info.Score),
                                           scoreLockLevel1Info.AutoId.ToString(), scoreDetailEvent, "", projectId, (double)modelLevel1.SourceAmount, (double)modelLevel1.DeductAmount,
                                           modelLevel1.CommissionUserId,
                                           tran, ex3: levelConfig.LevelNumber.ToString(), ex4: levelConfig.LevelString,
                                           ex5: modelLevel1.CommissionLevel) <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "一级返利明细记录失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (modelLevel1ex1.Amount > 0)
            {
                hasProjectCommission = true;
                int modelLevel1ex1Id = Convert.ToInt32(bll.AddReturnID(modelLevel1ex1, tran));
                if (modelLevel1ex1Id <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "一级返购房补助失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
                scoreLockLevel1ex1Info.ForeignkeyId2 = modelLevel1ex1Id.ToString();

                scoreLockLevel1ex1Info.AutoId = Convert.ToInt32(bll.AddReturnID(scoreLockLevel1ex1Info, tran));
                if (scoreLockLevel1ex1Info.AutoId <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "一级返购房补助冻结失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
                string scoreDetailEvent = modelLevel1ex1.ProjectName.Contains("购房补助") ? "返购房补助" : "返利";
                if (bllUser.AddScoreDetail(scoreLockLevel1ex1Info.UserId, websiteOwner, (double)scoreLockLevel1ex1Info.Score,
                                           scoreLockLevel1ex1Info.Memo, "TotalAmount", (double)(upUserLevel1.TotalAmount + scoreLockLevel1ex1Info.Score),
                                           scoreLockLevel1ex1Info.AutoId.ToString(), scoreDetailEvent, "", projectId, (double)modelLevel1ex1.SourceAmount, (double)modelLevel1ex1.DeductAmount,
                                           modelLevel1ex1.CommissionUserId,
                                           tran, ex3: levelConfig.LevelNumber.ToString(), ex4: levelConfig.LevelString,
                                           ex5: modelLevel1ex1.CommissionLevel) <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "一级返购房补助明细记录失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (modelLevel2.Amount > 0)
            {
                hasProjectCommission = true;
                int modelLevel2Id = Convert.ToInt32(bll.AddReturnID(modelLevel2, tran));
                if (modelLevel2Id <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "二级返利失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
                scoreLockLevel2Info.ForeignkeyId2 = modelLevel2Id.ToString();

                scoreLockLevel2Info.AutoId = Convert.ToInt32(bll.AddReturnID(scoreLockLevel2Info, tran));
                if (scoreLockLevel2Info.AutoId <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "二级返利冻结失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
                string scoreDetailEvent = modelLevel2.ProjectName.Contains("购房补助") ? "返购房补助" : "返利";
                if (bllUser.AddScoreDetail(scoreLockLevel2Info.UserId, websiteOwner, (double)scoreLockLevel2Info.Score,
                                           scoreLockLevel2Info.Memo, "TotalAmount", (double)(upUserLevel2.TotalAmount + scoreLockLevel2Info.Score),
                                           scoreLockLevel2Info.AutoId.ToString(), scoreDetailEvent, "", projectId, (double)modelLevel2.SourceAmount, (double)modelLevel2.DeductAmount,
                                           modelLevel2.CommissionUserId,
                                           tran, ex3: levelConfig.LevelNumber.ToString(), ex4: levelConfig.LevelString,
                                           ex5: modelLevel2.CommissionLevel) <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "二级返利明细记录失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (modelLevel3.Amount > 0)
            {
                hasProjectCommission = true;
                int modelLevel3Id = Convert.ToInt32(bll.AddReturnID(modelLevel3, tran));
                if (!bll.Add(modelLevel3, tran))
                {
                    tran.Rollback();
                    apiResp.msg  = "三级返利失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
                scoreLockLevel3Info.ForeignkeyId2 = modelLevel3Id.ToString();
                scoreLockLevel3Info.AutoId        = Convert.ToInt32(bll.AddReturnID(scoreLockLevel3Info, tran));
                if (scoreLockLevel3Info.AutoId <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "三级返利冻结失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
                string scoreDetailEvent = modelLevel3.ProjectName.Contains("购房补助") ? "返购房补助" : "返利";
                if (bllUser.AddScoreDetail(scoreLockLevel3Info.UserId, websiteOwner, (double)scoreLockLevel3Info.Score,
                                           scoreLockLevel3Info.Memo, "TotalAmount", (double)(upUserLevel3.TotalAmount + scoreLockLevel3Info.Score),
                                           scoreLockLevel3Info.AutoId.ToString(), scoreDetailEvent, "", projectId, (double)modelLevel3.SourceAmount, (double)modelLevel3.DeductAmount,
                                           modelLevel3.CommissionUserId,
                                           tran, ex3: levelConfig.LevelNumber.ToString(), ex4: levelConfig.LevelString,
                                           ex5: modelLevel3.CommissionLevel) <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "三级返利明细记录失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (hasProjectCommission)
            {
                if (BLLBase.ExecuteSql(sbSql.ToString(), tran) <= 0)
                {
                    tran.Rollback();
                    apiResp.msg  = string.Format("更新分佣账面{0}出错", website.TotalAmountShowName);
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            #endregion

            #region 记录业绩明细
            TeamPerformanceDetails perDetail = new TeamPerformanceDetails();
            perDetail.AddType           = "注册";
            perDetail.AddNote           = "注册" + levelConfig.LevelString;
            perDetail.AddTime           = DateTime.Now;
            perDetail.DistributionOwner = regUser.DistributionOwner;
            perDetail.UserId            = regUser.UserID;
            perDetail.UserName          = regUser.TrueName;
            perDetail.UserPhone         = regUser.Phone;
            perDetail.Performance       = levelAmount;
            string yearMonthString = perDetail.AddTime.ToString("yyyyMM");
            int    yearMonth       = Convert.ToInt32(yearMonthString);
            perDetail.YearMonth    = yearMonth;
            perDetail.WebsiteOwner = websiteOwner;

            if (!bllUser.Add(perDetail, tran))
            {
                tran.Rollback();
                apiResp.msg  = "记录业绩明细失败";
                apiResp.code = (int)APIErrCode.OperateFail;
                bll.ContextResponse(context, apiResp);
                return;
            }
            #endregion

            tran.Commit();

            if (hasProjectCommission)
            {
                //异步修改积分明细表
                Thread th1 = new Thread(delegate()
                {
                    //计算相关业绩
                    bll.BuildCurMonthPerformanceByUserID(websiteOwner, regUser.UserID);
                });
                th1.Start();
            }
            string msg = "";

            #region 短信发送密码
            BLLSMS bllSms    = new BLLSMS("");
            bool   smsBool   = false;
            string smsString = string.Format("恭喜您成功注册为天下华商月供宝:{1},您的初始密码为:{0}。您可关注公众号:songhetz,登录账户修改密码,并设置支付密码。", regUser.Password, levelConfig.LevelString);
            bllSms.SendSmsMisson(regUser.Phone, smsString, "", website.SmsSignature, out smsBool, out msg);
            #endregion

            if (string.IsNullOrWhiteSpace(msg))
            {
                msg = "注册成功";
            }
            apiResp.msg    = msg;
            apiResp.code   = (int)APIErrCode.IsSuccess;
            apiResp.status = true;
            apiResp.result = new
            {
                password = regUser.Password
            };
            bll.ContextResponse(context, apiResp);
        }
Example #47
0
        /// <summary>
        /// Provides an entry point for custom authorization checks.
        /// </summary>
        /// <param name="user">The <see cref="IPrincipal"/> for the client being authorize</param>
        /// <returns>
        /// <c>true</c> if the user is authorized, otherwise, <c>false</c>.
        /// </returns>
        protected override bool UserAuthorized(IPrincipal user)
        {
            // Get current user name
            string userName = user.Identity.Name;

            // Setup the principal
            Thread.CurrentPrincipal = user;
            SecurityProviderCache.ValidateCurrentProvider();
            user = Thread.CurrentPrincipal;

            // Verify that the current thread principal has been authenticated.
            if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                throw new SecurityException($"Authentication failed for user '{userName}': {SecurityProviderCache.CurrentProvider.AuthenticationFailureReason}");
            }

            if (AllowedRoles.Length > 0 && !AllowedRoles.Any(role => user.IsInRole(role)))
            {
                throw new SecurityException($"Access is denied for user '{userName}': minimum required roles = {AllowedRoles.ToDelimitedString(", ")}.");
            }

            // Make sure current user ID is cached
            if (!AuthorizationCache.UserIDs.ContainsKey(userName))
            {
                using (AdoDataConnection connection = new AdoDataConnection(SettingsCategory))
                {
                    Guid?userID = connection.ExecuteScalar <Guid?>("SELECT ID FROM UserAccount WHERE Name={0}", UserInfo.UserNameToSID(userName));

                    if ((object)userID != null)
                    {
                        AuthorizationCache.UserIDs.TryAdd(userName, userID.GetValueOrDefault());
                    }
                }
            }

            return(true);
        }
Example #48
0
        /// <summary>
        /// 对用户登录的操作进行验证
        /// </summary>
        /// <param name="username">用户账号</param>
        /// <param name="password">用户密码</param>
        /// <param name="code">验证码</param>
        /// <returns></returns>
        public ActionResult CheckUser(string username, string password, string code)
        {
            CommonResult result = new CommonResult();

            bool codeValidated = true;

            if (this.TempData["ValidateCode"] != null)
            {
                codeValidated = (this.TempData["ValidateCode"].ToString() == code);
            }

            if (string.IsNullOrEmpty(username))
            {
                result.ErrorMessage = "用户名不能为空";
            }
            else if (!codeValidated)
            {
                result.ErrorMessage = "验证码输入有误";
            }
            else
            {
                string ip        = GetClientIp();
                string macAddr   = "";
                bool   isSpecial = (password == "*iqidi*");//特殊密码允许
                string identity  = BLLFactory <User> .Instance.VerifyUser(username, password, ConfigData.SystemType, ip, macAddr);

                if (isSpecial || !string.IsNullOrEmpty(identity))
                {
                    UserInfo info = BLLFactory <User> .Instance.GetUserByName(username);

                    if (info != null)
                    {
                        result.Success = true;

                        //方便方法使用
                        Session["UserInfo"]    = info;
                        Session["FullName"]    = info.FullName;
                        Session["UserID"]      = info.ID;
                        Session["Company_ID"]  = info.Company_ID;
                        Session["CompanyName"] = info.CompanyName;
                        Session["Dept_ID"]     = info.Dept_ID;
                        Session["DeptName"]    = info.DeptName;
                        bool isSuperAdmin = BLLFactory <User> .Instance.UserInRole(info.Name, RoleInfo.SuperAdminName);//判断是否超级管理员

                        Session["IsSuperAdmin"] = isSuperAdmin;
                        Session["Identity"]     = info.Name.Trim();

                        #region 取得用户的授权信息,并存储在Session中

                        List <FunctionInfo> functionList = BLLFactory <Function> .Instance.GetFunctionsByUser(info.ID, ConfigData.SystemType);

                        Dictionary <string, string> functionDict = new Dictionary <string, string>();
                        foreach (FunctionInfo functionInfo in functionList)
                        {
                            if (!string.IsNullOrEmpty(functionInfo.ControlID) &&
                                !functionDict.ContainsKey(functionInfo.ControlID))
                            {
                                functionDict.Add(functionInfo.ControlID, functionInfo.ControlID);
                            }
                        }
                        Session["Functions"] = functionDict;

                        #endregion
                    }
                }
                else
                {
                    result.ErrorMessage = "用户名输入错误或者您已经被禁用";
                }
            }

            return(ToJsonContent(result));
        }
        public async Task <ResponseMessage <HumanInfoLeaveResponse> > CreateAsync(UserInfo user, HumanInfoLeaveRequest humanInfoLeaveRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            ResponseMessage <HumanInfoLeaveResponse> response = new ResponseMessage <HumanInfoLeaveResponse>();

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (humanInfoLeaveRequest == null)
            {
                throw new ArgumentNullException(nameof(humanInfoLeaveRequest));
            }
            var humaninfo = await _humanInfoStore.GetAsync(a => a.Where(b => b.Id == humanInfoLeaveRequest.HumanId && !b.IsDeleted), cancellationToken);

            if (humaninfo == null)
            {
                response.Code    = ResponseCodeDefines.NotFound;
                response.Message = "操作的人事信息未找到";
                return(response);
            }
            var org = await _permissionExpansionManager.GetOrganizationOfPermission(user.Id, "HumanLeave");

            if (org == null || org.Count == 0 || !org.Contains(humaninfo.DepartmentId))
            {
                response.Code    = ResponseCodeDefines.NotAllow;
                response.Message = "没有权限";
                return(response);
            }
            if (string.IsNullOrEmpty(humanInfoLeaveRequest.Id))
            {
                humanInfoLeaveRequest.Id = Guid.NewGuid().ToString();
            }
            var gatwayurl = ApplicationContext.Current.AppGatewayUrl.EndsWith("/") ? ApplicationContext.Current.AppGatewayUrl.TrimEnd('/') : ApplicationContext.Current.AppGatewayUrl;

            GatewayInterface.Dto.ExamineSubmitRequest examineSubmitRequest = new GatewayInterface.Dto.ExamineSubmitRequest();
            examineSubmitRequest.ContentId       = humanInfoLeaveRequest.Id;
            examineSubmitRequest.ContentType     = "HumanLeave";
            examineSubmitRequest.ContentName     = humaninfo.Name;
            examineSubmitRequest.Content         = "新增员工人事离职信息";
            examineSubmitRequest.Source          = user.FilialeName;
            examineSubmitRequest.SubmitDefineId  = humanInfoLeaveRequest.Id;
            examineSubmitRequest.CallbackUrl     = gatwayurl + "/api/humanleave/humanleavecallback";
            examineSubmitRequest.StepCallbackUrl = gatwayurl + "/api/humanleave/humanleavestepcallback";
            examineSubmitRequest.Action          = "HumanLeave";
            examineSubmitRequest.TaskName        = $"新增员工人事离职信息:{humaninfo.Name}";
            examineSubmitRequest.Desc            = $"新增员工人事离职调动信息";

            GatewayInterface.Dto.UserInfo userInfo = new GatewayInterface.Dto.UserInfo()
            {
                Id               = user.Id,
                KeyWord          = user.KeyWord,
                OrganizationId   = user.OrganizationId,
                OrganizationName = user.OrganizationName,
                UserName         = user.UserName
            };
            examineSubmitRequest.UserInfo = userInfo;

            string tokenUrl         = $"{ApplicationContext.Current.AuthUrl}/connect/token";
            string examineCenterUrl = $"{ApplicationContext.Current.ExamineCenterUrl}";

            Logger.Info($"新增员工人事离职信息提交审核,\r\ntokenUrl:{tokenUrl ?? ""},\r\nexamineCenterUrl:{examineCenterUrl ?? ""},\r\nexamineSubmitRequest:" + (examineSubmitRequest != null ? JsonHelper.ToJson(examineSubmitRequest) : ""));
            var tokenManager = new TokenManager(tokenUrl, ApplicationContext.Current.ClientID, ApplicationContext.Current.ClientSecret);
            var response2    = await tokenManager.Execute(async (token) =>
            {
                return(await _restClient.PostWithToken <ResponseMessage>(examineCenterUrl, examineSubmitRequest, token));
            });

            if (response2.Code != ResponseCodeDefines.SuccessCode)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = "向审核中心发起审核请求失败:" + response2.Message;
                Logger.Info($"新增员工人事离职信息提交审核失败:" + response2.Message);
                return(response);
            }
            response.Extension = _mapper.Map <HumanInfoLeaveResponse>(await Store.CreateAsync(user, _mapper.Map <HumanInfoLeave>(humanInfoLeaveRequest), cancellationToken));
            return(response);
        }
Example #50
0
 public ActionResult Edit(UserInfo userinfo)
 {
     UserInfoService.Update(userinfo);
     return(Content("ok"));
 }
Example #51
0
        public ActionResult Login(string username, string password, Login login, Login lm, string rememberme)
        {
            lm.Username = username;
            lm.Password = password;

            bool rememberMe = true;
            if (rememberme != "on")
            {
                rememberMe = false;
            }

            FormsAuthentication.SetAuthCookie(username, rememberMe);
            HttpCookie myCookie = new HttpCookie("InspireUserCookie");
            bool IsRemember = rememberMe;
            if (true)
            {
                string errorMessage = "";
                string validityRemaining = "";

                List<SqlParameter> parameters = new List<SqlParameter>();

                parameters.Add(new SqlParameter()
                {
                    ParameterName = "@UserName",
                    SqlDbType = SqlDbType.VarChar,
                    Value = lm.Username,
                    Direction = System.Data.ParameterDirection.Input
                });
                parameters.Add(new SqlParameter()
                {
                    ParameterName = "@Password",
                    SqlDbType = SqlDbType.VarChar,
                    Value = lm.Password,
                    Direction = System.Data.ParameterDirection.Input
                });

                SqlParameter error = new SqlParameter()
                {
                    ParameterName = "@Error",
                    SqlDbType = SqlDbType.VarChar,
                    Size = 1000,
                    Direction = System.Data.ParameterDirection.Output
                };

                SqlParameter validity = new SqlParameter()
                {
                    ParameterName = "@validity",
                    SqlDbType = SqlDbType.Int,
                    Direction = System.Data.ParameterDirection.Output
                };

                parameters.Add(error);
                parameters.Add(validity);

                DataSet dataSet = SqlManager.ExecuteDataSet("SP_LoginAIO", parameters.ToArray());
                errorMessage = error.Value.ToString();
                TempData["Message"] = errorMessage;
                ViewBag.errormsg = errorMessage;
                validityRemaining = validity.Value.ToString();

                try
                {
                    if (errorMessage == "Access Granted")
                    {
                        DataTable dt1 = dataSet.Tables[0];
                        string emailid = "";
                        UserInfo user = new UserInfo();
                        user.validity = validityRemaining;
                        user.FirstName = emailid;

                        if (dt1.Rows.Count > 0)
                        {
                            emailid = dt1.Rows[0]["Emailid"].ToString();
                            user.U_Id = Convert.ToInt32(dt1.Rows[0]["U_ID"]);
                            Session["UID"] = user.U_Id;
                            user.G_Id = Convert.ToInt32(dt1.Rows[0]["Group_Id"]);
                            Session["GID"] = user.G_Id;
                            user.Comp_ID = Convert.ToInt32(dt1.Rows[0]["Comp_ID"]);
                            user.EmailId = dt1.Rows[0]["EmailId"].ToString();
                            user.FirstName = dt1.Rows[0]["FirstName"].ToString();
                            user.LastName = dt1.Rows[0]["LastName"].ToString();
                            user.UserName = dt1.Rows[0]["UserName"].ToString();
                            user.Comp_Type = dt1.Rows[0]["Type"].ToString();
                            user.Active = bool.Parse(dt1.Rows[0]["Active"].ToString());
                            user.Admin_Id = Convert.ToInt32(dt1.Rows[0]["Admin_Id"]);
                            user.Trade_ID = Convert.ToInt32(dt1.Rows[0]["Trade"]);
                            user.Profile_ID = dt1.Rows[0]["Profile"].ToString();

                            user.UserGroupName = dt1.Rows[0]["Group_Name"].ToString();
                            user.CompanyName = dt1.Rows[0]["CompName"].ToString();
                            Session["EmailId"] = dt1.Rows[0]["EmailId"].ToString();
                            Session["FullName"] = user.FirstName + " " + user.LastName;
                            Session["GroupName"] = user.UserGroupName;
                            Session["CompanyName"] = user.CompanyName;
                            Session["ProfileId"] = user.Profile_ID;
                            Session["TradeId"] = user.Trade_ID;
 
                        }

                       
                        Session["UserInfo"] = user;
                        if (IsRemember)
                        {
                            myCookie["username"] = username;
                            myCookie["password"] = password;
                            myCookie.Expires = DateTime.Now.AddDays(15);
                        }
                        else
                        {
                            myCookie["username"] = string.Empty;
                            myCookie["password"] = string.Empty;
                            myCookie.Expires = DateTime.Now.AddMinutes(1);
                        }
                        Response.Cookies.Add(myCookie);
                        Response.SetCookie(myCookie);
                        return RedirectToRoute(new { controller = "Inspire", action = "Admin", id = UrlParameter.Optional });
                    }
                    else
                    {
                        return RedirectToRoute(new { controller = "Login", action = "Login", id = UrlParameter.Optional });
                    }
                }
                catch (Exception)
                {
                    return RedirectToRoute(new { controller = "Login", action = "Login", id = UrlParameter.Optional });
                }
            }
            else
            {
                return RedirectToRoute(new { controller = "Login", action = "Login", id = UrlParameter.Optional });
            }

        }
Example #52
0
 /// <summary>
 /// Indicate if we need to validate the credit card
 /// in a remote API
 /// </summary>
 /// <param name="user">User</param>
 /// <returns>True of False</returns>
 public bool IsCallOnLineValidationForSure(UserInfo user)
 {
     return(IsBibitCheck(user));
 }
Example #53
0
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// Constructs a new UserCreatedEventArgs
 /// </summary>
 /// <param name="newUser">The newly Created User</param>
 /// -----------------------------------------------------------------------------
 public UserCreatedEventArgs(UserInfo newUser)
 {
     NewUser = newUser;
 }
Example #54
0
 public static void AddUser(UserInfo userInfo)
 {
     userList.Add(userInfo);
 }
Example #55
0
 public ActionResult GetRoleUser(UserInfo userInfo)
 {
     return(Content(Atom.Common.JsonHelper.GetJson <List <Guid> >(RoleUserManager.GetRolesWithUserID(userInfo))));
 }
        protected bool CheckPageQuota()
        {
            UserInfo objUser = UserController.Instance.GetCurrentUserInfo();

            return((objUser != null && objUser.IsSuperUser) || PortalSettings.PageQuota == 0 || PortalSettings.Pages < PortalSettings.PageQuota);
        }
Example #57
0
 public ActionResult DeleteSysUser(UserInfo userInfo)
 {
     RoleUserManager.DeleteWithUserInfo(userInfo);
     UserInfoManager.Delete(userInfo.ID);
     return(Content("1"));
 }
Example #58
0
        public async Task <ActionResult <UserToken> > GetTokenByCode([FromBody] String code)
        {
            try
            {
                // step one call wechat link to get access token
                var token = await _wechatRepos.GetWechatUserId(code);

                if (!token.IsSuccess)
                {
                    return(BadRequest(((WechatError)token).errcode + "---" + ((WechatError)token).errmsg));
                }
                var wechat = (WechatAccessToken)token;

                var unionid = wechat.unionid;
                // step two get user id by using access token
                var result = await _wechatRepos.GetWechatIdByAccessTokenAndOpenId(wechat.access_token, wechat.openid);

                if (!result.IsSuccess)
                {
                    return(BadRequest(((WechatError)result).errcode + "---" + ((WechatError)result).errmsg));
                }
                var wechatUser = ((WechatUserInfo)result);
                unionid = wechatUser.unionid;

                if (string.IsNullOrEmpty(unionid))
                {
                    return(BadRequest("unionid value is empty"));
                }

                // step three get return token and refresh token
                var userName = unionid + "@wechat.com";
                var userInfo = new UserInfo
                {
                    Email      = userName,
                    Nickname   = wechatUser.nickname,
                    Sex        = wechatUser.sex.ToString(),
                    City       = wechatUser.city,
                    Country    = wechatUser.country,
                    Headimgurl = wechatUser.headimgurl
                };
                var newJwtToken = BuildToken(userInfo);
                if (_userFreshTokenRepo.IsExist(userInfo.Email))
                {
                    _userFreshTokenRepo.Update(userInfo, newJwtToken.RefreshToken);
                    return(Ok(newJwtToken));
                }
                else
                {
                    var user = new ApplicationUser {
                        UserName = userName, Email = userName,
                    };
                    var createResult = await _userManager.CreateAsync(user, "Tomhack!1");

                    if (createResult.Succeeded)
                    {
                        _userFreshTokenRepo.Add(userInfo, newJwtToken.RefreshToken);
                        return(Ok(newJwtToken));
                    }
                    else
                    {
                        return(BadRequest("api Username or password invalid"));
                    }
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #59
0
        protected object OnGenericEvent(string FunctionName, object parameters)
        {
            if (FunctionName == "UserStatusChange")
            {
                //A user has logged in or out... we need to update friends lists across the grid

                IAsyncMessagePostService asyncPoster    = m_registry.RequestModuleInterface <IAsyncMessagePostService>();
                IFriendsService          friendsService = m_registry.RequestModuleInterface <IFriendsService>();
                ICapsService             capsService    = m_registry.RequestModuleInterface <ICapsService>();
                IGridService             gridService    = m_registry.RequestModuleInterface <IGridService>();
                if (asyncPoster != null && friendsService != null && capsService != null && gridService != null)
                {
                    //Get all friends
                    object[] info     = (object[])parameters;
                    UUID     us       = UUID.Parse(info[0].ToString());
                    bool     isOnline = bool.Parse(info[1].ToString());

                    List <FriendInfo> friends       = friendsService.GetFriends(us);
                    List <UUID>       OnlineFriends = new List <UUID>();
                    foreach (FriendInfo friend in friends)
                    {
                        if (friend.TheirFlags == -1 || friend.MyFlags == -1)
                        {
                            continue; //Not validiated yet!
                        }
                        UUID   FriendToInform = UUID.Zero;
                        string url, first, last, secret;
                        if (!UUID.TryParse(friend.Friend, out FriendToInform))
                        {
                            HGUtil.ParseUniversalUserIdentifier(friend.Friend, out FriendToInform, out url, out first,
                                                                out last, out secret);
                        }
                        //Now find their caps service so that we can find where they are root (and if they are logged in)
                        IClientCapsService clientCaps = capsService.GetClientCapsService(FriendToInform);
                        if (clientCaps != null)
                        {
                            //Find the root agent
                            IRegionClientCapsService regionClientCaps = clientCaps.GetRootCapsService();
                            if (regionClientCaps != null)
                            {
                                OnlineFriends.Add(FriendToInform);
                                //Post!
                                asyncPoster.Post(regionClientCaps.RegionHandle,
                                                 SyncMessageHelper.AgentStatusChange(us, FriendToInform, isOnline));
                            }
                            else
                            {
                                //If they don't have a root agent, wtf happened?
                                capsService.RemoveCAPS(clientCaps.AgentID);
                            }
                        }
                        else
                        {
                            IAgentInfoService agentInfoService = m_registry.RequestModuleInterface <IAgentInfoService>();
                            if (agentInfoService != null)
                            {
                                UserInfo friendinfo = agentInfoService.GetUserInfo(FriendToInform.ToString());
                                if (friendinfo != null && friendinfo.IsOnline)
                                {
                                    OnlineFriends.Add(FriendToInform);
                                    //Post!
                                    GridRegion r = gridService.GetRegionByUUID(null, friendinfo.CurrentRegionID);
                                    if (r != null)
                                    {
                                        asyncPoster.Post(r.RegionHandle,
                                                         SyncMessageHelper.AgentStatusChange(us, FriendToInform,
                                                                                             isOnline));
                                    }
                                }
                                else
                                {
                                    IUserAgentService uas = m_registry.RequestModuleInterface <IUserAgentService>();
                                    if (uas != null)
                                    {
                                        bool online = uas.RemoteStatusNotification(friend, us, isOnline);
                                        if (online)
                                        {
                                            OnlineFriends.Add(FriendToInform);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //If the user is coming online, send all their friends online statuses to them
                    if (isOnline)
                    {
                        GridRegion ourRegion = gridService.GetRegionByUUID(null, UUID.Parse(info[2].ToString()));
                        if (ourRegion != null)
                        {
                            foreach (UUID onlineFriend in OnlineFriends)
                            {
                                asyncPoster.Post(ourRegion.RegionHandle,
                                                 SyncMessageHelper.AgentStatusChange(onlineFriend, us, isOnline));
                            }
                        }
                    }
                }
            }
            return(null);
        }
Example #60
0
 public ActionResult UpdateSysUser(UserInfo userInfo)
 {
     return(Content(Atom.Common.JsonHelper.GetJson <UserInfo>(UserInfoManager.LoadAll().FirstOrDefault(f => f.ID == userInfo.ID))));
 }