如何监控主窗体

在项目中我们总是的关注当某个用户在登陆后,如果有相同的用户也登陆则会出错,有时session会不无故丢失,有时控制用户在有效的时间段内才能运行或者控制注销等操作时,我们可以把监控窗体和主窗体分开。监测窗体主要控制上述功能。
在登陆窗体进行时间的检测。没有有效的登陆时间则不允许登陆
 public partial class Login : PageBase
    {
        private string user;
        private string pwd;
        private int uid;

        protected void Redirect(string rawUrl)
        {
            InitWebConsoleContext();
            if (!string.IsNullOrEmpty(rawUrl))
                this.Response.Redirect(rawUrl);
            else
                Response.Redirect("~/Main.aspx?NMS=Local", true);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SetFocus(UserName);
            AppTitle.Text = "";
            this.Title =  System.Configuration.ConfigurationSettings.AppSettings["AppTitle"];
     
                Dictionary<string, string> context = new Dictionary<string, string>( StringComparer.CurrentCultureIgnoreCase );
                if (((ISSOAuthentication)Services.GetService(typeof(ISSOAuthentication))).Authenticate(this, context))
                {
                    context.TryGetValue("user", out user );
                    context.TryGetValue("pwd",out pwd);
                    string uid_string;
                    if (context.TryGetValue("uid", out uid_string))
                        uid = int.Parse(uid_string);
     
                    Redirect(this.Request["ReturnUrl"]);
                    return;
                }                   
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            user = this.UserName.Text;
            pwd = this.Password.Text;
          
            WebAuthentication auth = (WebAuthentication)Services.GetService(typeof(WebAuthentication));
            try
            {
                uid = auth.SignIn(user, pwd);

                if (uid >= 0)
                {
                        if (IsLoginTime(user))
                      {
                             Redirect(this.Request["ReturnUrl"]);
                       }
                      else
                        {
                             this.lblError.Text = (string)this.GetLocalResourceObject("InvalidLoginTime");
                         }
                }
                else
                {
                    this.FailureText.Visible = true;
                    this.FailureText.Text = (string)this.GetLocalResourceObject("InvalidUserOrPwd");
                }
            }
            catch (Exception se)
            {
                this.lblError.Text = se.Message;
            }           
        }

  //确定时间是否在允许的范围  
  private bool IsLoginTime(string userName)
  {
   IRepository Repository = (IRepository)Services.GetService(typeof(IRepository));
   IUserRestriction ur = Repository.GetUserRestriction(userName, "UserLoginTime");
   DateTime timeNow = DateTime.Now;
   if (ur != null)
   {
    string strRes = ur.Restriction;
    if (strRes == "")
     return true;
    string[] strDate = strRes.Split(',');
    foreach (string s in strDate)
    {
     string[] date = s.Split(new string[] { "---"},System.StringSplitOptions.RemoveEmptyEntries);
     DateTime TimeOne = DateTime.Parse(date[0]);
     DateTime TimeTwo = DateTime.Parse(date[1]);
     if (timeNow >= TimeOne && timeNow <= TimeTwo)
     {
      return true;
     }
    }
    return false;
   }
   return true;
  }

建一个监测窗体( main.aspx)
public partial class Main : System.Web.UI.Page
{
    string nms;
    protected void Page_Load(object sender, EventArgs e)
    {       
            nms = Request["NMS"];
            Nms.Value = Request["NMS"];
            this.Title = System.Configuration.ConfigurationSettings.AppSettings["AppTitle"];             
    } 
}

在脚本中写(main.js)
// JScript 文件

var win,win1
    function onloadme()
    {
        document.cookie
        window.name = "btnm4_startup";
        //window.resizeTo( 500,450);
        //window.moveTo( (window.screen.availWidth - 500 )/2,  (window.screen.availHeight- 450)/2)
       
        win = window.open("", "BtnmMainWindow_"+document.all.Nms.value, "status=no,toolbar=no,menubar=no");
        win.moveTo(0,0)
        win.resizeTo(  window.screen.availWidth , window.screen.availHeight);
       
        document.btim.submit();

        if( document.getElementById("show_btsm").value )
        {
            win1 = window.open("", "BtsmMainWindow_"+document.all.Nms.value, "status=no,toolbar=no,menubar=no");
            win1.moveTo(0,0)
            win1.resizeTo(  window.screen.availWidth , window.screen.availHeight);
           
            document.btsm.submit();
        }
       
        checkState();
    }
   
    function checkState()
    {
        CheckState.CheckRunState(document.all.Nms.value,checkStateCallback,checkStateError);
    }
   
    function checkStateCallback(result)
    {
        try
        {
            if(result.IsKicked && !result.IsUnRegistered)
            {
                win.close();
                alert(result.Message);
                window.location.href('logout.aspx');
            }
           
            if(result.IsUnRegistered && !result.IsKicked)
            {
                win.close();
                alert(result.Message);
                window.location.href('logout.aspx');
            }
           
            if(result.IsKicked && result.IsUnRegistered)
            {
                win.close();
                alert(result.Message);
                window.location.href('logout.aspx');
            }
           
            if(result.IsValidLoginTime)
            {
                win.close();
                alert(result.Message);
                window.location.href('logout.aspx');
            }
          
        }
        catch(ex)
        {}
   
        window.setTimeout("checkState()",10000);
    }
   
    function checkStateError(result)
    {
        window.setTimeout("checkState()",10000);
    }
    

创建一个webservice('webState.asmx')
<%@ WebService Language="C#" Class="CheckState" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Web.Services;
using System.Web.Services.Protocols;

using Betanetworks.Btnm.WebConsole.Shared;
using Betanetworks.Btnm.WebConsole.Framework;
using Betanetworks.Security.Permissions;
using Betanetworks.Btnm.Users;


[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class CheckState  : WebServiceBase {

    [WebMethod]
    public UserRunState CheckRunState(string nms)
    {
        string user = (string)WebConsoleContext.GetContextObj(nms, WebConsoleContext.USER_NAME);
       
       
        UserRunState urs = new UserRunState();
        HttpSessionState session = null;
       
        try
        {
            session = Betanetworks.Btnm.WebConsole.Shared.WebConsoleContext.GetCurrentSession();
            if (session == null)
                throw new Exception();
        }
        catch(Exception ex)
        {
            urs.IsKicked = true;
            urs.IsUnRegistered = true;
            //urs.Message = string.Format(Resources.CheckState.AppError, System.Environment.NewLine, ex.Message);
            urs.Message = Resources.CheckState.AppError;
            return urs;
        }

       
       
        object isOut = session["IsOut"];
        if (isOut != null && ((bool)isOut))
        {
            urs.IsKicked = true;
            urs.Message = Resources.CheckState.KickError;
        }

        object isRegistered = session["Betanetworks.IsUnRegister"];
        if (isRegistered != null && ((bool)isRegistered))
        {
            urs.IsKicked = true;
            urs.Message = Resources.CheckState.UnRegisterError;
        }
       
        //ISecurityRepository secRep = (ISecurityRepository)Services.GetService(typeof(ISecurityRepository));
        //IRole role = secRep.GetRoleByName(user);

      
            IRepository Repository = (IRepository)Services.GetService(typeof(IRepository));
            IUserRestriction ur = Repository.GetUserRestriction(user, "UserLoginTime");
            DateTime timeNow = DateTime.Now;
            string isTime = "";

            if (ur != null)
            {
                string strTime = ur.Restriction;
                if (strTime == "")
                {
                    isTime = "yes";
                    goto found;
                }
                string[] strDate = strTime.Split(',');

                for (int i = 0; i < strDate.Length; i++)
                {
                    string[] date = strDate[i].Split(new string[] { "---" }, System.StringSplitOptions.RemoveEmptyEntries);
                    DateTime TimeOne = DateTime.Parse(date[0]);
                    DateTime TimeTwo = DateTime.Parse(date[1]);
                    if (timeNow >= TimeOne && timeNow <= TimeTwo)
                    {
                        isTime = "yes";
                        goto found;    
                    }
                }
            }
            else
            {
                isTime = "yes";
            }
            found:
            if (isTime != "yes")
            {
                urs.IsValidLoginTime = true;
                urs.Message = Resources.CheckState.UserLoginTimeError;
            }

       
        return urs;
    }
   
}

      
[Serializable]
public class UserRunState
{
    #region
    private bool _isKicked;
    private bool _isUnRegistered;
    private bool _isValidLoginTime;

    public string _mesg = string.Empty;
    #endregion

    #region properties
    /// <summary>
    /// 表示是否已经被重复登录。
    /// </summary>
    public bool IsKicked
    {
        get { return _isKicked; }
        set
        {
            _isKicked = value;
        }
    }

    /// <summary>
    /// 表示是否已经被注销。
    /// </summary>
    public bool IsUnRegistered
    {
        get { return _isUnRegistered; }
        set
        {
            _isUnRegistered = value;
        }
    }
    ///<summary>
    ///表示当前是否处于有效的运行时间
    ///</summary>
    public bool IsValidLoginTime
    {
        get { return _isValidLoginTime; }
        set
        {
            _isValidLoginTime=value;
        }
    }

    /// <summary>
    /// 信息说明。
    /// </summary>
    public string Message
    {
        get { return _mesg; }
        set
        {
            _mesg = value;
        }
    }
    #endregion
}


   

posted @ 2007-06-22 13:12  无边落木  阅读(305)  评论(0编辑  收藏  举报