??xml version="1.0" encoding="utf-8" standalone="yes"?> /*DataDridFilterForm.aspx 前台E序 */ <%@ Page language="c#" Codebehind="DataGridFilterForm.aspx.cs"
AutoEventWireup="false"
Inherits="DataDridFilterDemo.DataDridFilterForm" %> /*DataDridFilterForm.aspx.cs 后台处理E序 */ using System; namespace DataDridFilterDemo #region Web H体设计器生成的代码 } private void FillDropDownList() DataSet ds=new DataSet(); ddlCategory.DataSource=ds; private void DataFiller() DataSet objds=new DataSet(); DataView dvUK=new DataView(objds.Tables["dtProduct"]); this.dgProduct.DataSource=dvUK; private void FilterChange(object sender, System.EventArgs e) /* 实现DataGrid控g分页昄的示?/p>
*/ 前台处理E序 //DataGridPageDemo.aspx <%@ Page language="c#" Codebehind="DataGridPageDemo.aspx.cs"
AutoEventWireup="false" Inherits="DataGridPageDemo.DataGridPageDemo"
%> //下面的是后台处理E序 DataGridPageDemo.aspx.cs using System; namespace DataGridPageDemo #region Web H体设计器生成的代码 } private void DataFiller() dgDemo.DataSource=ds.Tables["dtorder"]; } private void dgDemo_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e) /*UpdateDelForm.aspx 前台E序代码 */ <%@ Page language="c#" Codebehind="UpdateDelForm.aspx.cs"
AutoEventWireup="false" Inherits="UpdateDelDbDemo.UpdateDelForm" %> /*UpdateDelForm.aspx.cs 后台E序代码 */ using System; namespace UpdateDelDbDemo #region Web H体设计器生成的代码 } dgDemo.DataSource=ds; private void dgDemo_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) private void dgDemo_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) private void dgDemo_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) dgDemo.EditItemIndex=-1; } private void UpdateRecord(string strUserID, string strFirstName, string strLastName, string strAddress) DataTable tbl=ds.Tables["dtUserInfo"]; SqlCommandBuilder cb=new SqlCommandBuilder(objAdpt); private void dgDemo_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) string strUserID=e.Item.Cells[0].Text; dgDemo.EditItemIndex=-1; DataTable tbl=ds.Tables["dtUserInfo"];
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="vs_snapToGrid" content="True">
<meta name="vs_showGrid" content="True">
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content=" </HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<FONT face="宋体">
<asp:DropDownList id="ddlCategory" style="Z-INDEX: 101; LEFT: 120px; POSITION: absolute; TOP: 16px"
runat="server" Width="106px" Height="26px" AutoPostBack="True"></asp:DropDownList>
<asp:Label id="lblCategory" style="Z-INDEX: 102; LEFT: 32px; POSITION: absolute; TOP: 24px"
runat="server">Category:</asp:Label>
<asp:Label
id="lblPrice" style="Z-INDEX: 103; LEFT: 256px; POSITION: absolute;
TOP: 24px" runat="server">Price Range:</asp:Label>
<asp:DropDownList id="ddlPrice" style="Z-INDEX: 104; LEFT: 368px; POSITION: absolute; TOP: 16px" runat="server"
AutoPostBack="True">
<asp:ListItem Value="0" Selected="True">Any Price</asp:ListItem>
<asp:ListItem Value="1">Cheap</asp:ListItem>
<asp:ListItem Value="2">Moderate</asp:ListItem>
<asp:ListItem Value="3">Expensive</asp:ListItem>
<asp:ListItem Value="4">Absurdly Expensive</asp:ListItem>
</asp:DropDownList>
<asp:DataGrid id="dgProduct" style="Z-INDEX: 105; LEFT: 224px; POSITION: absolute; TOP: 96px"
runat="server">
<AlternatingItemStyle BackColor="#E8E6E6"></AlternatingItemStyle>
<ItemStyle BackColor="#F1F1F1"></ItemStyle>
<HeaderStyle BackColor="#C0C0FF"></HeaderStyle>
</asp:DataGrid></FONT>
</form>
</body>
</HTML>
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
{
/// <summary>
/// WebForm1 的摘要说明?br> /// </summary>
public class DataDridFilterForm : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DropDownList ddlCategory;
protected System.Web.UI.WebControls.Label lblCategory;
protected System.Web.UI.WebControls.Label lblPrice;
protected System.Web.UI.WebControls.DropDownList ddlPrice;
protected System.Web.UI.WebControls.DataGrid dgProduct;
public static string strCategory="CategoryID=1";
public static string strPrice="UnitPrice>0";
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放|用户代码以初始化页?br> if(!IsPostBack)
{
FillDropDownList();
DataFiller();
}
}
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web H体设计器所必需的?br> //
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方?- 不要使用代码~辑器修?br> /// 此方法的内容?br> /// </summary>
private void InitializeComponent()
{
this.ddlCategory.SelectedIndexChanged += new System.EventHandler(this.FilterChange);
this.ddlPrice.SelectedIndexChanged += new System.EventHandler(this.FilterChange);
this.Load += new System.EventHandler(this.Page_Load);
#endregion
{
string strCon="server=JOSEN;database=NorthWind;integrated security=true";
string strSqlCategory="select CategoryName,CategoryID from Categories";
SqlConnection objCon=new SqlConnection(strCon);
SqlDataAdapter objAdpt=new SqlDataAdapter(strSqlCategory,objCon);
objAdpt.Fill(ds);
ddlCategory.DataTextField="CategoryName";
ddlCategory.DataValueField="CategoryID";
ddlCategory.DataBind();
}
{
string strCon="server=JOSEN;database=NorthWind;integrated security=true";
string strSqlProduct="select ProductID,ProductName,CategoryID,UnitPrice from Products";
SqlConnection objCon=new SqlConnection(strCon);
SqlDataAdapter objAdpt=new SqlDataAdapter(strSqlProduct,objCon);
objAdpt.Fill(objds,"dtProduct");
dvUK.RowFilter=strCategory+" and "+strPrice;
dgProduct.DataBind();
}
{
FilterByPrice(ddlPrice.SelectedItem.Text.ToString());
FilterByCategory(ddlCategory.SelectedItem.Value.ToString());//注意q里Q用的是CategoryID而不是CategoryName
DataFiller();
}
private void FilterByPrice(string strChoice)
{
switch(strChoice)
{
case "Any Price":
strPrice="UnitPrice>0";
break;
case "Cheap":
strPrice="UnitPrice<20";
break;
case "Moderate":
strPrice="UnitPrice>19 and UnitPrice<50";
break;
case "Expensive":
strPrice="UnitPrice>=50";
break;
case "Absurdly Expensive":
strPrice="UnitPrice>100";
break;
}
}
{
strCategory="CategoryID="+strChoice;
}
}
}
文章来源:http://www.tkk7.com/kuxiaoku/articles/94809.html
]]>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content=" </HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<FONT face="宋体">
<asp:DataGrid id="dgDemo" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 8px" runat="server"
Width="264px" Height="240px" AllowPaging="True">
<PagerStyle Mode="NumericPages"></PagerStyle>
</asp:DataGrid></FONT>
</form>
</body>
</HTML>
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
{
/// <summary>
/// WebForm1 的摘要说明?br> /// </summary>
public class DataGridPageDemo : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgDemo;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放|用户代码以初始化页?br> if(!IsPostBack)
{
DataFiller();
}
}
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web H体设计器所必需的?br> //
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方?- 不要使用代码~辑器修?br> /// 此方法的内容?br> /// </summary>
private void InitializeComponent()
{
this.dgDemo.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dgDemo_PageIndexChanged);
this.Load += new System.EventHandler(this.Page_Load);
#endregion
{
string strConn="server=JOSEN;database=NorthWind;integrated security=true";
string strSql="select * from orders";
SqlConnection objCon=new SqlConnection(strConn);
SqlDataAdapter objAdapter=new SqlDataAdapter(strSql,objCon);
DataSet ds=new DataSet();
objAdapter.Fill(ds,"dtorder");
dgDemo.DataBind();
{
dgDemo.CurrentPageIndex=e.NewPageIndex;
DataFiller();
}
}
}
文章来源:http://www.tkk7.com/kuxiaoku/articles/94810.html
]]>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="vs_snapToGrid" content="False">
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content=" </HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<FONT face="宋体">
<asp:DataGrid id="dgDemo" runat="server" AutoGenerateColumns="False" GridLines="Horizontal">
<Columns>
<asp:BoundColumn DataField="ID" ReadOnly="True" HeaderText="UserID"></asp:BoundColumn>
<asp:BoundColumn DataField="FirstName" HeaderText="FirstName"></asp:BoundColumn>
<asp:BoundColumn DataField="LastName" HeaderText="LastName"></asp:BoundColumn>
<asp:BoundColumn DataField="address" HeaderText="Address"></asp:BoundColumn>
<asp:EditCommandColumn
ButtonType="LinkButton" UpdateText="更新" CancelText="取消"
EditText="~辑"></asp:EditCommandColumn>
<asp:ButtonColumn Text="删除" CommandName="Delete"></asp:ButtonColumn>
</Columns>
</asp:DataGrid></FONT>
</form>
</body>
</HTML>
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
{
/// <summary>
/// WebForm1 的摘要说明?br> /// </summary>
public class UpdateDelForm : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgDemo;
private string strCon="server=JOSEN;database=testDb;integrated security=true";
private string strSqlSelect="select * from UserInfo";
private SqlConnection objCon;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放|用户代码以初始化页?br> if(!IsPostBack)
LoadGrid();
}
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web H体设计器所必需的?br> //
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方?- 不要使用代码~辑器修?br> /// 此方法的内容?br> /// </summary>
private void InitializeComponent()
{
this.dgDemo.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgDemo_CancelCommand);
this.dgDemo.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgDemo_EditCommand);
this.dgDemo.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgDemo_UpdateCommand);
this.dgDemo.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgDemo_DeleteCommand);
this.Load += new System.EventHandler(this.Page_Load);
#endregion
//d数据q帮定到QataQrid
private void LoadGrid()
{
Connect();
SqlDataAdapter objAdpt=new SqlDataAdapter(strSqlSelect,objCon);
DataSet ds=new DataSet();
objAdpt.Fill(ds,"dtUserInfo");
dgDemo.DataBind();
}
//建立数据库的q接
private void Connect()
{
if(objCon==null)
objCon=new SqlConnection(strCon);
if(objCon.State==ConnectionState.Closed)
objCon.Open();
}
//断开数据库的q接
private void Disconnect()
{
objCon.Close();
}
{
dgDemo.EditItemIndex=e.Item.ItemIndex;
LoadGrid();
}
{
dgDemo.EditItemIndex=-1;
LoadGrid();
}
{
string strUserID=e.Item.Cells[0].Text;
//string strUserID=((TextBox)e.Item.Cells[0].Controls[0]).Text;
string strFirstName=((TextBox)e.Item.Cells[1].Controls[0]).Text;
string strLastName=((TextBox)e.Item.Cells[2].Controls[0]).Text;
string strAddress=((TextBox)e.Item.Cells[3].Controls[0]).Text;
//此方法具体处理数据库的更?br> UpdateRecord(strUserID,strFirstName,strLastName,strAddress);
//调用此方法从数据库读取数?br> LoadGrid();
{
Connect();
SqlDataAdapter objAdpt=new SqlDataAdapter(strSqlSelect,objCon);
DataSet ds=new DataSet();
objAdpt.Fill(ds,"dtUserInfo");
Disconnect();
//讑֮表的主键
DataColumn[] myKey=new DataColumn[1];
myKey[0]=tbl.Columns["ID"];
tbl.PrimaryKey=myKey;
DataRow dr=tbl.Rows.Find(strUserID);
//dr["ID"]=strUserID;
dr["FirstName"]=strFirstName;
dr["LastName"]=strLastName;
dr["address"]=strAddress;
Connect();
objAdpt.Update(ds,"dtUserInfo");
Disconnect();
}
{
DelRecord(strUserID);
//调用此方法从数据库读取数?br> LoadGrid();
}
private void DelRecord(string strUserID)
{
Connect();
SqlDataAdapter objAdpt=new SqlDataAdapter(strSqlSelect,objCon);
DataSet ds=new DataSet();
objAdpt.Fill(ds,"dtUserInfo");
Disconnect();
//讑֮表的主键
DataColumn[] myKey=new DataColumn[1];
myKey[0]=tbl.Columns["ID"];
tbl.PrimaryKey=myKey;
DataRow dr=tbl.Rows.Find(strUserID);
dr.Delete();
Connect();
objAdpt.Update(ds,"dtUserInfo");
Disconnect();
}
}
}
文章来源:http://www.tkk7.com/kuxiaoku/articles/94807.html
]]>
前台E序
*/
<%@ Page language="c#" Codebehind="CalendarForm2.aspx.cs" AutoEventWireup="false" Inherits="CalendarDemo.CalendarForm2" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>CalendarForm2</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content=" </HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<FONT face="宋体">
<asp:ListBox id="lbxEmployee" style="Z-INDEX: 101; LEFT: 224px; POSITION: absolute; TOP: 80px"
runat="server" Width="144px" Height="264px" Rows="7" AutoPostBack="True"></asp:ListBox>
<asp:Calendar id="calHire" style="Z-INDEX: 102; LEFT: 232px; POSITION: absolute; TOP: 384px" runat="server"
Width="312px" Height="160px"></asp:Calendar>
<asp:Label id="lblInfo" style="Z-INDEX: 103; LEFT: 232px; POSITION: absolute; TOP: 352px" runat="server"
Width="152px" Height="24px">display Dates</asp:Label></FONT>
</form>
</body>
</HTML>
/*CalendarForm2.aspx.cs
日历控g使用后台E序
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CalendarDemo
{
/// <summary>
/// CalendarForm2 的摘要说明?br> /// </summary>
public class CalendarForm2 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.ListBox lbxEmployee;
protected System.Web.UI.WebControls.Calendar calHire;
protected System.Web.UI.WebControls.Label lblInfo;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放|用户代码以初始化页?br> string strCon="server=JOSEN;database=NorthWind;integrated security=true";
string strSql="select EmployeeID,LastName,FirstName,HireDate from Employees";
SqlConnection objCon=new SqlConnection(strCon);
SqlDataAdapter objAdpt=new SqlDataAdapter(strSql,objCon);
DataSet ds=new DataSet();
objAdpt.Fill(ds,"dtEmployee");
if(!IsPostBack)
{
this.lbxEmployee.DataSource=ds;
lbxEmployee.DataTextField="LastName";
lbxEmployee.DataBind();
}
else
{
DateTime datHireDate;
datHireDate=Convert.ToDateTime(ds.Tables["dtEmployee"].Rows[lbxEmployee.SelectedIndex]["HireDate"]);
lblInfo.Text=ds.Tables["dtEmployee"].Rows[lbxEmployee.SelectedIndex]["LastName"].ToString();
this.calHire.VisibleDate=datHireDate;
calHire.SelectedDate=datHireDate;
lblInfo.Text+="hired on "+datHireDate;
}
}
#region Web H体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web H体设计器所必需的?br> //
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方?- 不要使用代码~辑器修?br> /// 此方法的内容?br> /// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
攄规则Q第一个整?一律被攄在第一行的中间位置Q第二个值得位置必须攄在第一个值得左上角,因此Q由1的位|往左一|再往上一|此时出数组的范_因此回到同一列的最下方?/p>
同样Q?必须攑֜2的左上角Q?攑֜3的左上角Q此时超出数l范围回到同一行的最双I格。同此规则,来到5的位|,当我们要填入6的时候,其位|? 已被数字1占据Q因此将其放|到5的下方,接下来的数字则依规则一一攄到合适的位置Q当填到15的时候,其左方与上方均没有位|,因此下一个数直接攄 ?5的下方,完成了填?6的|接下来的数目Q均可以依上q的规则填写完成?/p>
下面看看q个术矩阵的示例代码:
/*此类是主H口Q接受输入的奇数
MagicSquare.cs
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace MagicSquare
{
/// <summary>
/// Form1 的摘要说明?br> /// </summary>
public class MagicSquare : System.Windows.Forms.Form
{
/// <summary>
/// 必需的设计器变量?br> /// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label lblNumber;
private System.Windows.Forms.TextBox txbNumber;
private System.Windows.Forms.Button btnOK;
public int number=0;
public MagicSquare()
{
//
// Windows H体设计器支持所必需?br> //
InitializeComponent();
//
// TODO: ?InitializeComponent 调用后添加Q何构造函C?br> //
}
/// <summary>
/// 清理所有正在用的资源?br> /// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows H体设计器生成的代码
/// <summary>
/// 设计器支持所需的方?- 不要使用代码~辑器修?br> /// 此方法的内容?br> /// </summary>
private void InitializeComponent()
{
this.lblNumber = new System.Windows.Forms.Label();
this.txbNumber = new System.Windows.Forms.TextBox();
this.btnOK = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lblNumber
//
this.lblNumber.Location = new System.Drawing.Point(48, 32);
this.lblNumber.Name = "lblNumber";
this.lblNumber.TabIndex = 0;
this.lblNumber.Text = "误入奇敎ͼ";
//
// txbNumber
//
this.txbNumber.Location = new System.Drawing.Point(192, 32);
this.txbNumber.Name = "txbNumber";
this.txbNumber.TabIndex = 1;
this.txbNumber.Text = "";
//
// btnOK
//
this.btnOK.Location = new System.Drawing.Point(144, 80);
this.btnOK.Name = "btnOK";
this.btnOK.TabIndex = 2;
this.btnOK.Text = "OK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// MagicSquare
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(432, 117);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.txbNumber);
this.Controls.Add(this.lblNumber);
this.Name = "MagicSquare";
this.Text = "MagicSquare";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 应用E序的主入口炏V?br> /// </summary>
[STAThread]
static void Main()
{
Application.Run(new MagicSquare());
}
private void btnOK_Click(object sender, System.EventArgs e)
{
number=Convert.ToInt32(txbNumber.Text.Trim());
if(number%2==1)
{
this.Hide();
ShowResult result=new ShowResult(number);
result.Show();
}
else
{
MessageBox.Show("您输入的不是奇数Q请重新输入奇数Q?,"输入错误");
}
}
}
}
/*q个cȝ来处理魔术矩늚生成Q以及在H体上显C出?/p>
Show.cs
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace MagicSquare
{
/// <summary>
/// Show 的摘要说明?br> /// </summary>
public class ShowResult : System.Windows.Forms.Form
{
/// <summary>
/// 必需的设计器变量?br> /// </summary>
private System.ComponentModel.Container components = null;
private int n;
private int[,] mm;
public ShowResult ()
{
//
// Windows H体设计器支持所必需?br> //
InitializeComponent();
//
// TODO: ?InitializeComponent 调用后添加Q何构造函C?br> //
}
public ShowResult (int number)
{
n=number;
mm=new int[n,n];
AssignValue(n);
}
/// <summary>
/// 清理所有正在用的资源?br> /// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
Application.Exit();
}
#region Windows H体设计器生成的代码
/// <summary>
/// 设计器支持所需的方?- 不要使用代码~辑器修?br> /// 此方法的内容?br> /// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.Size = new System.Drawing.Size(300,300);
this.Text = "ShowResult";
}
#endregion
public void AssignValue(int n)
{
int assignValue=1;
int p=n-1;
int col=p/2;
int row=0;
//初始化数l?br> for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
mm[i,j]=0;
}
}
mm[row,col]=assignValue;
do
{
assignValue++;
col--;
row--;
if(col<0&&row<0)
{
row+=2;
col+=1;
}
else
{
if(col<0)
col=p;
if(row<0)
row=p;
}
if(mm[row,col]!=0)
{
col+=1;
row+=2;
}
mm[row,col]=assignValue;
}while(assignValue<n*n);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint (e);
Graphics g=this.CreateGraphics();
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
g.DrawString(mm[i,j].ToString(),new Font(FontFamily.GenericSansSerif.ToString(),15f),Brushes.YellowGreen,j*40+20,i*40+20);
}
g.Dispose();
}
}1? 自动化的内存理QAutomatic memory managementQ?
手动理内存需要程序员自行分配和释攑ֆ存块。这要求E序员有清晰的头脑和Ҏ个运行过E有十分?
把握Q好难!Q。而c#把程序员从这难以承担的Q务中解放出来。在多数的情况下Q这U自动内存管理提
高代码的质量和程序员的生产力。ƈ且,不会对程序的意图和执行生幅面的影响Q?俺可不相信m$的鬼
话)。不q,估计比java的回收站好一点吧。因为c#出道q嘛Q尽胡扯Q。好了,来看看例子?/
using System;
public class Stack
{
private Node first = null;
public bool Empty {
get {
return (first == null);
}
}
public object Pop() {
if (first == null)
throw new Exception("Can't Pop from an empty Stack.");
else {
object temp = first.Value;
first = first.Next;
return temp;
}
}
public void Push(object o) {
first = new Node(o, first);
}
class Node
{
public Node Next;
public object Value;
public Node(object value): this(value, null) {}
public Node(object value, Node next) {
Next = next;
Value = value;
}
}
}
class Test
{
static void Main() {
Stack s = new Stack();
for (int i = 0; i < 10; i++)
s.Push(i);
while (!s.Empty)
Console.WriteLine(s.Pop());
}
}
/*
stackcdC一pdNode的实例。大家可以看看stackcȝPushҎ。Node的实例就是在PushҎ中创建的?
是“first = new Node(o, first);”。请Cq个“new”噢。它是用来创徏cd例的。相关的语法?
多,遛到后面用一节详l讲。这里只是要了解自动内存理QAutomatic memory managementQ好处?Q?#8220;new”
是负责初始化cd例。而在c/c++中释放这些实例要用另一个关键字“delete”。但是在什么时候用delete呢,
q通常是很费神的活Q老手也会阴沟里翻舏V何冉|俺呢Q但在c#中有不用了。例子里没有用“delete”?
当Node的实例不需要时Q垃圾收集器Qgarbage collectorQ自动销毁它Q不用俺操心喽。这点到和java?
像的Q可能是抄的Q?
在一个testc里Q俺用了一个@环,对stackcȝ实例的PushҎ赋值十ơ。于是,Push创徏了Node的十个实
例(instanceQ。然后用Pop把它们显C出来。其序正好与创建的序相反?
q个例子相当的好Q是stack
的一个典型,也很好的表述了自动内存管理的机制。但也不好懂Q好在这一节不是写l毫无基的网友看的?
个都׃几分钟看明白Q各位大虾更是没问题?
其实Q当昄完了“10”以后Q就会有一个Node的实例符合被释放的条Ӟ但垃圾收集器q不一定会q样做?
也就是说Q它的行为ƈ不确定(q和java一P俺猜Q。有时候,q种行ؓ会带来一些负面媄响。v码是?
能降低。自动内存管理本w也是有问题的。因为它很难理一些特D情c有一些关于java的垃圾收集器?
文章也有提到。m$也不会好得了多少。所以,m$有个不安全代码的术语Qunsafe codeQ,用来为高U用h
务。即Q用户可以不采用垃圾攉器。但必须?#8220;unsafe”关键字显式声明之。这样就避免了用户不l意?
外用不安全代码。下面是一个例子:*/
using System;
class Test
{
unsafe static void WriteLocations(byte[] arr) {
fixed (byte *p_arr = arr) {
byte *p_elem = p_arr;
for (int i = 0; i < arr.Length; i++) {
byte value = *p_elem;
string addr = int.Format((int) p_elem, "X");
Console.WriteLine("arr[{0}] at 0x{1} is {2}", i, addr, value);
p_elem++;
}
}
}
static void Main() {
byte[] arr = new byte[] {1, 2, 3, 4, 5};
WriteLocations(arr);
}
}
/*
俺对q个例子不是很满意,也让俺有点迷惑,有机会再自己写一个。很单,只是可以用指针了Q万岁!
其实Q俺对这一节最没有把握了!有不地斚w不能自圆其说Q所以,请各位大虑֤力批评?/
1? cd
c#支持两种基本的类型:一U是|value typesQ,一U是引用Qreference typesQ。值包括简单类?
Qchar、int、和floatQ,枚DQenumQ和l构QstructQ。引用包括类QclassQ,界面QinterfaceQ,
代表QdelegateQ和数组阵列QarrayQ。g引用不同之处在于Q值直接存储它的数据内容;而引用存储对?
的引用。是不是_费解?Q打个比方吧。你在某C了套别墅Q好噢Q。却从未去过Q只知道地址Q?
么办Q你可以坐出URQ司机看了地址q道怎样C用你操心。你手里的地址好像对象的名字Q你?
它写在程序中Q就好像把地址l了司机。司机就是你的编译器Q它知道该去哪。你豪华的房子就好比那个
NGWS SDK开发包Q?2mb噢,够豪华了Q俺的m?-pL喽)。房子里有你惌的东东,比如你想写一?
话(i dont like Hello worldQ,好像上面例子,要用?#8220;WriteLine”。于是,你就l出“WriteLine”
的地址Q比如:“Console.WriteLine”。明白?Q俺可篏了。zzz... Q强打精)不知道你惛_没有Q?
值和引用的区别可以引Z个重要特性。值的变量和变量存储的数据是一一对应的,唯一性。而引用则?
然。引用中不同的变量可以引用同一个对象的实例。当其中一个变量改变实例的值时Q其他引用这个实例的
变量也会受到影响Q当Ӟ变量本nq没有改变,卻I地址没变Q。瞧Q变量只是说明存储对象的位置Q地
址Q,而不是对象本w。就好像你漂亮的房子被烧了,但你的地址q没有改变,但地址对应的房子就没了?
也许是别Z有这个地址Q他ȝ了你的房子!好了Q在l个例子Q?/
1: using System;
2: class CValue
3: {
4: public int Value = 0;
5: }
6: class Test
7: {
8: static void Main() {
9: int val1 = 0;
10: int val2 = val1;
11: val2 = 123;
12: CValue ref1 = new CValue();
13: CValue ref2 = ref1;
14: ref2.Value = 123;
15: Console.WriteLine("Values: {0}, {1}", val1, val2);
16: Console.WriteLine("Refs: {0}, {1}", ref1.Value, ref2.Value);
17: }
18: }
/* 下面是输出的l果Q?
Values: 0, 123
Refs: 123, 123
啊哈Q应该粉清楚了吧。变量val1和变量val2互不影响,它们各自有自q存储I间。而ref2复制
了ref1Q所以,它们引用了同一个对象的实例。当改变它们其中一个的时候,׃影响到另一个的
倹{?
1? 数组cdQArray typesQ?
数组可以是一l的Q也可是多维的。数的成员可以是整齐的Q也可以是变长(jaggedQ的?
一l的数组是最普通,最单的。这里值给Z个例子,׃多解释了?/
using System;
class Test
{
static void Main() {
int[] arr = new int[5];
for (int i = 0; i < arr.Length; i++)
arr[i] = i * i;
for (int i = 0; i < arr.Length; i++)
Console.WriteLine("arr[{0}] = {1}", i, arr[i]);
}
}
/* l果如下Q?
arr[0] = 0
arr[1] = 1
arr[2] = 4
arr[3] = 9
arr[4] = 16
我们q可以比较的看看多维Q规则,变长的数l的定义和赋|*/
class Test
{
static void Main() {
int[] a1 = new int[] {1, 2, 3}; //一l?
int[,] a2 = new int[,] {{1, 2, 3}, {4, 5, 6}}; //二维
int[,,] a3 = new int[10, 20, 30]; //三维
int[][] j2 = new int[3][]; //变长
j2[0] = new int[] {1, 2, 3};
j2[1] = new int[] {1, 2, 3, 4, 5, 6};
j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
}
}
/*
上面的例子给Z各种样式的数l。变量a1、a2和a3是规则数l。j2则是变长的数l?
规则数组很容易就可以计算出它们的长度。比如a3的长度是Q?0*20*30=6000。相反,变长
数组有点不同,它的每一个维度都必须单独定义。如j2的第一l度?Q第二个?Q第
三个?Q所以总长度是Q?*3+1*6+1*9=18?
上面Ҏl的赋值是严}的风|在某U情况下Q我们可以简化写法,但我总觉得这U简?
应用限制太多Q容易出错。在q里׃作介l了。这里再l一个例子说明函C的参数如?
赋?/
class Test
{
static void F(long[] arr) {}
static void Main() {
F(new longt[] {1, 2, 3});
}
}
赶出一~!h正!
1? l一pȝcdQType system unificationQ?
c#独创了一U类型——统一pȝcdQؓ了这个篏刑,我头疼死了。谁有更好的名字Q请务必告诉
我)。MQ所有的其他cdQ包括值和引用Q都可以被当作统一pȝcd来对待。从概念上说Q?
所有的cd都从它派生。这P其他的类型就可以使用l一pȝcd的属性和Ҏ。包括一?#8220;
?#8221;cdQ如Qint。还是给个例子吧Q?/
using System;
class Test
{
static void Main() {
Console.WriteLine(3.ToString());
}
}
/*“3.ToString()”调用了object?#8220;ToString()”Ҏ。相信学qc/c++的朋友都知道要输Z?
数字有多ȝQ现在就省事了。再看一个:*/
class Test
{
static void Main() {
int i = 123;
object o = i; // boxing
int j = (int) o; // unboxing
}
}
/* q个像帽子戏法的例子中,?#8220;int”转换?#8220;object”Q又转换回来。这样一来,在值和引用
之间架起了一座桥梁。这h什么用呢。即兴D一个常见的例子...min把。在c/c++中:*/
// c/c++ code
void min(int i, int j)
{
return ((i < j) ? i : j);
}
/* 如果比较的不是intQ或者说可能是intQ也可能是float、double呢?可以q样Q?/
template<class T>
T min (T i, T j)
{
return ((i < j) ? i : j)
}
/* 用c#可以Q?/
void swap (object a, object b)
{
return ((i < j) ? i : j);
}
/* 我想大家一定看出来W二个例子要比较一个int和一个float的话Q还需要一些{换,而第三个
例子可以比较所有的变量Q这个灵zd直太大了。所以,我私以ؓQ大家用时一定要心Q?
它在比较一个int和一个class的时候决不会报错的。呵呵,我发现我的翻译L跑远QL
扣不住原文。篡改甚多,敬请原谅Q?/span>
1? 语句QStatementsQ?
c#借用了c/c++大多数的语句ҎQ不q仍然有些值得注意的地斏V还有些地方是有所改动的?
在这里,我只提一些c#Ҏ的东东?
1??0 “foreach”语句
“foreach”语句列D一个集合内的所有元素,q对q些元素执行一pd的操作。还是看看例子吧Q?/
using System;
using System.Collections;
class Test
{
static void WriteList(ArrayList list) {
foreach (object o in list)
{
int i = (int) o;//如果是for语句Q这里一定会报错Q?
Console.WriteLine(0);
Console.WriteLine(++i);
}
}
static void Main() {
ArrayList list = new ArrayList();
for (int i = 0; i < 10; i++)
list.Add(i);
WriteList(list);
}
}
/*q个例子?#8220;foreach”扫描了整?#8220;list”Qƈ?#8220;list”中所有的元素打印出来。有时候还?
挺方便的?
1??5 安全查开养IThe checked and unchecked statementsQ?
“checked”?#8220;unchecked”语句用来控制数学q算和完整类型{换的查工作?#8220;checked”查它
作用的域中可能出现的q例Qƈ抛出一个异常;?#8220;unchecked”则阻止所有的查。D个例子:*/
using System;
class Test
{
static int x = 1000000;
static int y = 1000000;
static int F() {
checked {return (x * y);} // 抛出 OverflowException
}
static int G() {
unchecked {return (x * y);} // q回 -727379968
}
static int H() {
return x * y; // ~省状态?
}
static void Main() {
F(); //可以注销掉此行试试?
Console.WriteLine(G());
Console.WriteLine(H());
}
}
/*
在编译过E中不会有Q何错误出现。因?#8220;checked”?#8220;unchecked”只在q行时才起作用。值得一说的?
H()。它的缺省状态和~译器当前的~省溢出查的状态有兟뀂但q回的结果肯定和F()或G()中的M个相同?
再看一个例子:*/
using System;
class Test
{
const int x = 1000000;
const int y = 1000000;
static int F() {
checked {return (x * y);} // ~译器警告(Compile warningQ:溢出QoverflowQ?
}
static int G() {
unchecked {return (x * y);} // q回 -727379968
}
static int H() {
return x * y; // ~译器警告(Compile warningQ:溢出QoverflowQ?
}
static void Main() {
Console.WriteLine(F()); //可以注销掉此行试试?
Console.WriteLine(G());
Console.WriteLine(H()); //可以注销掉此行试试?
}
}
/* 当F()和H()求值的时候,׃引v一个编译警告。而在G()中,因ؓ有了“unchecked”Q屏蔽了q个?
告。要注意的是“checked”?#8220;unchecked”都不能对函数的返回D行操作!比如Q?/
class Test
{
static int Multiply(int x, int y) {
return x * y;
}
static int F() {
checked{ return Multiply(1000000, 1000000); } // ?return Multiply(1000000, 1000000);
} // 有相同的效果?
}
/* 其实大家E微想一下知道ؓ什么m$没有q么做!对这个内容的讨论出本文的范围和俺的能力之外哦?
在c#中,所有的十六q制数都是uint。如果用强制cd转换会引L译器报错。用“unchecked”则可?
跌q个机制Q把uint的十六进制数转化为int。如Q?/
class Test
{
public const int AllBits = unchecked((int)0xFFFFFFFF);
public const int HighBit = unchecked((int)0x80000000);
}
/* 上例所有的常数都是uintQ而且过了int的范_没有“unchecked”Q这U{换会引发一个编译器?
误。注意:上面用的?#8220;unchecked”操作W。不是语句。不q它们之间除了一个用“()”Q另一个用
“{}”以外Q几乎一栗BTWQ?#8220;checked”同样?
1??6 “lock”语句QThe lock statementQ?
“lock”获得一个相互排斥的对象锁定。(俺查q一些资料,但都没有清晰说明Q暂不介l)
Hashtable socketHolder = new Hashtable();
2. TcpClient与TcpSrvq接上后Q发送客L信息数据包至TcpServerQ然后发线E,该线E是用来接收通过Socket传来的数据?br>
3.TcpServer接收来自TcpClient的连接请求,q且socket 实例保存到Hash表中Q然后发线E以便控制socket的通讯Q同时将客户端信息在listview 控g中显C出来?br>
|
using System; using System.ServiceProcess; public class ServiceControl: ServiceBase { // 创徏服务对象的主入口?br> public static void Main() { ServiceBase.Run(new ServiceControl()); } // 定义服务参数的构造对?br> public ServiceControl() { CanPauseAndContinue = true; ServiceName = "MSDNMessageService"; AutoLog = false; } protected override void OnStart(string[] args) {...} protected override void OnStop() {...} protected override void OnPause() {...} protected override void OnContinue() {...} } |
public interface IWebMessage { WebMessageReturn Process(string sMessageLabel, string sMessageBody, int iAppSpecific); void Release(); } |
public enum WebMessageReturn { ReturnGood, ReturnBad, ReturnAbort } |
Q?xml version="1.0"?Q?br>QconfigurationQ?br>QProcessListQ?br> QProcessDefinition ProcessName="Worker1" ProcessDesc="Message Worker with 2 Threads" ProcessType="AppSpecific" ProcessThreads="2" InputQueue=".\private$\test_load1" ErrorQueue=".\private$\test_error"Q?br> QOutputListQ?br> QOutputDefinition OutputName=".\private$\test_out11" /Q?br> QOutputDefinition OutputName=".\private$\test_out12" /Q?br> Q?OutputListQ?br> Q?ProcessDefinitionQ?br> QProcessDefinition ProcessName="Worker2" ProcessDesc="Assembly Worker with 1 Thread" ProcessType="Assembly" ProcessThreads="1" InputQueue=".\private$\test_load2" ErrorQueue=".\private$\test_error"Q?br> QOutputListQ?br> QOutputDefinition OutputName="C:\MSDNMessageService\MessageExample.dll" /Q?br> QOutputDefinition OutputName="MSDNMessageService.MessageSample.ExampleClass"/Q?br> Q?OutputListQ?br> Q?ProcessDefinitionQ?br>Q?ProcessListQ?br>Q?configurationQ?/td> |
Q?xml version ="1.0"?Q?br>QMetaData xmlns="x-schema:CatMeta.xms"Q?br> QDatabaseMeta InternalName="MessageService"Q?br> QServerWiring Interceptor="Core_XMLInterceptor"/Q?br> QCollection InternalName="Process" PublicName="ProcessList" PublicRowName="ProcessDefinition" SchemaGeneratorFlags="EMITXMLSCHEMA"Q?br> QProperty InternalName="ProcessName" Type="String" MetaFlags="PRIMARYKEY" /Q?br> QProperty InternalName="ProcessDesc" Type="String" /Q?br> QProperty InternalName="ProcessType" Type="Int32" DefaultValue="RoundRobin" Q?br> QEnum InternalName="RoundRobin" Value="0"/Q?br> QEnum InternalName="AppSpecific" Value="1"/Q?br> QEnum InternalName="Assembly" Value="2"/Q?br> Q?PropertyQ?br> QProperty InternalName="ProcessThreads" Type="Int32" DefaultValue="1" /Q?br> QProperty InternalName="InputQueue" Type="String" /Q?br> QProperty InternalName="ErrorQueue" Type="String" /Q?br> QProperty InternalName="OutputName" Type="String" /Q?br> QQueryMeta InternalName="All" MetaFlags="ALL" /Q?br> QQueryMeta InternalName="QueryByFile" CellName="__FILE" Operator="EQUAL" /Q?br> Q?CollectionQ?br> QCollection InternalName="Output" PublicName="OutputList" PublicRowName="OutputDefinition" SchemaGeneratorFlags="EMITXMLSCHEMA"Q?br> QProperty InternalName="ProcessName" Type="String" MetaFlags="PRIMARYKEY" /Q?br> QProperty InternalName="OutputName" Type="String" MetaFlags="PRIMARYKEY" /Q?br> QQueryMeta InternalName="All" MetaFlags="ALL" /Q?br> QQueryMeta InternalName="QueryByFile" CellName="__FILE" Operator="EQUAL" /Q?br> Q?CollectionQ?br> Q?DatabaseMetaQ?br> QRelationMeta PrimaryTable="Process" PrimaryColumns="ProcessName" ForeignTable="Output" ForeignColumns="ProcessName" MetaFlags="USECONTAINMENT"/Q?br>Q?MetaDataQ?/td> |
private Hashtable htWorkers = new Hashtable(); IConfigCollection cWorkers = ConfigManager.Get("ProcessList", new AppDomainSelector()); foreach (IConfigItem ciWorker in cWorkers) { WorkerFormatter sfWorker = new WorkerFormatter(); sfWorker.ProcessName = (string)ciWorker["ProcessName"]; sfWorker.ProcessDesc = (string)ciWorker["ProcessDesc"]; sfWorker.NumberThreads = (int)ciWorker["ProcessThreads"]; sfWorker.InputQueue = (string)ciWorker["InputQueue"]; sfWorker.ErrorQueue = (string)ciWorker["ErrorQueue"]; // 计算q定义进E类?br> switch ((int)ciWorker["ProcessType"]) { case 0: sfWorker.ProcessType = WorkerFormatter.SFProcessType.ProcessRoundRobin; break; case 1: sfWorker.ProcessType = WorkerFormatter.SFProcessType.ProcessAppSpecific; break; case 2: sfWorker.ProcessType = WorkerFormatter.SFProcessType.ProcessAssembly; break; default: throw new Exception("Unknown Processing Type"); } // 执行更多的工作以d输出信息 string sProcessName = (string)ciWorker["ProcessName"]; if (htWorkers.ContainsKey(sProcessName)) throw new ArgumentException("Process Name Must be Unique: " + sProcessName); htWorkers.Add(sProcessName, new CWorker(sfWorker)); } |
string sQuery = "SELECT * FROM OutputList WHERE ProcessName=" + sfWorker.ProcessName + " AND Selector=appdomain://"; ConfigQuery qQuery = new ConfigQuery(sQuery); IConfigCollection cOutputs = ConfigManager.Get("OutputList", qQuery); int iSize = cOutputs.Count, iLoop = 0; sfWorker.OutputName = new string[iSize]; foreach (IConfigItem ciOutput in cOutputs) sfWorker.OutputName[iLoop++] = (string)ciOutput["OutputName"]; |
foreach (CWorker cWorker in htWorkers.Values) cWorker.Start(); |
aThreads = new ArrayList(); for (int idx=0; idxQsfWorker.NumberThreads; idx++) { WorkerThreadFormatter wfThread = new WorkerThreadFormatter(); wfThread.ProcessName = sfWorker.ProcessName; wfThread.ProcessDesc = sfWorker.ProcessDesc; wfThread.ThreadNumber = idx; wfThread.InputQueue = sfWorker.InputQueue; wfThread.ErrorQueue = sfWorker.ErrorQueue; wfThread.OutputName = sfWorker.OutputName; // 定义辅助cdQƈ其插入辅助U程l构 CWorkerThread wtBase; switch (sfWorker.ProcessType) { case WorkerFormatter.SFProcessType.ProcessRoundRobin: wtBase = new CWorkerThreadRoundRobin(this, wfThread); break; case WorkerFormatter.SFProcessType.ProcessAppSpecific: wtBase = new CWorkerThreadAppSpecific(this, wfThread); break; case WorkerFormatter.SFProcessType.ProcessAssembly: wtBase = new CWorkerThreadAssembly(this, wfThread); break; default: throw new Exception("Unknown Processing Type"); } // dҎl的调用 aThreads.Insert(idx, wtBase); } |
foreach(CWorkerThread cThread in aThreads) cThread.Start(); |
GC.SuppressFinalize(this); |
在类析构函数中将调用 Stop ҎQ这P在没有显式调?Stop Ҏ的情况下也可以正地l止对象。如果调用了 Stop
ҎQ将不需要析构函数。SuppressFinalize Ҏ能够防止调用对象?Finalize ҎQ析构函数的实际实现Q?/p>
CWorkerThread 抽象c?br>
CWorkerThread 是一个由 CWorkerThreadAppSpecifc、CWorkerThreadRoundRobin ?
CWorkerThreadAssembly l承的抽象类。无论如何处理消息,队列的大部分处理是相同的Q所?CWorkerThread
cL供了q一功能。这个类提供了抽象方法(必须被实际方法替代)以管理资源和处理消息?br>
cȝ工作再一ơ通过 Start、Stop、Pause ?Continue Ҏ来实现。在 Start Ҏ中引用了输入和错误队列。在 .NET 框架中,消息?System.Messaging 名称I间处理Q?br>
// 试打开队列Qƈ讄默认的读写属?br>MessageQueue mqInput = new MessageQueue(sInputQueue); mqInput.MessageReadPropertyFilter.Body = true; mqInput.MessageReadPropertyFilter.AppSpecific = true; MessageQueue mqError = new MessageQueue(sErrorQueue); // 如果使用 MSMQ COMQ则格式化E序讄?ActiveX mqInput.Formatter = new ActiveXMessageFormatter(); mqError.Formatter = new ActiveXMessageFormatter(); |
procMessage = new Thread(new ThreadStart(ProcessMessages)); procMessage.Start(); |
// 加入服务U程和处理线E?br>bRun = false; procMessage.Join(); // 关闭打开的消息队?br>mqInput.Close(); mqError.Close(); |
if (bPause) Thread.Sleep(500); |
Message mInput; try { // 从队列中dQƈ{?1 U?br> mInput = mqInput.Receive(new TimeSpan(0,0,0,1)); } catch (MessageQueueException mqe) { // 消息设|ؓ null mInput = null; // 查看错误代码Q了解是否超?br> if (mqe.ErrorCode != (-1072824293) ) //0xC00E001B { // 如果未超Ӟ发出一个错误ƈ记录错误?br> LogError("Error: " + mqe.Message); throw mqe; } } if (mInput != null) { // 得到一个要处理的消息,调用处理消息抽象Ҏ try { ProcessMessage(mInput); } // 捕获已知异常状态的错误 catch (CWorkerThreadException ex) { ProcessError(mInput, ex.Terminate); } // 捕获未知异常Qƈ调用 Terminate catch { ProcessError(mInput, true); } } |
public CWorkerThreadDerived(CWorker v_cParent, WorkerThreadFormatter v_wfThread) : base (v_cParent, v_wfThread) {} |
iQueues = wfThread.OutputName.Length; mqOutput = new MessageQueue[iQueues]; for (int idx=0; idxQiQueues; idx++) { mqOutput[idx] = new MessageQueue(wfThread.OutputName[idx]); mqOutput[idx].Formatter = new ActiveXMessageFormatter(); } |
try { mqOutput[iNextQueue].Send(v_mInput); } catch (Exception ex) { // 如果错误强制l止异常 throw new CWorkerThreadException(ex.Message, true); } // 计算下一个队列号 iNextQueue++; iNextQueue %= iQueues; |
private IWebMessage iwmSample; private string sFilePath, sTypeName; // 保存E序集\径和cd名称 sFilePath = wfThread.OutputName[0]; sTypeName = wfThread.OutputName[1]; // 获取对必要对象的引用 Assembly asmSample = Assembly.LoadFrom(sFilePath); Type typSample = asmSample.GetType(sTypeName); object objSample = Activator.CreateInstance(typSample); // 定义l对象的必要接口 iwmSample = (IWebMessage)objSample; 获取对象引用后,ProcessMessage Ҏ在 IWebMessage 接口上调?Process ҎQ?br> WebMessageReturn wbrSample; try { // 定义Ҏ调用的参?br> string sLabel = v_mInput.Label; string sBody = (string)v_mInput.Body; int iAppSpecific = v_mInput.AppSpecific; // 调用Ҏq捕捉返回代?br> wbrSample = iwmSample.Process(sLabel, sBody, iAppSpecific); } catch (InvalidCastException ex) { // 如果在消息内容中发生错误Q则强制发出一个非l止异常 throw new CWorkerThreadException(ex.Message, false); } catch (Exception ex) { // 如果错误调用E序集,则强制发出终止异?br> throw new CWorkerThreadException(ex.Message, true); } // 如果没有错误Q则查对象调用的q回状?br>switch (wbrSample) { case WebMessageReturn.ReturnBad: throw new CWorkerThreadException ("Unable to process message: Message marked bad", false); case WebMessageReturn.ReturnAbort: throw new CWorkerThreadException ("Unable to process message: Process terminating", true); default: break; } |
public CWorkerThreadDerived(CWorker v_cParent, WorkerThreadFormatter v_wfThread) : base (v_cParent, v_wfThread) {} |
iQueues = wfThread.OutputName.Length; mqOutput = new MessageQueue[iQueues]; for (int idx=0; idxQiQueues; idx++) { mqOutput[idx] = new MessageQueue(wfThread.OutputName[idx]); mqOutput[idx].Formatter = new ActiveXMessageFormatter(); } |
try { mqOutput[iNextQueue].Send(v_mInput); } catch (Exception ex) { // 如果错误强制l止异常 throw new CWorkerThreadException(ex.Message, true); } // 计算下一个队列号 iNextQueue++; iNextQueue %= iQueues; |
private IWebMessage iwmSample; private string sFilePath, sTypeName; // 保存E序集\径和cd名称 sFilePath = wfThread.OutputName[0]; sTypeName = wfThread.OutputName[1]; // 获取对必要对象的引用 Assembly asmSample = Assembly.LoadFrom(sFilePath); Type typSample = asmSample.GetType(sTypeName); object objSample = Activator.CreateInstance(typSample); // 定义l对象的必要接口 iwmSample = (IWebMessage)objSample; 获取对象引用后,ProcessMessage Ҏ在 IWebMessage 接口上调?Process ҎQ?br> WebMessageReturn wbrSample; try { // 定义Ҏ调用的参?br> string sLabel = v_mInput.Label; string sBody = (string)v_mInput.Body; int iAppSpecific = v_mInput.AppSpecific; // 调用Ҏq捕捉返回代?br> wbrSample = iwmSample.Process(sLabel, sBody, iAppSpecific); } catch (InvalidCastException ex) { // 如果在消息内容中发生错误Q则强制发出一个非l止异常 throw new CWorkerThreadException(ex.Message, false); } catch (Exception ex) { // 如果错误调用E序集,则强制发出终止异?br> throw new CWorkerThreadException(ex.Message, true); } // 如果没有错误Q则查对象调用的q回状?br>switch (wbrSample) { case WebMessageReturn.ReturnBad: throw new CWorkerThreadException ("Unable to process message: Message marked bad", false); case WebMessageReturn.ReturnAbort: throw new CWorkerThreadException ("Unable to process message: Process terminating", true); default: break; } |