Ejemplo n.º 1
0
    /// <summary>
    /// 根据用户名和密码检索数据
    /// </summary>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    public void Select001(string username, string password)
    {
        Result.Clear();
        string sql = "select ID,USERNAME,PASSWORD,REALNAME,TELPHONE,CREATETIME,ADDRESS,STATUS,MEMO from CYGJ_USER_BASIC where " +
                     "USERNAME = '******' and PASSWORD = '******'";
        DataSet ds = OdbcDataManager.Instance.odbcOra.ReturnDataSet(sql, pageSize, CurrentPageIndex, "CYGJ_USER_BASIC");

        if (ds.Tables.Count > 0)
        {
            DataTable dt = ds.Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                UserBasicInfo info = new UserBasicInfo();
                info.ID         = dr["ID"].ToString();
                info.UserName   = dr["USERNAME"].ToString();
                info.Password   = dr["PASSWORD"].ToString();
                info.RealName   = dr["REALNAME"].ToString();
                info.Telphone   = dr["TELPHONE"].ToString();
                info.CreateTime = dr["CREATETIME"].ToString();
                info.Address    = dr["ADDRESS"].ToString();
                info.Status     = dr["STATUS"].ToString();
                info.Memo       = dr["MEMO"].ToString();

                Result.Add(info);
            }
        }
        Logger.Instance.WriteLog("根据用户名和密码检索数据。检索件数:" + Result.Count);
    }
Ejemplo n.º 2
0
    /// <summary>
    /// 确定创建用户
    /// </summary>
    public void Comfirm()
    {
        Logger.Instance.WriteLog("保存新创建的用户信息");
        UserBasicDao ubdao = new UserBasicDao();

        ubdao.Insert001(IPTAccount.value, IPTPassword.value, IPTRealName.value,
                        IPTTelphone.value, System.DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss"),
                        IPTAddress.value, "正常", IPTMemo.value);

        ubdao.Select003(IPTAccount.value);
        UserBasicInfo ubInfo = ubdao.Result [0];

        string goupId = "1";

        foreach (GroupInfo info in Groups)
        {
            if (PPLGroup.value == info.Name)
            {
                goupId = info.Id;
                break;
            }
        }

        UserGroupDao ugpDao = new UserGroupDao();

        ugpDao.Insert001(ubInfo.ID, goupId);

        UserRecordManage.Instance.GetComponent <UserRecordManage> ().ReLoadUserRecord();
        Destroy(gameObject);
    }
Ejemplo n.º 3
0
        public async Task <IActionResult> UpdateProfile(UserBasicInfo model)
        {
            try
            {
                if (model == null || String.IsNullOrWhiteSpace(model.Id) || String.IsNullOrWhiteSpace(model.Name) || String.IsNullOrWhiteSpace(model.Email))
                {
                    return(BadRequest(new { message = "Incomplete user information" }));
                }

                if (model.Id != userId)
                {
                    return(BadRequest(new { message = "Invalid user update request" }));
                }

                var existingUser = await databaseService.GetUserAsync(model.Id);

                if (existingUser == null)
                {
                    return(BadRequest(new { message = "User doesn't exit" }));
                }

                existingUser.Email = model.Email;
                existingUser.Name  = model.Name;
                existingUser.Image = model.Image;

                var insertedUser = await databaseService.SaveUserAsync(existingUser);

                return(Ok(insertedUser));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Ejemplo n.º 4
0
        //GetUserBasicInfo TDY 2014-12-4  //WF 20151010
        public UserBasicInfo GetUserBasicInfo(DataConnection pclsCache, string UserId)
        {
            UserBasicInfo ret = new UserBasicInfo();

            try
            {
                if (!pclsCache.Connect())
                {
                    return(null);
                }
                //Array a = Ps.BasicInfo.GetPatientBasicInfo(pclsCache.CacheConnectionObject, UserId);
                ret.UserName      = Ps.BasicInfo.GetPatientBasicInfo(pclsCache.CacheConnectionObject, UserId)[0].ToString();
                ret.Birthday      = Ps.BasicInfo.GetPatientBasicInfo(pclsCache.CacheConnectionObject, UserId)[1].ToString();
                ret.Gender        = Ps.BasicInfo.GetPatientBasicInfo(pclsCache.CacheConnectionObject, UserId)[2].ToString();
                ret.BloodType     = Ps.BasicInfo.GetPatientBasicInfo(pclsCache.CacheConnectionObject, UserId)[3].ToString();
                ret.IDNo          = Ps.BasicInfo.GetPatientBasicInfo(pclsCache.CacheConnectionObject, UserId)[4].ToString();
                ret.DoctorId      = Ps.BasicInfo.GetPatientBasicInfo(pclsCache.CacheConnectionObject, UserId)[5].ToString();
                ret.InsuranceType = Ps.BasicInfo.GetPatientBasicInfo(pclsCache.CacheConnectionObject, UserId)[6].ToString();
                ret.InvalidFlag   = Ps.BasicInfo.GetPatientBasicInfo(pclsCache.CacheConnectionObject, UserId)[7].ToString();



                return(ret);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString(), "获取名称失败!");
                HygeiaComUtility.WriteClientLog(HygeiaEnum.LogType.ErrorLog, "PsBasicInfo.GetUserBasicInfo", "数据库操作异常! error information : " + ex.Message + Environment.NewLine + ex.StackTrace);
                return(null);
            }
            finally
            {
                pclsCache.DisConnect();
            }
        }
Ejemplo n.º 5
0
    public void AddNewUser()
    {
        Logger.Instance.WriteLog("保存新创建的用户信息");
        UserBasicDao ubdao = new UserBasicDao();

        ubdao.Insert001(accountName.value, UIRecord.UBInfo.Password, userName.value,
                        userMobile.value, System.DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss"),
                        userAdd.value, "正常", remark.value);

        ubdao.Select003(accountName.value);
        UserBasicInfo ubInfo = ubdao.Result [0];

        string goupId = "1";

        foreach (UILabel lb in groups)
        {
            if (lb.transform.parent.GetComponent <userGroupItem>().selectToggle.value)
            {
                goupId = lb.transform.parent.GetComponent <userGroupItem>().info.Id;
            }
        }

        UserGroupDao ugpDao = new UserGroupDao();

        ugpDao.Insert001(ubInfo.ID, goupId);

        ReLoadUserRecord();
        newBtn.SetActive(true);
        updateBtn.SetActive(false);
    }
Ejemplo n.º 6
0
        //1:所内用户  2:科技厅用户   3:纯外部用户
        public int GetRequestUserType(int UserID)
        {
            UserBasicInfo currentUser = GetBasicUserInfoByUserID(UserID);

            if (currentUser.UserTypeID == 1)
            {
                return(1);
            }
            else
            {
                OuterUserInfo OuterUser = GetOuterUserInfoByUserID(UserID);
                bool          var1      = OuterUser.Roles.Exists((RoleInfo r) => r.RoleId == 4);//科技厅领导角色是4
                bool          var2      = false;
                if (OuterUser.InstitueName != null)
                {
                    var2 = OuterUser.InstitueName.Contains("科技厅");//机构名称中有科技厅
                }
                if (var1 || var2)
                {
                    return(2);
                }
                else
                {
                    return(3);
                }
            }
        }
            public static UserBasicInfo MapUserBasicDto(UserInfo uInfo, UserBasicDto d)
            {
                IFolderInfo   userFolder = FolderManager.Instance.GetUserFolder(uInfo);
                UserBasicInfo info       = new UserBasicInfo()
                {
                    userId             = d.UserId,
                    displayName        = d.Displayname,
                    userName           = d.Username,
                    email              = d.Email,
                    avatar             = uInfo.Profile.PhotoURL.Contains("no_avatar.gif") ? Vanjaro.Common.Utilities.UserUtils.GetProfileImage(PortalSettings.Current.PortalId, d.UserId, d.Email) : d.AvatarUrl,
                    firstName          = d.Firstname,
                    lastName           = d.Lastname,
                    createdOnDate      = d.CreatedOnDate,
                    isDeleted          = d.IsDeleted,
                    authorized         = uInfo.Membership.Approved,
                    isSuperUser        = d.IsSuperUser,
                    isAdmin            = d.IsAdmin,
                    lastLogin          = uInfo.Membership.LastLoginDate,
                    lastActivity       = uInfo.Membership.LastActivityDate,
                    lastPasswordChange = uInfo.Membership.LastPasswordChangeDate,
                    lastLockout        = uInfo.Membership.LastLockoutDate,
                    isLocked           = uInfo.Membership.LockedOut,
                    needUpdatePassword = uInfo.Membership.UpdatePassword,
                    portalId           = uInfo.PortalID,
                    userFolder         = FolderManager.Instance.GetUserFolder(uInfo).FolderPath.Substring(6),
                    userFolderId       = userFolder != null ? userFolder.FolderID : -1,
                    hasUserFiles       = FolderManager.Instance.GetFiles(userFolder, true).Any()
                };

                return(info);
            }
 /// <summary>
 /// 修改
 /// </summary>
 public void Updateuserbasicinfo(UserBasicInfo userbasicinfo)          //Convert.ToDateTime("01/01/1900");
 {
     //if (userbasicinfo.Birthday ==null||userbasicinfo.Birthday==Convert.ToDateTime ("01/01/0001"))
     //{
     //    userbasicinfo .Birthday = Convert.ToDateTime("01/01/1900");
     //}
     ExecuteUpdate("Updateuserbasicinfo", userbasicinfo);
 }
 /// <summary>
 /// 新建
 /// </summary>
 public void Adduserbasicinfo(UserBasicInfo userbasicinfo)
 {
     //if (userbasicinfo.Birthday == null || userbasicinfo.Birthday == Convert.ToDateTime("01/01/0001"))
     //{
     //    userbasicinfo.Birthday = Convert.ToDateTime("01/01/1900");
     //}
     // userbasicinfo.RegisterId = new aers_sys_seedSqlMapDao().GetMaxID("Message");
     ExecuteInsert("Insertuserbasicinfo", userbasicinfo);
 }
Ejemplo n.º 10
0
        public async Task <ActionResult <ProjectModel> > PostProjectModel(ProjectModel projectModel)
        {
            string userId = User.Claims.First(c => c.Type == "UserID").Value;
            var    user   = await _userManager.Users.Include(x => x.UserBasic).FirstOrDefaultAsync(x => x.Id == userId);

            ProjectModel newProject = new ProjectModel()
            {
                Name      = projectModel.Name,
                AddedDate = DateTime.Now
            };



            UserBasicInfo projManager = _context.UserBasicInfo.FirstOrDefault(x => x.Id == projectModel.ProjectManager.Id);

            newProject.ProjectManager = projManager;
            UserBasicInfo projCreator = _context.UserBasicInfo.FirstOrDefault(x => x.Id == user.UserBasic.Id);

            newProject.ProjectCreator = projCreator;

            try
            {
                _context.Projects.Add(newProject);
                await _context.SaveChangesAsync();

                ProjectUserModel projMan = new ProjectUserModel()
                {
                    ProjectId = newProject.Id,
                    UserId    = projectModel.ProjectManager.Id
                };
                _context.ProjectUser.Add(projMan);

                if (projManager.Id != user.UserBasic.Id)
                {
                    ProjectUserModel projCre = new ProjectUserModel()
                    {
                        ProjectId = newProject.Id,
                        UserId    = user.UserBasic.Id
                    };
                    _context.ProjectUser.Add(projCre);
                }

                var result = await _context.SaveChangesAsync();

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="accessToken">ACCESS TOKEN</param>
        /// <param name="userid">用户OPENID</param>
        /// <returns></returns>
        public override UserBasicInfo GetUserBasicInfomation(String accessToken, String userid)
        {
            String requestUrl = String.Format(API_URL, "get_user_info", accessToken, ClientId, userid);

            var reply = HttpPost(requestUrl, new{});

            if (reply.IsSuccessStatusCode)
            {
                var result = reply.Content.ReadAsStringAsync().Result;

                Dictionary <String, String> rep = JsonConvert.DeserializeObject <Dictionary <String, String> >(result);

                UserBasicInfo userInfo = new UserBasicInfo();

                Int32 ret = 0;
                if (rep.ContainsKey("ret") && Int32.TryParse(rep["ret"], out ret))
                {
                    throw new Exception("invalid reply. No return code.");
                }
                else if (ret < 0)
                {
                    throw new Exception(rep.ContainsKey("msg") ? rep["msg"] : " failed to get user's infomation, no message. return code = " + ret);
                }


                userInfo.OpenID = userid;

                if (rep.ContainsKey("nickname"))
                {
                    userInfo.Name = rep["nickname"];
                }

                if (rep.ContainsKey("gender"))
                {
                    userInfo.Gender = rep["gender"];
                }

                if (rep.ContainsKey("figureurl_qq_1"))
                {
                    userInfo.Avatar = rep["figureurl_qq_1"];
                }

                return(userInfo);
            }
            else
            {
                throw new Exception("failed to get user's basic infomation. code = " + reply.StatusCode);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 获取执行人列表
        /// </summary>
        /// <param name="RefID"></param>
        /// <param name="stepNum"></param>
        /// <returns></returns>
        public List <UserBasicInfo> GetRelatives(int RefID, int stepNum)
        {
            List <UserBasicInfo>  list = new List <UserBasicInfo>();
            ProcessStepEntityInfo step;
            UserBasicInfo         user;
            string sql;

            switch (stepNum)
            {
            case 2:
            case 3:
            case 4:
            case 8:
                step = GetProcessStep(RefID, "资源申请业务流程", stepNum);
                list = base.GetRelatives(step.ProcessStepModelID);
                break;

            case 5:
                // 第四步执行人的下属
                step = GetProcessStep(RefID, "资源申请业务流程", 4);
                sql  = @"SELECT  U.*
                            FROM    dbo.SYS_R_User_Department UD
		                            INNER JOIN dbo.SYS_R_User_Department UD1 ON UD1.depID = UD.depID
                                    INNER JOIN dbo.SYS_User U ON U.userID = UD1.UserID
                            WHERE	UD.UserID = @UserID AND UD.IsSupervisor = 1"    ;
                list = SqlMapDAL.CreateNameQuery("QueryDb").ReplaceText("{0}", sql).SetParameter("UserID", step.ExecutiveByID).ListEntity <UserBasicInfo>();
                break;

            case 6:
                // 第四步执行人
                step          = GetProcessStep(RefID, "资源申请业务流程", 4);
                user          = new UserBasicInfo();
                user.UserID   = step.ExecutiveByID;
                user.UserName = step.ExecutiveBy;
                list.Add(user);
                break;

            case 7:
                // 第三步执行人
                step          = GetProcessStep(RefID, "资源申请业务流程", 3);
                user          = new UserBasicInfo();
                user.UserID   = step.ExecutiveByID;
                user.UserName = step.ExecutiveBy;
                list.Add(user);
                break;
            }
            return(list);
        }
        /// <summary>
        /// 发表评论
        /// </summary>
        /// <returns></returns>

        public ActionResult AddCotent()
        {
            //获取登录用户信息
            UserLogin userLogin = new UserLogin(this.HttpContext);     //将当前页面信息传入UserLogin
            int       userId    = userLogin.GetUserId();               //如果对象不为空,获取UserId
            string    username  = "";

            if (userId == 0)
            {
                return(null);
            }
            else
            {
                using (SYSClient client = new SYSClient())
                {
                    UserBasicInfo info = client.GetUserBaseInfo(userId);
                    username = info.UserName;
                    client.Close();
                }
            }
            //发表评论
            long   docid       = 0;
            bool   isanonymous = false;
            string content     = "";
            int    result      = -1;
            long   parentid    = 0; //默认

            if (Request["isanonymous"] != null && Request["isanonymous"] != "")
            {
                isanonymous = Convert.ToBoolean(Request["isanonymous"]);             //当前页码
            }
            if (Request["content"] != null && Request["content"] != "")
            {
                content = Request["content"];               //页容量
            }
            if (Request["docid"] != null || !string.IsNullOrEmpty(Request["docid"]))
            {
                long.TryParse((Request["docid"]), out docid);
            }
            using (DFClient client = new DFClient())
            {
                result = client.InsertComment(docid, isanonymous, userId, username, content, parentid);
                client.Close();
            }
            return(result > 0 ? Json(new { Status = "success", Msg = "发布成功" }) : Json(new { Status = "success", Msg = "发布失败" }));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="dataTypeEntities">Data type entity</param>
        /// <param name="idEntity">ID entity. Unique code</param>
        public FileEntityBase(DataTypeEnum dataTypeEntities, string entityId, EncryptTypeEnum encrypt, int version)
        {
            TypeEntity = dataTypeEntities;
            Encrypt    = encrypt;
            EntityId   = entityId;
            Version    = version;

            if (EntityId == null)
            {
                //create new ID
                EntityId    = Guid.NewGuid().ToString("N");
                CreatedWhen = DateTimeOffset.Now;
                UpdatedWhen = CreatedWhen;
                CreatedWho  = new UserBasicInfo();
                UpdatedWho  = CreatedWho;
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="accessToken">ACCESS TOKEN</param>
        /// <param name="userid">用户ID. 就是 http://weibo.com/u/xxxxxxxxxx &lt;- 这一串数字 </param>
        /// <returns></returns>
        public override UserBasicInfo GetUserBasicInfomation(String accessToken, String userid)
        {
            String requestUrl = String.Format(API_URL, "users/show.json");

            var reply = HttpPost(requestUrl, new
            {
                access_token = accessToken,
                uid          = userid
            });

            if (reply.IsSuccessStatusCode)
            {
                var result = reply.Content.ReadAsStringAsync().Result;

                Dictionary <String, String> rep = JsonConvert.DeserializeObject <Dictionary <String, String> >(result);

                UserBasicInfo userInfo = new UserBasicInfo();

                if (rep.ContainsKey("id"))
                {
                    userInfo.OpenID = rep["id"];
                }

                if (rep.ContainsKey("screen_name"))
                {
                    userInfo.Name = rep["screen_name"];
                }

                if (rep.ContainsKey("gender"))
                {
                    userInfo.Gender = rep["gender"] == "m" ? "男" : "女";
                }

                if (rep.ContainsKey("avatar_large"))
                {
                    userInfo.Avatar = rep["avatar_large"];
                }

                return(userInfo);
            }
            else
            {
                throw new Exception("failed to get user's basic infomation. code = " + reply.StatusCode);
            }
        }
        private string GetEmailContent(UserBasicInfo ownerInfo, List <WebVisitReport> relatedVisits, GetDropdownValueResponse lifeCycleStages)
        {
            var emailContent = string.Empty;

            if (!relatedVisits.IsAny())
            {
                return(emailContent);
            }

            relatedVisits.ForEach(c =>
            {
                c.VisitedOn      = c.VisitedOn.ToTimezone(ownerInfo.TimeZone);
                c.LifecycleStage = lifeCycleStages
                                   .DropdownValues
                                   .DropdownValuesList
                                   .Where(d => d.DropdownValueID == c.LifecycleStageId)
                                   .Select(d => d.DropdownValue)
                                   .FirstOrDefault() ?? "";
            });

            emailContent += relatedVisits.GetTable(
                p => p.FirstName,
                p => p.LastName,
                p => p.Email,
                p => p.Phone,
                p => p.Zip,
                p => p.LifecycleStage,
                p => p.VisitedOn,
                p => p.PageViews,
                p => p.Duration,
                p => p.Page1,
                p => p.Page2,
                p => p.Page3,
                p => p.Source,
                p => p.LeadScore,
                p => p.Location);

            return(emailContent);
        }
Ejemplo n.º 17
0
    public int getUserInfoFormDB(ref List <UserBasicInfo> users)
    {
        try
        {
            string  sql = "select ID,USERNAME,PASSWORD,REALNAME,TELPHONE,CREATETIME,ADDRESS,STATUS,MEMO  from CYGJ_USER_BASIC order by CREATETIME asc";
            DataSet ds  = OdbcDataManager.Instance.odbcOra.ReturnDataSet(sql, pageSize, CurrentPageIndex, "CYGJ_USER_BASIC");
            if (ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    UserBasicInfo info = new UserBasicInfo();
                    info.ID         = dr["ID"].ToString();
                    info.UserName   = dr["USERNAME"].ToString();
                    info.Password   = dr["PASSWORD"].ToString();
                    info.RealName   = dr["REALNAME"].ToString();
                    info.Telphone   = dr["TELPHONE"].ToString();
                    info.CreateTime = dr["CREATETIME"].ToString();
                    info.Address    = dr["ADDRESS"].ToString();
                    info.Status     = dr["STATUS"].ToString();
                    info.Memo       = dr["MEMO"].ToString();
                    users.Add(info);
                }
            }
            Logger.Instance.WriteLog("检索所有用户信息。检索件数:" + users.Count);
        }
        catch (System.Exception e)
        {
            Logger.Instance.error(e.Message);
            users.Clear();
            return(-1);
        }


        return(users.Count);
    }
Ejemplo n.º 18
0
        public ActionResult ChangeUserAccess(UsersAccessControlViewModel model)
        {
            model.Users = Mapper.Map <IEnumerable <User>, IEnumerable <UserBasicInfo> >(accessRepository.UsersWithAccess(model.DocumentID));
            if (!userRepository.CheckUser(model.ChangeAccessToUser) || string.IsNullOrEmpty(model.ChangeAccessToUser))
            {
                ModelState.AddModelError(string.Empty, "Пользователя с таким логином не существует");
            }
            else
            {
                var user     = userRepository.SearchUserByLogin(model.ChangeAccessToUser);
                var userInfo = new UserBasicInfo()
                {
                    UserID = user.UserID,
                    Login  = user.Login
                };

                if (userInfo.UserID != fileRepository.GetHolder(model.DocumentID))
                {
                    accessRepository.ChangePartialAccessToUser(userInfo.UserID, model.DocumentID);
                }
            }

            return(RedirectToAction("GetAllDocuments"));
        }
Ejemplo n.º 19
0
        private void AddHospitalUserInfo()
        {
            UserService userservice = new UserService();
            var         listUser    = GetUser();


            foreach (var item in listUser)
            {
//------------------------------------------------------------------------------------------------------------------------------------------------------
                //以前的注册表信息导入到授权表里面
                var registerdata       = userservice.GetUserregiserId();
                UserauthsSqlMapDao urd = new UserauthsSqlMapDao();    //授权表导入数据   登陆名,密码,以前的注册Id
                Userauths          ur  = new Userauths();
                ur.AuthsId       = new aers_sys_seedSqlMapDao().GetMaxID("Userauths");
                ur.LoginLastTime = Common.StrToDateTime();
                ur.LoginNumber   = item.LoginName;
                ur.LoginType     = 0; //院内账号类型是0;
                ur.Password      = item.Password;
                ur.RegisterId    = registerdata;
                ur.Verified      = 0;
                ur.ReguserId     = item.ReguserId;
                urd.Adduserauths(ur);


                //------------------------------------------------------------------------------------------------------------------------------------------------------
                aers_tbl_staffSqlMapDao sdao = new aers_tbl_staffSqlMapDao();
                aers_tbl_staff          s    = new aers_tbl_staff();
                var sdata = sdao.FindByRUid(item.ReguserId);
                //根据注册ID取出以前用户表里面的数据  科室id,姓名,性别,角色


                userregisterSqlMapDao urdao = new userregisterSqlMapDao(); //注册表导入姓名
                userregister          urr   = new userregister();
                urr.RegisterId = registerdata;                             //注册Id
                urr.Name       = sdata.Name;                               //添加姓名
                urdao.Updateuserregister(urr);

                userbasicinfoSqlMapDao ubdao = new userbasicinfoSqlMapDao();  //基本信息表导入性别
                UserBasicInfo          ub    = new UserBasicInfo();
                ub.RegisterId = registerdata;
                if (sdata.Sex == "107")
                {
                    ub.Sex = "女";
                }
                else if (sdata.Sex == "108")
                {
                    ub.Sex = "男";
                }
                else
                {
                    ub.Sex = "";
                }
                ub.Birthday = Common.StrToDateTime();
                ubdao.Updateuserbasicinfo(ub);

                UserrelrecordSqlMapDao urrrdao = new UserrelrecordSqlMapDao();   //组织关系表导入科室Id
                Userrelrecord          urrr    = new Userrelrecord();
                urrr.RegisterId   = registerdata;
                urrr.DepartmentId = sdata.DepId;     //科室Id
                urrr.Role         = sdata.RoleState; //还用以前的标记  角色

                aers_tbl_hospdepSqlMapDao ad = new aers_tbl_hospdepSqlMapDao();
                urrr.DepartmentName = ad.FindhospdepByDepId(sdata.DepId).HospdepName; //科室姓名
                var hospId = ad.FindhospdepByDepId(sdata.DepId).HospId;               //医院ID

                //  aers_tbl_hospitalSqlMapDao DDD = new aers_tbl_hospitalSqlMapDao(); //shit
                aers_tbl_events_ycSqlMapDao hdao = new aers_tbl_events_ycSqlMapDao();
                var hdat = hdao.hospitalFindByHospId(hospId);
                urrr.HospitalName = hdat.HospName; //医院姓名
                urrr.HospitalId   = hospId;        //医院Id

                //h.HospitalId = item.HospId;
                //h.Name = item.HospName;

                urrrdao.Updateuserrelrecord(urrr);
            }
        }
Ejemplo n.º 20
0
        protected void btnLoginIn_Click(object sender, EventArgs e)
        {
            string ad  = Request.Form["txUsername"];
            string pwd = Request.Form["txPassword"];
            string msg = "";

            Business.CacheFactory.ClearCache();
            UserBasicInfo domainUser = null;

            try {
                if (!UserState.IsLogin)
                {
                    // 检查用户是否存在
                    tbl_user user = Common.GetUserInfoByAd(ad);
                    if (user == null)
                    {
                        msg = "账号不存在,请先注册! \nLogin user not exist, please register first!";
                        alertMsg.Style[HtmlTextWriterStyle.Display] = "";
                        alertMsg.InnerText = msg;
                        return;
                    }

                    //验证域密码
                    if (user != null)
                    {
                        domainUser = new UserBasicInfo(user);
                    }
                    if (user == null || false == Business.AppSettings.DebugRun)
                    {
                        domainUser = new ActiveDirectoryHelper().GetDomainUser(ad, pwd, out msg);
                        if (domainUser == null)
                        {
                            alertMsg.Style[HtmlTextWriterStyle.Display] = "";
                            alertMsg.InnerText = msg;
                            return;
                        }
                        if (user != null)
                        {
                            domainUser = new UserBasicInfo(user);
                        }
                        // 更新用户邮箱
                        if (user != null && string.IsNullOrEmpty(domainUser.Email) == false &&
                            domainUser.Email != user.Email)
                        {
                            user.Email = domainUser.Email;
                            using (FavLinkEntities context = new FavLinkEntities())
                            {
                                context.ObjectStateManager.ChangeObjectState(user, System.Data.EntityState.Modified);
                                context.SaveChanges();
                            }
                        }
                    }
                    // 帐号被停用
                    if (!user.IsValid)
                    {
                        msg = "账号已被停用. Your account was disabled.";
                        alertMsg.Style[HtmlTextWriterStyle.Display] = "";
                        alertMsg.InnerText = msg;
                        return;
                    }
                }
                else
                {
                    domainUser = UserState.GetLoginUser();
                }
                UserState.Login(domainUser);
                Common.UpdateUserLoginTimeByAd(ad);
                if (!string.IsNullOrEmpty(ReUrl))
                {
                    Response.Redirect(ReUrl);
                }
                else
                {
                    Response.Redirect(ResolveUrl("~/Default.aspx"));
                }
            } catch (Exception ex) {
                alertMsg.Style[HtmlTextWriterStyle.Display] = "";
                alertMsg.InnerText = ex.Message;
            }
        }
Ejemplo n.º 21
0
        public override void RunAllTests()
        {
            //init all loop variables
            string oldServiceURL;
            string oldServiceXMLOutput;

            string errorType    = string.Empty;
            string errorMessage = string.Empty;

            OldIdList = new DatabaseFacade().ConnectToDataSourceAndRetrieveOldIds("a30");

            var singleProfileWatch   = new Stopwatch();
            var testingDurationWatch = new Stopwatch();
            var oldServiceDataWatch  = new Stopwatch();
            var newServiceDataWatch  = new Stopwatch();

            testingDurationWatch.Start();

            LogManager.Instance.StartWritingReports();

            if (TestSuiteUser.IsDebugMode)
            {
                OldIdList = new HashSet <int>()
                {
                    12386392, 12789020, 10254830, 10345899, 10643722, 10356439, 13087115, 10098855, 10445859, 12445467, 10044421, 11842460, 10273683, 11228709, 12528002, 10410346, 10071485, 10934133, 12149599, 12641341, 10151776, 10290564, 11091604, 11472557, 12149599, 13132301, 10146455, 13157019, 10646102, 12192949, 10106216, 12268225, 11161032, 11832447, 11436806, 10736848
                };
            }

            bool keepGoing = true;

            //loop on the list of all OldIds retrieved from the old database
            foreach (int OldId in OldIdList)
            //Parallel.ForEach(OldIdList, OldId =>
            {
                if (keepGoing)
                {
                    oldServiceXMLOutput = string.Empty;

                    System.Diagnostics.Debug.WriteLine(OldId);
                    System.Console.Out.WriteLine(OldId);

                    LogManager.Instance.StatsCountTotalOldIds++;

                    if (false && LogManager.Instance.StatsCountTotalOldIds > 1000)
                    {
                        keepGoing = false;
                    }


                    singleProfileWatch.Start();

                    if (LogManager.Instance.StatsCountTotalOldIds % MaxProfilesForOneFile == 0)
                    {
                        // change to next output files
                        LogManager.Instance.StartWritingReports();
                    }

                    //go to the old service and retrieve the data
                    oldServiceURL = this.BuildOldServiceFullURL(OldId);

                    //Find a way to set the 'Timeout' property in Milliseconds. The old service can be slow.
                    //we also need exception handling!
                    oldServiceDataWatch.Start();
                    try
                    {
                        using (var webClient = new TimeoutExtendedWebClient())
                        {
                            try
                            {
                                webClient.Encoding  = System.Text.Encoding.UTF8;
                                oldServiceXMLOutput = webClient.DownloadString(oldServiceURL);
                            }
                            catch (WebException we)
                            {
                                System.Diagnostics.Debug.WriteLine(we.StackTrace);
                                System.Diagnostics.Debug.WriteLine("Trying to get data from old service for OldId " + OldId + " again");

                                try
                                {
                                    oldServiceXMLOutput = webClient.DownloadString(oldServiceURL);
                                }
                                catch (WebException we2)
                                {
                                    System.Diagnostics.Debug.WriteLine(we2.StackTrace);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e.StackTrace);
                        System.Diagnostics.Debug.WriteLine("Some inactive profiles do not have the flag set in the old service. Likely to be the case here.");
                    }
                    oldServiceDataWatch.Stop();

                    var allTheTests   = new HashSet <TestUnit>();
                    var allTheResults = new HashSet <ResultReport>();

                    XDocument oldServiceXMLOutputDocument = null;
                    IEnumerable <XElement> oldData        = null;
                    UserBasicInfo          newDataBasic   = null;
                    UserCompleteInfo       newData        = null;
                    string pageName = string.Empty;
                    int    userId;

                    if (!string.IsNullOrEmpty(oldServiceXMLOutput))
                    {
                        try
                        {
                            oldServiceXMLOutputDocument = XDocument.Parse(oldServiceXMLOutput);
                            oldData = oldServiceXMLOutputDocument.XPathSelectElements("/Faculty/facultyMember/*");

                            var rootDepthOnly = ParsingHelper.ParseListNodesOnlySameDepth(oldData, null);
                            //}
                            //catch (Exception e)
                            //{
                            //    System.Diagnostics.Debug.WriteLine(e.StackTrace);
                            //}

                            //try
                            //{

                            bool isInactive = false;

                            // there is a third state : "Read-Only", not used for the moment
                            isInactive = (ParsingHelper.ParseSingleValue(oldData, "Inactive") == "Yes");

                            if (!isInactive)
                            {
                                TestUnit testUnit;
                                IEnumerable <XElement> oldDataSubset = null;
                                var usersClient = new UsersClient();

                                newServiceDataWatch.Start();

                                newDataBasic = usersClient.GetUserByOldId(OldId);

                                newServiceDataWatch.Stop();

                                userId   = newDataBasic.UserId;
                                pageName = newDataBasic.PageName;

                                // This service has to be called first because it will provided the User ID mapped to the OldId for the next calls.
                                oldDataSubset = rootDepthOnly;
                                testUnit      = new TestUnitUserBasicInfo(this, newDataBasic);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    -1,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                newServiceDataWatch.Start();

                                newData = usersClient.GetUserCompleteByPageName(pageName);

                                newServiceDataWatch.Stop();

                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.title.ToString(), new List <XElement>(rootDepthOnly));
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.cv.ToString(), new List <XElement>(oldDataSubset));
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.language.ToString(), new List <XElement>(oldDataSubset));
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.department.ToString(), new List <XElement>(oldDataSubset));
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.treeDepartments.ToString(), new List <XElement>(oldDataSubset));
                                testUnit      = new TestUnitUserGeneralInfo(this, newData);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    userId,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.assistant.ToString());
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.labWebsite.ToString(), new List <XElement>(oldDataSubset));
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.location.ToString(), new List <XElement>(oldDataSubset));
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.mailing.ToString(), new List <XElement>(oldDataSubset), true);
                                testUnit      = new TestUnitUserContactLocationInfo(this, newData.LabWebsites, newData.UserAddresses);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    userId,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.featuredPublication.ToString());
                                testUnit      = new TestUnitUserPublicationInfo(this, newData.UserPublications);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    userId,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.researchSummary.ToString());
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.researchOverview.ToString(), new List <XElement>(oldDataSubset));
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.publicHealthKeywords.ToString(), new List <XElement>(oldDataSubset));
                                testUnit      = new TestUnitUserResearchInfo(this, newData.Research);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    userId,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.education.ToString());
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.training.ToString(), new List <XElement>(oldDataSubset));
                                testUnit      = new TestUnitUserEducationTrainingInfo(this, newData.Educations, newData.Trainings);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    userId,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.professionalHonor.ToString());
                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.professionalService.ToString(), new List <XElement>(oldDataSubset));
                                testUnit      = new TestUnitUserHonorServiceInfo(this, newData.Honors, newData.Services);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    userId,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.boardCertification.ToString(), new List <XElement>(rootDepthOnly));
                                testUnit      = new TestUnitUserPatientCareInfo(this, newData.BoardCertifications, newData.PatientCare);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    userId,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                oldDataSubset = ParsingHelper.ParseListNodes(oldData, EnumOldServiceFieldsAsKeys.treeDepartments.ToString());
                                testUnit      = new TestUnitUserOrganization(this, newData.OrganizationsTree);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    userId,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                oldDataSubset = rootDepthOnly;
                                testUnit      = new TestUnitUserGeneralContact(this, newData.GeneralContact);
                                allTheTests.Add(testUnit);
                                testUnit.ProvideData(
                                    OldId,
                                    oldDataSubset,
                                    userId,
                                    pageName);
                                testUnit.RunAllTests();
                                oldDataSubset = null;

                                foreach (var test in allTheTests)
                                {
                                    test.ComputerOverallResults();
                                    allTheResults.UnionWith(test.DetailedResults.Values);

                                    // log only first occurence of error - enough to generate the warning
                                    if ((test.HttpErrorHappened || test.UnknownErrorHappened) && string.IsNullOrEmpty(errorMessage))
                                    {
                                        errorMessage = test.ErrorMessage;

                                        if (test.HttpErrorHappened)
                                        {
                                            errorType = "HTTP";
                                        }
                                        else
                                        {
                                            errorType = "UNKNOWN";
                                        }
                                    }
                                }
                            }
                            else
                            {
                                LogManager.Instance.StatsCountProfilesIgnored++;
                            }
                        }
                        catch (Exception e)
                        {
                            System.Console.WriteLine(e.StackTrace);
                            System.Diagnostics.Debug.WriteLine(e.StackTrace);
                            System.Console.WriteLine(e.InnerException);
                            System.Diagnostics.Debug.WriteLine(e.InnerException);
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("No data returned by old service for OldId " + OldId);
                        System.Console.Out.WriteLine("No data returned by old service for OldId " + OldId);
                    }

                    singleProfileWatch.Stop();

                    LogManager.Instance.LogProfileResult(OldId, allTheResults, singleProfileWatch.Elapsed, oldServiceDataWatch.Elapsed, newServiceDataWatch.Elapsed);

                    singleProfileWatch.Reset();
                    oldServiceDataWatch.Reset();
                    newServiceDataWatch.Reset();
                }
            }
            testingDurationWatch.Stop();

            LogManager.Instance.LogSummary(testingDurationWatch.Elapsed, errorType, errorMessage);

            LogManager.Instance.Dispose();
        }
Ejemplo n.º 22
0
        public ActionResult Signin(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            string ad  = model.Username;
            string pwd = model.Password;
            string msg = "";

            //CacheFactory.ClearCache(); //TODO remove

            try
            {
                UserBasicInfo domainUser = null;
                if (!CommonInfo.IsLogin())
                {
                    var user = SysUserInfo.GetUserInfoByAd(ad);
                    if (user == null)
                    {
                        msg = "账号不存在,请先注册! Login user not exist, please register first!";
                        ModelState.AddModelError("", msg);
                        return(View());
                    }

                    //验证域密码
                    if (user != null)
                    {
                        domainUser = new UserBasicInfo(user.id, user.ADAccount, user.Email, user.FullName, user.IsAdmin);
                    }
                    if (user == null /*|| false == ConfigInfo.DebugRun*/)
                    {
                        domainUser = new ActiveDirectoryHelper().GetDomainUser(ad, pwd, out msg);
                        if (domainUser == null)
                        {
                            ModelState.AddModelError("", msg);
                            return(View());
                        }
                        if (user != null)
                        {
                            domainUser = new UserBasicInfo(user.id, user.ADAccount, user.Email, user.FullName, user.IsAdmin);
                        }
                        // 更新用户邮箱
                        if (user != null && string.IsNullOrEmpty(domainUser.Email) == false &&
                            domainUser.Email != user.Email)
                        {
                            user.Email = domainUser.Email;
                            SysUserInfo.Update(user);
                        }
                    }
                    // 帐号被停用
                    if (!user.IsValid)
                    {
                        msg = "账号已被停用. Your account was disabled.";
                        ModelState.AddModelError("", msg);
                        return(View());
                    }
                }
                else
                {
                    domainUser = CommonInfo.CurrentUser;
                }
                CommonInfo.Login(domainUser);
                SysUserInfo.UpdateUserLoginTimeByAd(ad);
                return(RedirectToLocal(model.ReturnUrl));
            }
            catch (Exception ex)
            {
                LogHelper.WriteError(this.GetType(), ex);
                ModelState.AddModelError("", ex);
                return(View());
            }
        }
Ejemplo n.º 23
0
        internal static void Login(UserBasicInfo domainUser)
        {
            var vUserState = UserState.GetInstance(_cook);

            vUserState.Login(domainUser);
        }
Ejemplo n.º 24
0
        public static void Trigger(Object stateInfo)
        {
            try
            {
                if (emailNotifierIsProcessing)
                {
                    return;
                }
                emailNotifierIsProcessing = true;
                Logger.Current.Verbose("WebVisitEmailNotifier triggered");


                Logger.Current.Verbose("Getting visits");

                GetCurrentWebVisitNotificationsResponse webVisitsToBeNotified = webAnalyticsService.GetCurrentWebVistNotifications(new GetCurrentWebVisitNotificationsRequest());
                Logger.Current.Informational("WebVisitsToBeNotified Count" + webVisitsToBeNotified.CurrentVisits.Count());

                var accounts = webVisitsToBeNotified.CurrentVisits.Select(c => c.AccountId).ToList().Distinct();

                var emailResults = new List <KeyValuePair <IEnumerable <string>, string> >();
                var failedEmails = new List <KeyValuePair <IEnumerable <string>, string> >();

                foreach (int accountId in accounts)
                {
                    var userIds = webVisitsToBeNotified.CurrentVisits
                                  .Where(c => c.AccountId == accountId)
                                  .Select(c => c.OwnerID).Distinct().ToList();
                    if (userIds.IsAny())
                    {
                        Dictionary <Guid, string> emailProvider   = accountService.GetTransactionalProviderDetails(accountId);
                        GetDropdownValueResponse  lifeCycleStages = dropdownService.GetDropdownValue(new GetDropdownValueRequest()
                        {
                            AccountId = accountId, DropdownID = (byte)DropdownFieldTypes.LifeCycle
                        });

                        IEnumerable <UserBasicInfo> optedUsers
                            = userService.GetUsersOptedInstantWebVisitEmail(new GetUsersOptedInstantWebVisitEmailRequest()
                        {
                            AccountId = accountId
                        }).Users;


                        List <UserBasicInfo> owners = userService.GetUsersByUserIDs(new GetUsersByUserIDsRequest()
                        {
                            UserIDs = userIds
                        }).Users.ToList();
                        //add empty owner
                        var eo = new UserBasicInfo()
                        {
                            UserID = 0,
                            Email  = defaultEmail
                        };
                        if (!owners.Any(f => f.Email == defaultEmail))
                        {
                            owners.Add(eo);
                        }



                        var account = accountRepository.GetAccountBasicDetails(accountId);
                        if (account.Status != (byte)AccountStatus.Suspend)
                        {
                            #region == Send email to each user ==
                            //is account subscribed
                            var providerResponse = accountService.GetAccountWebAnalyticsProviders(new GetWebAnalyticsProvidersRequest()
                            {
                                AccountId = accountId
                            });

                            WebAnalyticsProvider provider = providerResponse.WebAnalyticsProviders.FirstOrDefault();

                            foreach (var owner in owners)
                            {
                                IEnumerable <WebVisitReport> relatedVisits = null;
                                if (owner.Email == defaultEmail)
                                {
                                    relatedVisits   = webVisitsToBeNotified.CurrentVisits.Where(c => c.AccountId == accountId && c.OwnerID == null).OrderByDescending(c => c.VisitedOn).ToList();
                                    owner.FirstName = "Not";
                                    owner.LastName  = "Assigned";
                                    owner.TimeZone  = account.TimeZone;
                                }
                                else
                                {
                                    relatedVisits = webVisitsToBeNotified.CurrentVisits.Where(c => c.AccountId == accountId && c.OwnerID == owner.UserID).OrderByDescending(c => c.VisitedOn).ToList();
                                }

                                if (relatedVisits.IsAny())
                                {
                                    try
                                    {
                                        if (provider.NotificationStatus)
                                        {
                                            //when owner is default user or un assigned, email will not be sent to owner.
                                            NotifyByEmail(accountId, relatedVisits, owner, "SmartTouch Current Web Visit Alert", lifeCycleStages, emailProvider, owner.Email);
                                        }
                                        foreach (var optedUser in optedUsers)
                                        {
                                            try
                                            {
                                                NotifyByEmail(accountId, relatedVisits, owner, "SmartTouch Current Web Visit Alert (Admin)", lifeCycleStages, emailProvider, optedUser.Email);
                                            }
                                            catch (Exception ex)
                                            {
                                                ex.Data.Clear();
                                                ex.Data.Add("Copy User", optedUser.UserID);
                                                Logger.Current.Error("Unable to send web visit email to user: "******", email: " + optedUser.Email, ex);
                                            }
                                        }
                                        emailResults.Add(new KeyValuePair <IEnumerable <string>, string>(relatedVisits.Select(c => c.VisitReference).ToList(), "Success"));
                                    }
                                    catch (Exception ex)
                                    {
                                        ex.Data.Clear();
                                        ex.Data.Add("Copy User", owner.UserID);
                                        Logger.Current.Error("Unable to send web visit email to user: "******"Failed"));
                                    }
                                }
                            }
                            #endregion
                        }
                        emailResults.AddRange(failedEmails);
                    }
                }

                #region == Update Audits ==
                if (emailResults != null && emailResults.Any())
                {
                    webAnalyticsService.UpdateWebVisitNotifications(new UpdateWebVisitNotificationsRequest()
                    {
                        VisitReferences = emailResults
                    });
                }
                #endregion

                emailNotifierIsProcessing = false;
            }

            catch (Exception ex)
            {
                emailNotifierIsProcessing = false;
                Logger.Current.Error("Exception occured in Email Notifier.", ex);
            }

            finally
            {
                //emailNotifierIsProcessing = false;
            }
        }
Ejemplo n.º 25
0
        private static void NotifyByEmail(int accountId, IEnumerable <WebVisitReport> relatedVisits, UserBasicInfo owner, string subject,
                                          GetDropdownValueResponse lifeCycleStages, Dictionary <Guid, string> emailProvider, string to)
        {
            Logger.Current.Verbose("Distinct UserId: " + owner.UserID);
            Logger.Current.Verbose("Distinct User name: " + owner.FirstName + " " + owner.LastName);
            relatedVisits.Each(c =>
            {
                TimeZoneInfo tzInfo = TimeZoneInfo.FindSystemTimeZoneById(owner.TimeZone);
                c.VisitedOnUTZ      = TimeZoneInfo.ConvertTimeFromUtc(c.VisitedOn, tzInfo);
                c.LifecycleStage    = lifeCycleStages.DropdownValues.DropdownValuesList.Where(d => d.DropdownValueID == c.LifecycleStageId).Select(d => d.DropdownValue).FirstOrDefault() ?? "";
            });
            Logger.Current.Verbose("Sending notification email to userId:" + owner.UserID);
            var emailContent = relatedVisits.GetTable(p => p.FirstName
                                                      , p => p.LastName
                                                      , p => p.Email
                                                      , p => p.Phone
                                                      , p => p.Zip
                                                      , p => p.LifecycleStage
                                                      , p => p.VisitedOnUTZ
                                                      , p => p.PageViews
                                                      , p => p.Duration
                                                      , p => p.Page1
                                                      , p => p.Page2
                                                      , p => p.Page3
                                                      , p => p.Source
                                                      , p => p.LeadScore
                                                      , p => p.Location);
            var ownerName   = owner.FirstName + " " + owner.LastName;
            var accountName = relatedVisits.First().AccountName;
            //var accountLabel = "<label style='font-family:arial,sans-serif'>Account: <strong>  " + accountName + " </strong> <br></label>";

            var visitReference = relatedVisits.Select(c => c.VisitReference).FirstOrDefault();

            if (!string.IsNullOrEmpty(to) && to != defaultEmail)
            {
                Logger.Current.Verbose("Sending 1 mail to " + to);
                var subjectLine = subject + " - " + accountName;
                emailContent = "<div style='font-family:arial,sans-serif;font-size:12px'><label>Account: <strong style='font-family:arial,sans-serif'>  " + accountName
                               + "<br></strong> Account Executive: <strong>" + ownerName + "</strong><br><br></label>" + emailContent
                               + ((relatedVisits != null && relatedVisits.Any()) ? "<div style='font-family:arial,sans-serif;font-size:12px'><label>Above timestamps are according to " + owner.TimeZone + "<br></div>" : "")
                               + "</div>";

                SendMailRequest emailRequest = new SendMailRequest();
                if (emailProvider != null && emailProvider.Count > 0)
                {
                    var fromEmailId = !string.IsNullOrEmpty(emailProvider.FirstOrDefault().Value) ? emailProvider.FirstOrDefault().Value : "*****@*****.**";
                    emailRequest.TokenGuid     = emailProvider.FirstOrDefault().Key;
                    emailRequest.RequestGuid   = Guid.NewGuid();
                    emailRequest.ScheduledTime = DateTime.Now.AddMinutes(1).ToUniversalTime();
                    emailRequest.Subject       = subjectLine;
                    emailRequest.Body          = GenerateEmailBody(emailContent, accountId);
                    emailRequest.To            = new List <string>()
                    {
                        to
                    };
                    emailRequest.IsBodyHtml = true;
                    emailRequest.From       = fromEmailId;
                    emailRequest.CategoryID = (short)EmailNotificationsCategory.WebVisitInstantNotification;
                    emailRequest.AccountID  = accountId;
                    var sendMailResponse = mailService.Send(emailRequest);
                }
                Logger.Current.Informational("Successfully sent web visit notification: " + visitReference + ". To user: " + to);
            }
        }
Ejemplo n.º 26
0
        public ActionResult Signin(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            string ad  = model.Username;
            string pwd = model.Password;
            string msg = "";

            try
            {
                UserBasicInfo domainUser = null;
                if ("guest".Equals(ad, StringComparison.InvariantCultureIgnoreCase))
                {
                    //特殊帐号
                    var user = SysUserInfo.GetUserInfoByAd("guest");
                    domainUser = new UserBasicInfo(user.id, user.FullName, user.Email, user.FullName, user.IsAdmin);
                }
                else if (!CommonInfo.IsLogin())
                {
                    var user = SysUserInfo.GetUserInfoByAd(ad);
                    if (user == null)
                    {
                        msg = "账号不存在,请先注册! Login user not exist, please register first!";
                        ModelState.AddModelError("", msg);
                        return(View());
                    }

                    //验证域密码
                    domainUser = new ActiveDirectoryHelper().GetDomainUser(ad, pwd, out msg);
//true for debug only
#if false
                    domainUser = new UserBasicInfo(user.id, user.ADAccount, user.Email, user.FullName, user.IsAdmin);
#endif

                    if (domainUser == null)
                    {
                        ModelState.AddModelError("", msg);
                        return(View());
                    }

                    domainUser.UserID  = user.id;
                    domainUser.IsAdmin = user.IsAdmin;
                    // 更新用户邮箱
                    if (!string.IsNullOrEmpty(domainUser.Email) &&
                        0 != string.Compare(domainUser.Email, user.Email, true)
                        )
                    {
                        user.Email = domainUser.Email;
                        SysUserInfo.Update(user);
                    }

                    // 帐号被停用
                    if (!user.IsValid)
                    {
                        msg = "账号已被停用. Your account was disabled.";
                        ModelState.AddModelError("", msg);
                        return(View());
                    }
                }
                else
                {
                    domainUser = CommonInfo.CurrentUser;
                }
                CommonInfo.Login(domainUser);
                SysUserInfo.UpdateUserLoginTimeByAd(ad);
                return(RedirectToLocal(model.ReturnUrl));
            }
            catch (Exception ex)
            {
                LogHelper.WriteError(this.GetType(), ex);
                ModelState.AddModelError("", ex);
                return(View());
            }
        }
 public TestUnitUserBasicInfo(TestSuite parent, UserBasicInfo newData) : base(parent)
 {
     this.newData = newData;
 }
        private void NotifyByEmail(Account accountInfo, List <WebVisitReport> relatedVisits, UserBasicInfo owner, string subject,
                                   GetDropdownValueResponse lifeCycleStages, Dictionary <Guid, string> emailProvider, string to)
        {
            Log.Verbose("Distinct UserId: " + owner.UserID + " distinct User name: " + owner.FirstName + " " + owner.LastName);

            var emailContent = GetEmailContent(owner, relatedVisits, lifeCycleStages);
            var accountName  = relatedVisits.First().AccountName;

            var visitReference = relatedVisits.Select(c => c.VisitReference).FirstOrDefault();

            if (string.IsNullOrEmpty(to) || to == DefaultEmail)
            {
                return;
            }

            var subjectLine = subject + " - " + accountName;

            emailContent = "<div style='font-family:arial,sans-serif;font-size:12px'><label>Account: <strong style='font-family:arial,sans-serif'>  " + accountName
                           + "<br></strong> Account Executive: <strong>" + owner.FullName + "</strong><br><br></label>" + emailContent
                           + (relatedVisits.Any() ? "<div style='font-family:arial,sans-serif;font-size:12px'><label>Above timestamps are according to " + owner.TimeZone + "<br></div>" : "")
                           + "</div>";

            if (!(emailProvider?.Any() ?? false))
            {
                return;
            }

            var fromEmailId  = !string.IsNullOrEmpty(emailProvider.FirstOrDefault().Value) ? emailProvider.FirstOrDefault().Value : "*****@*****.**";
            var emailRequest = new SendMailRequest
            {
                TokenGuid     = emailProvider.FirstOrDefault().Key,
                RequestGuid   = Guid.NewGuid(),
                ScheduledTime = DateTime.UtcNow.NextMinute(),
                Subject       = subjectLine,
                Body          = GenerateEmailBody(emailContent, accountInfo.AccountID),
                To            = new List <string> {
                    to
                },
                IsBodyHtml = true,
                From       = fromEmailId,
                CategoryID = (short)EmailNotificationsCategory.WebVisitInstantNotification,
                AccountID  = accountInfo.AccountID
            };

            _mailService.Send(emailRequest);
            Log.Informational("Successfully sent web visit notification: " + visitReference + ". To user: " + to);
        }
        protected override void ExecuteInternal(IJobExecutionContext context)
        {
            var webVisitsToBeNotified = _webAnalyticsService.GetCurrentWebVistNotifications(new GetCurrentWebVisitNotificationsRequest());
            var accountIds            = webVisitsToBeNotified
                                        .CurrentVisits
                                        .Select(c => c.AccountId)
                                        .Distinct()
                                        .ToArray();

            var emailResults = new List <KeyValuePair <IEnumerable <string>, string> >();

            foreach (var accountId in accountIds)
            {
                var accountInfo = _accountRepository.GetAccountBasicDetails(accountId);
                if (accountInfo.Status == (byte)AccountStatus.Suspend)
                {
                    continue;
                }

                Log.Informational($"Process Real-Time Alerts for AccountID: {accountId}");

                var userIds = webVisitsToBeNotified.CurrentVisits
                              .Where(c => c.AccountId == accountId)
                              .Select(c => c.OwnerID)
                              .Distinct()
                              .ToArray();

                if (!userIds.IsAny())
                {
                    continue;
                }

                var emailProvider   = _accountService.GetTransactionalProviderDetails(accountId);
                var lifeCycleStages = _dropdownService.GetDropdownValue(new GetDropdownValueRequest {
                    AccountId = accountId, DropdownID = (byte)DropdownFieldTypes.LifeCycle
                });

                var usersToNotify = _userService.GetUsersOptedInstantWebVisitEmail(new GetUsersOptedInstantWebVisitEmailRequest {
                    AccountId = accountId
                })
                                    .Users
                                    .ToArray();
                var ownersToNotify = _userService.GetUsersByUserIDs(new GetUsersByUserIDsRequest {
                    UserIDs = userIds
                })
                                     .Users
                                     .ToList();

                //add empty owner
                var emptyOwner = new UserBasicInfo
                {
                    UserID = 0,
                    Email  = DefaultEmail
                };
                if (ownersToNotify.All(f => f.Email != DefaultEmail))
                {
                    ownersToNotify.Add(emptyOwner);
                }

                //is account subscribed
                var provider = _accountService.GetAccountWebAnalyticsProviders(
                    new GetWebAnalyticsProvidersRequest
                {
                    AccountId = accountId
                }).WebAnalyticsProviders.First();

                foreach (var owner in ownersToNotify)
                {
                    List <WebVisitReport> relatedVisits;
                    if (owner.Email == DefaultEmail)
                    {
                        relatedVisits = webVisitsToBeNotified.CurrentVisits
                                        .Where(c => c.AccountId == accountId && c.OwnerID == null)
                                        .OrderByDescending(c => c.VisitedOn)
                                        .ToList();
                        owner.FirstName = "Not";
                        owner.LastName  = "Assigned";
                        owner.TimeZone  = accountInfo.TimeZone;
                    }
                    else
                    {
                        relatedVisits = webVisitsToBeNotified.CurrentVisits
                                        .Where(c => c.AccountId == accountId && c.OwnerID == owner.UserID)
                                        .OrderByDescending(c => c.VisitedOn)
                                        .ToList();
                    }

                    if (!relatedVisits.IsAny())
                    {
                        continue;
                    }

                    try
                    {
                        if (provider.NotificationStatus)
                        {
                            //when owner is default user or unassigned, email will not be sent to owner.
                            NotifyByEmail(accountInfo, relatedVisits, owner, "SmartTouch Current Web Visit Alert",
                                          lifeCycleStages, emailProvider, owner.Email);
                        }
                        foreach (var user in usersToNotify)
                        {
                            try
                            {
                                NotifyByEmail(accountInfo, relatedVisits, owner,
                                              "SmartTouch Current Web Visit Alert (Admin)", lifeCycleStages,
                                              emailProvider, user.Email);
                            }
                            catch (Exception ex)
                            {
                                Log.Error("Unable to send web visit email to user: "******", email: " + user.Email, ex);
                            }
                        }
                        emailResults.Add(
                            new KeyValuePair <IEnumerable <string>, string>(
                                relatedVisits.Select(c => c.VisitReference).ToList(), "Success"));
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Unable to send web visit email to user: "******"Failed"));
                    }
                }
            }

            if (emailResults.Any())
            {
                _webAnalyticsService.UpdateWebVisitNotifications(new UpdateWebVisitNotificationsRequest {
                    VisitReferences = emailResults
                });
            }

            Log.Informational("Completed processing Real-Time Alerts");
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 创建 <see cref="UserLevel"/>
        /// </summary>
        /// <param name="currentUserId">当前登录用户 ID</param>
        /// <param name="userIdCode">用户识别码</param>
        /// <param name="targetPage">要获取的页面</param>
        /// <param name="dbContext"><see cref="KeylolDbContext"/></param>
        /// <param name="cachedData"><see cref="CachedDataProvider"/></param>
        /// <param name="userManager"><see cref="KeylolUserManager"/></param>
        /// <returns><see cref="UserLevel"/></returns>
        public static async Task <UserLevel> CreateAsync(string currentUserId, string userIdCode, EntrancePage targetPage,
                                                         KeylolDbContext dbContext, CachedDataProvider cachedData, KeylolUserManager userManager)
        {
            var user = await userManager.FindByIdCodeAsync(userIdCode);

            if (user == null)
            {
                return(new UserLevel());
            }
            var result = new UserLevel
            {
                BasicInfo = await UserBasicInfo.CreateAsync(currentUserId, user, dbContext, cachedData, userManager)
            };

            switch (targetPage)
            {
            case EntrancePage.Auto:
//                    if (await cachedData.Subscriptions
//                        .IsSubscribedAsync(currentUserId, user.Id, SubscriptionTargetType.User))
//                    {
//                        result.Current = EntrancePage.Timeline;
//                    }
//                    else
//                    {
//                        result.Dossier =
//                            await DossierPage.CreateAsync(user, currentUserId, dbContext, cachedData, userManager);
//                        result.Current = EntrancePage.Dossier;
//                    }
                result.Dossier =
                    await DossierPage.CreateAsync(user, currentUserId, dbContext, cachedData, userManager);

                result.Current = EntrancePage.Dossier;
                break;

            case EntrancePage.Dossier:
                result.Dossier =
                    await DossierPage.CreateAsync(user, currentUserId, dbContext, cachedData, userManager);

                break;

            case EntrancePage.People:
                result.People = await PeoplePage.CreateAsync(user.Id, currentUserId, dbContext, cachedData);

                break;

            case EntrancePage.Timeline:
                result.Timeline = await TimelinePage.CreateAsync(user.Id, currentUserId, dbContext, cachedData);

                break;

            case EntrancePage.Edit:
                if (await StateTreeHelper.CanAccessAsync <UserLevel>(nameof(Edit)))
                {
                    result.Edit = await EditPage.CreateAsync(user, currentUserId, dbContext, userManager);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(targetPage), targetPage, null);
            }
            return(result);
        }