事件处理程序从表单调用 [英] Event handler calling from form

查看:78
本文介绍了事件处理程序从表单调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hallo


之前我没有使用过事件处理程序,但是想了解如何使用n层编程拆分以下代码。感谢论坛上的一些示例代码,我不需要使用Modbus通信
协议重新发明轮子。


但这个示例代码是在表单中完成的并且只是在另一个传递事件的类中调用了一个方法。


在我们的应用程序中,我们得到了一个表单并拆分了业务逻辑和数据层,但我不知道如何处理现有的事件处理程序,我们不想直接从表单调用数据层,下面的代码在我们的BLL类中,并希望
将事件响应返回到我们的表单而不访问该数据层。 


我在考虑将对象指定为方法的返回类型,但不要认为这是正确的,任何帮助都将受到赞赏。


此事件已经在此时被声明,如果您希望代码直接在表单中,我们希望避免使用该事件。


最后一个问题,即使是所有方法在ModbusTCP_BA和a由于受保护级别,该类仍然是公开的,它仍然抱怨无法访问。

公共类ModbusTCP_BA 
{
ModbusTCP_BO ModbusData = new ModbusTCP_BO() ;

私人大师MBmaster;
private TextBox txtData;
//私人标签labData;
private byte []数据;
// data = new byte [0];
ResizeData();




// ---------------------------- --------------------------------------------
//按钮连接
// ------------------------------------------ ------------------------------
public void TCPConnect(string IPaddress)
{
尝试
{
//创建新的modbus主控并添加事件函数
MBmaster = new Master(IPaddress,502,true);
MBmaster.OnResponseData + = new Master.ResponseData(MBmaster_OnResponseData);
MBmaster.OnException + = new Master.ExceptionData(MBmaster_OnException);
//显示其他字段,启用watchdog
//grpExchange.Visible = true;
//grpData.Visible = true;
}
catch(SystemException错误)
{
throw error;
}
}




labjac

解决方案

这是一个高级别的考虑因素。


任何可能引发异常的类实现以下类。受保护的成员可以由实现以下类的类设置,并且调用类可以"提问"。

使用System; 
namespace BaseLibrary
{
public class BaseExceptionProperties
{
protected bool mHasException;
///< summary>
///表示抛出
///异常的最后一个操作。
///< / summary>
///< returns>< / returns>
public bool HasException => mHasException;

protected Exception mLastException;
///< summary>
///提供对抛出的最后一个异常的访问
///< / summary>
///< returns>< / returns>
public Exception LastException => mLastException;
///< summary>
///如果您不需要像
/// LastException那样的整个异常,则只提供异常的文本
///< / summary>
///< returns>< / returns>
public string LastExceptionMessage => LastException.Message;

///< summary>
///如果抛出
///异常,则表示返回函数。
///< / summary>
///< returns>< / returns>
public bool IsSuccessFul => !HasException;
}
}

所以在这种情况下,数据连接类实现了上述。

使用系统; 

namespace BaseLibrary
{
public class BaseSqlServerConnections:BaseExceptionProperties
{
///< summary>
///这指向您的数据库服务器
///< / summary>
protected string DatabaseServer =" KARENS-PC" ;;

///< summary>
///包含所需表格的数据库名称
///< / summary>
protected string DefaultCatalog ="" ;;
public string ConnectionString =>


" Data Source = {DatabaseServer}; Initial Catalog = {DefaultCatalog}; Integrated Security = True" ;;
///< summary>
///确定是否在Karen Payne的电脑上运行
///< / summary>
public bool IsKarenMachine => Environment.UserName ==" Karens" ;;
///< summary>
///确定是否已根据Karen Payne计算机上的默认值设置服务器名称
///< / summary>
public bool IsKarensDatabaseServer => DatabaseServer ==" KARENS-PC" ;;
}

}

然后

命名空间BaseLibrary 
{
公共类DataOperations:BaseSqlServerConnections
{

public bool InsertNew(string pKey,out int pId)
{
mHasException = false;
pId = 0;

var dt = new DataTable();
using(var cn = new SqlConnection(){ConnectionString =" Your connection string"})
{
using(var cmd = new SqlCommand(){Connection = cn})
{
//插入记录,获取新的主键(假设它是自动递增的)
cmd.CommandText =" INSERT INTO Keys(key)VALUES(@Value);" +
" SELECT CAST(scope_identity()AS int);" ;;

cmd.Parameters.AddWithValue(" Id",pKey);
尝试
{
cn.Open();
pId =(int)cmd.ExecuteScalar();
}
catch(Exception ex)
{
mHasException = true;
mLastException = ex;
}
}
}

返回IsSuccessFul;
}
}
}


两个基类都在另一层调用的数据层中,并且调用者检查bool返回价值。





Hallo

I haven't worked with the event handler before, but would like to understand how the following code will be split using n tier programming. Thanks to some sample codes on one o the forums I don't need to re invent the wheel with the Modbus communication protocol.

But this sample code was done inside a form and just called a methods inside another class that handed the event.

In our application we got a form and split the Business logic and the Data layer but I'm not sure how to handle the existing event handler, we don't want to call the data layer directly from the form, Code below is in the our BLL class and would like to get the event response back to our form without accessing that datalayer. 

I was thinking about specifying a object as return type on the methods, but don't think this is correct, any assistance will be appreciated.

The event has already been declared at this point, and it's working well if you wanted your code directly in the form, which we want to avoid.

The last issue, even all the methods in the ModbusTCP_BA and also the class is public it still complaints about inaccesible due to protected level.

   public class ModbusTCP_BA
    {
        ModbusTCP_BO ModbusData = new ModbusTCP_BO();

        private Master MBmaster;
        private TextBox txtData;
        //private Label labData;
        private byte[] data;
        //data = new byte[0];
        ResizeData();
                             

       

        // ------------------------------------------------------------------------
        // Button connect
        // ------------------------------------------------------------------------
        public void TCPConnect(string IPaddress)
        {
            try
            {
                // Create new modbus master and add event functions
                MBmaster = new Master(IPaddress, 502, true);
                MBmaster.OnResponseData += new Master.ResponseData(MBmaster_OnResponseData);
                MBmaster.OnException += new Master.ExceptionData(MBmaster_OnException);
                // Show additional fields, enable watchdog
                //grpExchange.Visible = true;
                //grpData.Visible = true;
            }
            catch (SystemException error)
            {
                throw error;
            }
        }


labjac

解决方案

Here is a high level consideration.

Any class which may throw an exception implement the following class. The protected members may be set by the class implementing the following class and the calling class can "ask questions".

using System;
namespace BaseLibrary
{
    public class BaseExceptionProperties
    {
        protected bool mHasException;
        /// <summary>
        /// Indicate the last operation thrown an 
        /// exception or not.
        /// </summary>
        /// <returns></returns>
        public bool HasException => mHasException;

        protected Exception mLastException;
        /// <summary>
        /// Provides access to the last exception thrown
        /// </summary>
        /// <returns></returns>
        public Exception LastException => mLastException;
        /// <summary>
        /// If you don't need the entire exception as in 
        /// LastException this provides just the text of the exception
        /// </summary>
        /// <returns></returns>
        public string LastExceptionMessage => LastException.Message;

        /// <summary>
        /// Indicate for return of a function if there was an 
        /// exception thrown or not.
        /// </summary>
        /// <returns></returns>
        public bool IsSuccessFul => !HasException;
    }
}

So in this case a data connection class implements the above.

using System;

namespace BaseLibrary
{
    public class BaseSqlServerConnections : BaseExceptionProperties
    {
        /// <summary>
        /// This points to your database server
        /// </summary>
        protected string DatabaseServer = "KARENS-PC";
       
        /// <summary>
        /// Name of database containing required tables
        /// </summary>
        protected string DefaultCatalog = "";
        public string ConnectionString =>


"Data Source={DatabaseServer};Initial Catalog={DefaultCatalog};Integrated Security=True"; /// <summary> /// Determines if running on Karen Payne's computer /// </summary> public bool IsKarenMachine => Environment.UserName == "Karens"; /// <summary> /// Determine if server name has been set from the default on Karen Payne's computer /// </summary> public bool IsKarensDatabaseServer => DatabaseServer == "KARENS-PC"; } }

Then

namespace BaseLibrary
{
    public class DataOperations : BaseSqlServerConnections
    {

        public bool InsertNew(string pKey, out int pId)
        {
            mHasException = false;
            pId = 0;

            var dt = new DataTable();
            using (var cn = new SqlConnection() { ConnectionString = "Your connection string" })
            {
                using (var cmd = new SqlCommand() { Connection = cn })
                {
                    // insert record, get new primary key (assuming it's auto-incrementing)
                    cmd.CommandText = "INSERT INTO Keys (key) VALUES (@Value);" +
                                      "SELECT CAST(scope_identity() AS int);";

                    cmd.Parameters.AddWithValue("Id", pKey);
                    try
                    {
                        cn.Open();
                        pId = (int)cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        mHasException = true;
                        mLastException = ex;
                    }
                }
            }

            return IsSuccessFul;
        }
   }
}

Where both base classes are in the data layer called by another layer and the caller inspects the bool return value.


这篇关于事件处理程序从表单调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆