Lightweight road data CYQ.Data application example two layers Chat (VI)

Following Previous: CYQ.Data lightweight road data layer of gorgeous upgrade V1.3 born (e) herein, this weekend and take advantage of off-hours to see posted are not many people, let low-key shot application at:

Also in order to introduce a complete one example, I selected a streamlined look, this is an example: login + + registered online chat [whisper omitted part]

Before looking at an example of this article, please see: Road CYQ.Data lightweight data-tier application examples of articles (four)  - Because the registration + landing Since direct Copy of this section on the province before.

 

The current environment is also: VS2005 + SQL2005, enter the following topic:

A: Database

Named: Chat

Two tables: Users + Message, on the map:

Description: the previous example and comparison: Users table is the same, Message table almost the same.

 

Two: the initial project

1: New Web Site project , named as: Cyq.Data.ChatDemoProject

After adding webconfig also produced good database link!

2: Add a reference : CYQ.Data.dll

3: generate paging query and stored procedure to enumerate : or page: WriteOut.aspx, for generating an output:

The method of generating a new tab stored procedure: CYQ.Data lightweight data channel layers gorgeous upgrade V1.3 born (e) : [ . 9: outputData: a method for increasing the direct execution procedure ExeCreateProc generating paging store ]

 

Three: Project start:

First on the map, the overall project situation:

1: registered users (Login.aspx: see example chapter (d))

2: User login (Reg.aspx: see example chapter (d))

3: Online chat: (Default.aspx)

First on the map, the main chat interface:

Subregional Description:

1: left area of the chat display area
2: right and top to exit welcome
3: user list area to the right lower head
4: bottom of the message area is
5: ajax refresh timer built with 2.0 ICallBack interface.

 

 

The following code illustrates:

When the page came in, to be able to be loaded are loaded complete: only three points [1: Lander name; 2: user list; 3: Take 10 default message display]

1: Lander name and exit events

05233050_Wr7N.gif
     void  LoadMyInfo()
    {
        
if  (Session[ " ID " ==   null )
        {
            Response.Redirect(
" Login.aspx " );
        }
        
else
        {
            Session[
" ID " =  Session[ " ID " ];
            myID 
= Convert.ToInt32(Session[ " ID " ]);
            MAction action 
=   new  MAction(TableNames.Users);
            
if  (action.Fill(myID))
            {
                action.SetTo(labUserName);
            }
            
else
            {
                labUserName.Text 
=   " 读取数据失败! " ;
            }
            action.Close();
        }
    }
    
protected   void  btnLogout_Click( object  sender, EventArgs e)
    {
        Session[
" ID " =   null ;
        Response.Redirect(
" Login.aspx " );
    }

 

2与3:绑定用户列表与后十条留言

05233050_Wr7N.gif
     void  LoadListInfo()
    {
        
int  rowCount;
        MAction action 
=   new  MAction(TableNames.Users); // 加载用户列表
        rptUserList.DataSource  =  action.Select( 0 , 0 , " ID<> " + myID, out  rowCount);
        rptUserList.DataBind();
        
if  (action.ResetTable(CustomerSQL.Message)) // 切换表到留言列表,加载留言列表
        {
            rptMessageList.DataSource 
=  action.Select( 1 10 "" out  rowCount);
            rptMessageList.DataBind();
            action.Close();
        }
    }

 

上面又有一个自定义的CustomerSQL.Message,其实我应该用一下存储过程来演示的,算了,写都写了:

还是和上次演示一下,自定义语句放到类里统一管理了:

05233050_Wr7N.gif
///   <summary>
///  by 路过秋天  http://cyq1162.cnblogs.com/
///   </summary>
public   class  CustomerSQL
{
    
public   const   string  Message  =   " (SELECT m.*,uA.UserName,isnull(uB.UserName,'所有人') AS UserName2 FROM Message m LEFT JOIN Users uA ON m.SendUserID=uA.ID LEFT JOIN Users uB ON m.RecvUserID=uB.ID) v " ;
}

 

 

4:接下来是Ajax部分了

这里我封装了一下,新建了个PageBase类放里面了,看一下PageBase.cs代码:

05233050_Wr7N.gif
///   <summary>
///  路过秋天  http://cyq1162.cnblogs.com
///   </summary>
public   class  PageBase:System.Web.UI.Page,ICallbackEventHandler
{
    
#region  ICallbackEventHandler 成员
    
///   <summary>
    
///  Ajax方法时的回调结果
    
///   </summary>
     public   string  ajaxCallBackResult  =   null ;
    
///   <summary>
    
///  注册Ajax方法
    
///  调用方法名:callAjax(arg)
    
///  回调方法名:callBack(result)
    
///   </summary>
     public   void  RegisterAjax()
    {
        RegisterAjax(
this " callAjax " " callBack " );
    }
    
public   void  RegisterAjax(Control ct,  string  functionName,  string  callBackName)
    {
        
if  ( ! ct.Page.ClientScript.IsClientScriptBlockRegistered(functionName))
        {
            
string  callBack  =  ct.Page.ClientScript.GetCallbackEventReference(ct,  " arg " , callBackName,  null );
            
string  clientFunction  =   " function  "   +  functionName  +   " (arg){ "   +  callBack  +   " } " ;
            ct.Page.ClientScript.RegisterClientScriptBlock(ct.Page.GetType(), functionName, clientFunction, 
true );
        }
    }
    
public   string  GetCallbackResult()
    {
        
return  ajaxCallBackResult;
    }
    
public   virtual   void  RaiseCallbackEvent( string  eventArgument)
    {
        
    }
    
public   virtual   void  RegisterCommonScript()
    {
        
const   string  script  =   @" function $(id){return document.getElementById(id)}function $V(id,defaltValue){if($(id)){if(defaltValue && $(id).value.length==0){return defaltValue;} else{return $(id).value;}}return '';} " ;

        Page.ClientScript.RegisterClientScriptBlock(
this .Page.GetType(),  " GetBy " , script,  true );
    }
    
#endregion
}

 

OK,现在看一下Default.aspx的Page_Load里调用一下:

05233050_Wr7N.gif
public   partial   class  _Default :PageBase
{
    
int  myID;
    
protected   void  Page_Load( object  sender, EventArgs e)
    {
        LoadMyInfo();
        LoadListInfo();
        RegisterCommonScript();
        RegisterAjax();
    }
// ...省略N行代码...
}

 

其实,Ajax只有两部分:

1:点提交时,用户消息要ajax提交到后台入库:
2:用户定时去取消息

 

 

关于这两个,我们看一下ICallBack的实现:

05233050_Wr7N.gif
public   override   void  RaiseCallbackEvent( string  eventArgument)
    {
        
int  splitIndex  =  eventArgument.IndexOf( ' : ' );
        
string  cmd  =  eventArgument.Substring( 0 , splitIndex);
        
string  data  =  eventArgument.Substring(splitIndex + 1 );
        
switch  (cmd)
        {
            
case   " 0 " : // 送发消息
                ajaxCallBackResult  =   " 0☆ "   +  Send(data);
                
break ;
            
case   " 1 " : // 查询消息
                ajaxCallBackResult  =   " 1☆ "   +  GetMessage(data);
                
break ;
        }
    }

接收时:该代码和前台html约定好分隔符,这里为“:”号;

返回时:也要约定好分隔符,这里为“☆”号;

 

接下来就是实现两个函数Send与GetMessage了。

看下Send:

05233050_Wr7N.gif
  string  Send( string  msg)
    {
        
int  splitIndex = msg.IndexOf( ' : ' );
        
string [] content  =  msg.Split( ' ' ); // 内容为接收者ID☆消息内容
         MAction action  =   new  MAction(TableNames.Message);
        action.Set(Message.SendUserID, myID);
        action.Set(Message.RecvUserID,msg.Substring(
0 ,splitIndex));
        action.Set(Message.Body, msg.Substring(splitIndex
+ 1 ));
        
string  result  =  action.Insert()  ?   " 1 "  :  " 0 " ;
        
return  result;
    }

 

再看下GetMessage:

05233050_Wr7N.gif
private   const   string  msg  =   " <div class=\ " msg\ " ><font color=\ " Olive\ " >{0}</font> 对 <font color=\ " Olive\ " >{1}</font> 说 <font color=\ " Olive\ " >{2}</font><br /><p>{3}</p></div> " ;
    
string  GetMessage( string  maxID)
    {
        
string  result = "" ;
        MAction action 
=   new  MAction(CustomerSQL.Message);
        
if  (maxID  == " 0 " )
        {
            
if  (action.Fill( " 1=1 order by id desc " )) // 取最大ID返回
            {
                result 
=  action.Get < string > (Message.ID) + " " ;
                action.Close();
            }
        }
        
else
        {
            
int  rowCount;
            MDataTable mTable 
=  action.Select( 0 0 string .Format( " ID>{0} and SendUserID<>{1} and (RecvUserID=0 or RecvUserID={1}) " , maxID, myID),  out  rowCount);
            action.Close();
            
if  (rowCount  >   0 )
            {
                result 
=  mTable.Rows[rowCount  -   1 ][ " ID " ].Value  +   " " ;
                
foreach  (MDataRow row  in  mTable.Rows)
                {
                    result 
+=   string .Format(msg,row[ " UserName " ].Value, row[ " UserName2 " ].Value,row[ " PubTime " ].Value,row[ " Body " ].Value);
                }
            }
            
else
            {
                result 
+=  maxID  +   " " ;
            }
        }
        
return  result;
    }

代码有点长,似乎不太好理解,因为和前台html界面相关的关系:其实就是组合字符串输出了。

 

5:前台HTML/JS

发送消息时:

// 组合成 命令:用户ID:留言内容
callAjax( " 0: " + $V( ' hdfUserID ' ) + " : " + $( ' txtBody ' ).innerHTML);

 

接收消息时:

// 组合成 命令:最大消息ID
callAjax( " 1: " + msgMaxID);

 

回调时结果:

05233050_Wr7N.gif
    function callBack(result)
    {
       var  items=result.split('☆');     
        switch(items[0])
        {
            case "0"://发送消息返回结果
                $('btnSend').disabled=false;
                add($V('hdfBody'));
                break;
            case "1"://查询返回结果
                if(items.length>1)
                {
                    msgMaxID=items[1];
                }
                if(items.length>2)
                {
                    add(items[2]);
                }
                break;
        }
   }
   function the Add (MSG)
   {
        IF (MSG)
        {
             $ ( 'left') the innerHTML + = MSG;.
             $ ( 'left') scrollTop = $ ( 'left') the scrollHeight;.. // scroll bar to the rearmost
        }
   }

 

The remaining specific html code will not stick out in detail, because I know what I have posted the code again in detail, it is estimated that not many people watching, everyone to see a beginning, and then pull down to see the source code download, click download, almost on the beat beat ass leave

But still want to provide the entire sample download: Download  [database creation script in the App_Data directory]

 

 Welcome interested readers to discuss and comment: [code comments above too, in test use, if unknown please leave a message]. [Write Example spent one hour writing an article spent a day, not easy! ]

Reproduced in: https: //my.oschina.net/secyaher/blog/274032

Guess you like

Origin blog.csdn.net/weixin_33806300/article/details/91966677