程序员的资源宝库

网站首页 > gitee 正文

ASP.NET asp.net machine account的账户

sanyeah 2024-03-29 17:13:07 gitee 9 ℃ 0 评论

1.委托的异步调用
{
(1)解决窗体假死
(2)多播委托不能异步调用
(3) //异步调用
DelTest del = Test;
//异步调用 async 异步 sync同步
IAsyncResult res = del.BeginInvoke(Callback, null);
(4) //如果执行的时候没有结束 做相应的提示
while (!res.IsCompleted)
{
this.Text += "*";
System.Threading.Thread.Sleep(500);
}

(5) //endinvoke的返回值 就是委托指向的方法的返回值
//获取异步委托执行的结果
//endinvoke等待begininvoke的返回值,又回到同步
string s = del.EndInvoke(res);
MessageBox.Show(s);

(6) //异步委托的回调函数
void Callback(IAsyncResult res)
{
//判断异步执行是否结束
if (res.IsCompleted)
{
MessageBox.Show("异步委托执行完毕");
}
}

}
2.文件流复习
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
namespace _03_文件流
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

//写文件
private void btnWrite_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "文本文件|*.txt";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtPath.Text = sfd.FileName;
using (FileStream fs = new FileStream(txtPath.Text, FileMode.Create))
{
//读取和写入时候使用的编码应该一致,否则会出现乱码的问题
byte[] buffer = Encoding.UTF8.GetBytes(txtWrite.Text);
//把字节数组,放到缓冲区中(内容)
fs.Write(buffer, 0, buffer.Length);

//把缓冲区中的内容写入到文件
//fs.Flush();
//调用了flush 并关闭流
//fs.Close();
}
}
}
//读取
private void btnRead_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "文本文件|*.txt";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtPath.Text = ofd.FileName;

using (FileStream fs = new FileStream(txtPath.Text,FileMode.Open))
{
byte[] buffer = new byte[1024*1024];

//把流中的内容读取到字节数组中
//第二个参数是把流中的内容放到字节数组中的第几个位置,
//第三个参数,是读取流中多少内容

//n 实际读到的字节个数
int n = fs.Read(buffer, 0, buffer.Length);
if (n != 0)
{
txtRead.Text = Encoding.UTF8.GetString(buffer);
}
}
}

}
}
}

}
3.简易摇奖机
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace 摇奖机
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
Thread th;
private void btn_Click(object sender, EventArgs e)
{
if (btn.Text == "开始")
{
isStart = true;
th = new Thread(Award);
th.IsBackground = true;
th.Start();
btn.Text = "结束";
}
else
{
isStart = false;
btn.Text = "开始";
}
}
bool isStart = false;
void Award()
{
Random r = new Random();
while (isStart)
{
label1.Text = r.Next(1, 10).ToString();
label2.Text = r.Next(1, 10).ToString();
label3.Text = r.Next(1, 10).ToString();
label4.Text = r.Next(1, 10).ToString();
label5.Text = r.Next(1, 10).ToString();
label6.Text = r.Next(1, 10).ToString();
Thread.Sleep(50);
}
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (th != null)
{
th.Abort();
}
}
}
}

}
4.Chat聊天室
{
(1)服务器端
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;

namespace SocketChat
{
public partial class 服务器端 : Form
{
//存储通信用的字典 string为IP和端口,scoket为对应的socket对象
Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
int count = 0;//用于限制用户的数量
string fileName;//获取文件名

public 服务器端()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}

/// <summary>
/// 创建监听用的socket
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStart_Click(object sender, EventArgs e)
{
//IP地址
IPAddress ip = IPAddress.Parse(txtServer.Text);

//IP和端口号
IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text));

//监听用的socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

//通常每个套接字地址(协议/网络地址/端口)只允许使用一次。
//绑定IP和端口
socket.Bind(point);
//监听窗口 10的当前时间的排队序列的最大数
socket.Listen(10);
//设置监听按钮不可用
btnStart.Enabled = false;
ShowMsg("开始监听");
//监听端口,如果有客户端连接,创建通信用的socket
//创建线程,防止窗体阻塞
Thread th = new Thread(Listen);
//设为后台线程
th.IsBackground = true;
th.Start(socket);

}

/// <summary>
/// 监听的方法
/// </summary>
/// <param name="o"></param>
void Listen(object o)
{
Socket socket = o as Socket;
//设为死循环,来不停的执行Accept方法
while (count < 100)
{
count++;
//监听端口,如果有客户端连接,创建通信用的socket
Socket connSocket = socket.Accept();
//显示连接成功的客户端的ip地址和端口号
string ipport = connSocket.RemoteEndPoint.ToString();
//显示ip和端口号
ShowMsg(ipport);
//给当前的下拉框添加ip和端口号
cboUsers.Items.Add(ipport);
//给字典添加数据
dic.Add(ipport, connSocket);
//本机的ip地址和端口 connSocket,LocalEndPoint
Thread th = new Thread(RecMsg);
th.IsBackground = true;
th.Start(connSocket);
}
}

/// <summary>
/// 接收消息
/// </summary>
/// <param name="o"></param>
void RecMsg(object o)
{
Socket connSocket = o as Socket;
//这里为死循环是可以多次发送消息,保证不停的执行Receive
while (true)
{
//接收数据
byte[] buffer = new byte[1024 * 1024];
//num为实际接收到的长度,接收数据,放入buffer
int num = -1;
try
{
num = connSocket.Receive(buffer);
//假如num为0的时候表示talnet已经关闭了,这时候关闭socket
if (num == 0)
{
//显示该IP的已经退出
ShowMsg(connSocket.RemoteEndPoint.ToString() + ":退出了");
//关闭socket的接收功能
connSocket.Shutdown(SocketShutdown.Receive);
//关闭socket
connSocket.Close();
//退出循环
break;
}
//显示接收的内容
string str = Encoding.UTF8.GetString(buffer, 0, num);
ShowMsg(connSocket.RemoteEndPoint.ToString() + ":" + str);
}
catch (Exception ex)
{
//显示异常信息并且跳出循环
ShowMsg(ex.Message);
break;
}
}
}

/// <summary>
/// 在log文本框内显示消息
/// </summary>
/// <param name="msg"></param>
void ShowMsg(string msg)
{
txtLog.AppendText(msg + "\r\n");
}

/// <summary>
/// 发送消息 协议首位为0
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
string key = cboUsers.Text.Trim();
if (!string.IsNullOrEmpty(key))
{
byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text.Trim());
List<byte> list = new List<byte>();
list.Add(0);
list.AddRange(buffer);
dic[key].Send(list.ToArray());
}
else
{
ShowMsg("请选择客户端");
}
}

/// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelect_Click(object sender, EventArgs e)
{
//选择文件
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtPath.Text = ofd.FileName;
}
}
/// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendFile_Click(object sender, EventArgs e)
{
//获取下拉框中的客户端的ip和端口
string key = cboUsers.Text.Trim();
if (!string.IsNullOrEmpty(key))
{
using (FileStream fs = new FileStream(txtPath.Text, FileMode.Open))
{
//定义字节数组,长度为文件流中字节数组的长度
byte[] buffer = new byte[fs.Length];
//num为实际读取的字节个数
int num = fs.Read(buffer, 0, buffer.Length);

//添加协议
List<byte> list = new List<byte>();
list.Add(1);//协议位第一位 1 文件 2 消息
//获取文件名名
fileName = Path.GetFileName(txtPath.Text);
//获取文件名的字节数组
byte[] bFilter = Encoding.UTF8.GetBytes(fileName);
//获取文件名的字节数组长度的字节数组
int length = bFilter.Length;
//长度添加进集合
list.Add((byte)length);
//文件名字节数组添加进协议位
list.AddRange(bFilter);
//文件数组添加进集合
list.AddRange(buffer);
//发送
dic[key].Send(list.ToArray());
}
}
else
{
MessageBox.Show("请选择客户端");
}
}
/// <summary>
/// 震动 协议首位为0
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnZD_Click(object sender, EventArgs e)
{
string key = cboUsers.Text.Trim();
if (!string.IsNullOrEmpty(key))
{
List<byte> list = new List<byte>();
list.Add(2);
dic[key].Send(list.ToArray());
}
else
{
MessageBox.Show("请选择客户端");
}
}
}
}
}
(2)客户端
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace SocketChatClient
{
public partial class 客户端 : Form
{
public 客户端()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}

Socket socket;
/// <summary>
/// 连接服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStart_Click(object sender, EventArgs e)
{
//客户端连接服务器的ip地址
IPAddress ip = IPAddress.Parse(txtServer.Text);
//端口
IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text));
//创建socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
//设定连接
socket.Connect(point);
ShowMsg("连接成功");

//接收消息
Thread th = new Thread(RecMsg);
th.IsBackground = true;
th.Start();
}
catch (Exception ex)
{

ShowMsg(ex.Message);
}
}

/// <summary>
/// txtLog文本框显示
/// </summary>
/// <param name="msg"></param>
void ShowMsg(string msg)
{
txtLog.AppendText(msg + "\r\n");
}
/// <summary>
/// 接收消息
/// </summary>
void RecMsg()
{
while (true)
{
byte[] buffer = new byte[1024 * 1024];
try
{
int num = socket.Receive(buffer);
//接收消息,消息中的第一个字节是协议
//读取协议 0 文字 1文件 2震动
int first = buffer[0];
if (first == 0)
{
string str = Encoding.UTF8.GetString(buffer, 1, num - 1);
ShowMsg(socket.RemoteEndPoint.ToString() + ":" + str);
}
else if (first == 1) //文件
{
//读取文件名的长度
int length = buffer[1];
//读取文件名
string fileName = Encoding.UTF8.GetString(buffer, 2, length);
//保存文件
SaveFileDialog sfd = new SaveFileDialog();
//获取文件名
sfd.FileName = Path.GetFileNameWithoutExtension(fileName);
//获取后缀名
sfd.Filter = "|*" + Path.GetExtension(fileName);
if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create))
{
fs.Write(buffer, 2 + length, num - length - 2);
}
}
}
else if (first == 2)
{
Shake();
}
}
catch (Exception ex)
{

ShowMsg(ex.Message);
break;
}
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
//socket==null 说明没有连接服务器
if (socket != null)
{
//发送数据
byte[] bs = Encoding.UTF8.GetBytes(txtMsg.Text.Trim());
socket.Send(bs);
}
else
{
ShowMsg("请先连接");
}
}
int n = -1;
void Shake()
{
for (int i = 0; i < 10; i++)
{
n = -n;
this.Location = new Point(this.Location.X + 5 * n, this.Location.Y + 5 * n);
System.Threading.Thread.Sleep(50);
}
}
}
}

}
}
5.Web服务器
{
1、Form1.cs
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WebServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// 开启监听socket,创建多线程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStart_Click(object sender, EventArgs e)
{
//ip地址
IPAddress ip = IPAddress.Parse(txtIp.Text.Trim());
//ip和端口号
IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text.Trim()));
//创建socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Bind(point);
//监听
socket.Listen(10);
ShowMsg("开始运行");
//接收消息
Thread th = new Thread(Listen);
th.IsBackground = true;
th.Start(socket);
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
/// <summary>
/// txtLog.text显示的信息
/// </summary>
/// <param name="msg"></param>
void ShowMsg(string msg)
{
txtLog.AppendText(msg + "\r\n");
}
/// <summary>
/// 创建连接用socket,多线程
/// </summary>
/// <param name="o">监听socket</param>
void Listen(object o)
{
Socket socket = o as Socket;
while (true)
{
//创建通信用socket
Socket connSocket = socket.Accept();
ShowMsg(connSocket.RemoteEndPoint.ToString() + ":连接成功");

//通过dataconnection的类接收http请求和发送http响应
//构造方法传入通信socket和委托,这个委托有显示的方法
DataConnection dc = new DataConnection(connSocket, ShowMsg);
}
}
}
}

}
2、DataConnection.cs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;

namespace WebServer
{
//创建委托,参数为显示信息的方法
delegate void DelSetTxt(string msg);
/// <summary>
/// 1 接收游览器发送的请求
/// 2向游览器发送响应
/// </summary>
class DataConnection
{
private Socket connSocket;
//实例化委托,要指向窗体中给文本框赋值的方法
private DelSetTxt del;

/// <summary>
/// 构造方法中把通信用的socket还有委托传递过来
/// </summary>
/// <param name="connSocket">通信用的socket </param>
/// <param name="del">实例化类的时候将showMsg方法直接指向委托</param>
public DataConnection(Socket connSocket, DelSetTxt del)
{
this.connSocket = connSocket;
this.del = del;//(del=ShowMsg())
//1. msg为接收的请求报文
string msg = RecMsg();
del(msg); //ShowMsg(msg),显示请求报文

//2 Request类是用来分析http请求报文的
Request req = new Request(msg);

//3.根据请求的路径 判断是静态页面还是动态页面
Judge(req.Url);
}

/// <summary>
/// 判断是静态页面还是动态页面
/// </summary>
/// <param name="url">文件的路径</param>
void Judge(string url)
{
//获得url的后缀名,去除.
string ext = Path.GetExtension(url).TrimStart('.');
switch (ext)
{
case "htm":
case "html":
case "css":
case "jpg":
case "js":
case "gif":
case "png":
//处理静态页面 并做出响应
ProcessStaticPage(url);
break;
case "aspx":
//处理动态页面
ProcessDyPage(url);
break;
default:
break;
}
}

/// <summary>
/// 接收通信用的socket收到的字节信息,转为字符串
/// </summary>
/// <returns></returns>
string RecMsg()
{
//接收消息
byte[] buffer = new byte[1024 * 1024];
//实际接收的字节个数
int num = connSocket.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, num);
return str;
}

/// <summary>
/// 处理静态页面,生成响应头并做出http响应
/// </summary>
/// <param name="url">Request方法得到的url</param>
void ProcessStaticPage(string url)
{
//1.跟据相对路径生成绝对路径

//获取exe所在文件夹的路径
//AppDomain.CurrentDomain.BaseDirectory表示当前程序域的基路径
string exePath = AppDomain.CurrentDomain.BaseDirectory;
//组合生成请求文件的绝对路径
string path = exePath + "web" + url;

//2.判断文件是否存在,然后读取静态页面
if (File.Exists(path))//File.Exists判断文件是否存在
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
try
{
//生成响应头
Response response = new Response(200, buffer.Length, url);
//发送响应头
connSocket.Send(response.GetResponseHeaders());
//发送响应题
connSocket.Send(buffer);
//关闭连接
connSocket.Close();
del("关闭连接");
//send发送数据的时候会等待一个非常短的时间,
//假如再有send,就把这几个send的数据一起发生数据,
//所有2个send其实是一个
}
catch (Exception ex)
{

del(ex.Message);
}
}
}
}
/// <summary>
/// 处理动态页面
/// </summary>
/// <param name="url">Request方法得到的url</param>
void ProcessDyPage(string url)
{
//通过反射创建请求类的对象
//根据字符串(类的全名称 命名空间.类名)创建对应类的对象

//获得文件名
string fileName = Path.GetFileNameWithoutExtension(url);

//获取当前方法所在的类的命名空间 MethodBase指的是当前的方法
//GetCurrentMethod 返回当前执行的方法的对象
//DeclaringType 获得当前方法所在的类
//Namespace 获得这个类的命名空间
string nameSpace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;

//类的全名称
string fullName = nameSpace + "." + fileName;

//GetExecutingAssembly获取当前执行的程序集
//使用CreateInstance方法创建fullname的对象
//反射创建fullname的对象,并且存储到接口中
IHttpHandler handler = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(fullName, true) as IHttpHandler;

//假如接口不为空
if (handler != null)
{
//生成响应体
byte[] buffer = handler.ProcessRequest();
//生成响应头
Response res = new Response(200, buffer.Length, url);

//发送动态页面
connSocket.Send(res.GetResponseHeaders());
connSocket.Send(buffer);
connSocket.Close();
del("关闭连接");
}
else
{
del("404 文件不存在");
}
}
}
}

}
3、Request.cs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebServer
{
/// <summary>
/// 解析请求报文中的url
/// </summary>
class Request
{
/// <summary>
/// 解析msg中的url
/// </summary>
/// <param name="msg">请求报文</param>
public Request(string msg)
{
try
{
//因为http协议严谨按照 不同元素之间有空格,隔行直接由转行,所有用split方法得到元素

//得到隔行的数组元素
string[] arrMsg = msg.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
//第一行是我们需要的
string firstLine = arrMsg[0];
//分割第一行
string[] arr = firstLine.Split(' ');
//第一行的第二个元素就是url
//这里url是属性
url = arr[1];
}
catch (Exception ex)
{
//发生错误,指定一个错误的页面去,上面显示404,请求的页面不存在
url = "";
}

}
private string url;
/// <summary>
/// 请求行中的路径
/// </summary>
public string Url
{
get { return url; }
set { url = value; }
}
}
}

}
4、Response.cs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WebServer
{
/// <summary>
/// 准备响应头
/// </summary>
public class Response
{
//字典中键是状态,值是对应的显示的提示
private Dictionary<int, string> dic = new Dictionary<int, string>();
//状态码,200为正常情况下的状态码
private int statusCode = 200;
//html页面里面内容的长度
private int contentLength;
//html页面里面内容的类型
private string contentType;

/// <summary>
/// 构造方法
/// </summary>
/// <param name="statusCode">状态码</param>
/// <param name="contentLength">html页面里面内容的长度</param>
/// <param name="url">html页面里面内容的url路径</param>
public Response(int statusCode, int contentLength, string url)
{
//填充字典 状态码和状态码的描述
FillDic();
this.statusCode = statusCode;
this.contentLength = contentLength;
GetContentType(url);
}

/// <summary>
/// 生成响应头
/// </summary>
/// <returns>响应头的字节数组</returns>
public byte[] GetResponseHeaders()
{
//准备拼接响应头的sb
StringBuilder sb = new StringBuilder();
//(Status-Line) HTTP/1.1 200 OK 状态行拼接
sb.AppendLine("HTTP/1.1 " + statusCode + " " + dic[statusCode]);
//Content-Length 3989 内容的长度
sb.AppendLine("Content-Length: " + contentLength);
//Content-Type text/html;charset=gbk 内容的类型
sb.AppendLine("Content-Type: " + contentType + ";charset=utf-8\r\n");
//返回拼接好的字符串的字节数组
return Encoding.UTF8.GetBytes(sb.ToString());
}

/// <summary>
/// 根据url给contentType(响应类型)赋值
/// </summary>
/// <param name="url"></param>
void GetContentType(string url)
{
//获得url的后缀
string ext = Path.GetExtension(url);
switch (ext)
{
case ".htm":
case ".html":
contentType = "text/html";
break;
case ".css":
contentType = "text/css";
break;
case ".js":
contentType = "text/javascript";
break;
case ".jpg":
contentType = "image/jpeg";
break;
default:
contentType = "text/html";
break;
}
}

/// <summary>
/// 填充字典,得到状态码和文字描述
/// </summary>
void FillDic()
{
dic.Add(200, "OK");
dic.Add(404, "Not Found");
}
}
}

}
5、IHttpHandler接口
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebServer
{
/// <summary>
/// 让实现了接口的类 能够处理浏览器的请求
/// </summary>
interface IHttpHandler
{
//处理请求并作出响应
byte[] ProcessRequest();
}
}

}
6、NewsDetails动态页面
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebServer
{
//继承至接口
class NewsDetails:IHttpHandler
{
/// <summary>
/// 返回字节数组的动态页面
/// </summary>
/// <returns></returns>
public byte[] ProcessRequest()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<html>");
sb.AppendLine("<head><title>新闻详细页面</title>");
sb.AppendLine("</head>");
sb.AppendLine("<body>");
sb.AppendLine("<center>");
sb.AppendLine("<h3>新闻详细页面。。。。");
sb.AppendLine("</h3>");
sb.AppendLine("<div>我是新闻详细页面" + DateTime.Now.ToString() + "</div>");
sb.AppendLine("</center>");
sb.AppendLine("</body>");
sb.AppendLine("</html>");

return Encoding.UTF8.GetBytes(sb.ToString());
}
}
}

}
}
6.加法计算器
{
(1)HTML模板
}
7.Ajax无刷新登录
{
1.HTML页面
{
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="Scripts/jquery-1.7.1.js"></script>
<script type="text/ecmascript">
//窗体加载的时候
$(function () {
$("#btn").click(function () {
//获得文本框内的值
var name = $("#txtName").val();
var pwd = $("#txtPwd").val();
var code = $("#txtCode").val();
//组装成json数据
var data = { "name": name, "pwd": pwd, "code": code };
//通过Ajax的post方式,到一般处理程序区处理
$.post("01-Login.ashx", data, function (msg) {
//在回调方法内给予提示,局部刷新span标签
//1 登录成功 2用户名不存在 3密码错误 4 验证码错误
if (msg == 1) {
window.location.href = "03-PhotoList.aspx";
}
if (msg == 2) {
$("#msg").text("用户名不存在");
}
if (msg == 3) {
$("#msg").text("密码错误");
}
if (msg == 4) {
$("#msg").text("验证码错误");
}
if (msg == 5) {
$("#msg").text("未知错误");
}
//每次点击事件结束时,调用刷新验证码的方法
ChangeCode();
})
})
})
//刷新验证码的方法
function ChangeCode() {
$("#i1").attr("src","02-ValidateCode.ashx?r="+Math.random());
}
</script>
</head>
<body>
用户名:<input type="text" id="txtName" /><br />
密码:<input type="password" id="txtPwd" /><br />

验证码:<input type="text" id="txtCode" /><img src="02-ValidateCode.ashx" id="i1" alt="点击改变验证码" onclick="ChangeCode()" style="cursor:pointer"/><br />
<input type="button" value="登录" id="btn" /><br />
<span id="msg" style="color:red"></span>
</body>
</html>

}
2.ashx页面
{
<%@ WebHandler Language="C#" Class="_01_Login" %>

using System;
using System.Web;
using System.Web.SessionState;
using MyPhotos.BLL;
using MyPhotos.Model;

public class _01_Login : IHttpHandler,IRequiresSessionState {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
//定义一个msg 1 登录成功 2用户名不存在 3密码错误 4 验证码错误
int msg = -1;
//获得post过来的数据
string name = context.Request.Form["name"];
string pwd = context.Request.Form["pwd"];
string code = context.Request.Form["code"];
//判断验证码是否正确
if (context.Session["code"] != null && code.ToLower() == context.Session["code"].ToString().ToLower())
{
User user;
UserBLL bll = new UserBLL();
//判断是否登录
if (bll.GetUserByUName(name, pwd, out msg, out user))
{
//session方式保持用户对象
context.Session["user"] = user;
}
}
else
{
msg = 4;
}
context.Response.Write(msg);
}

public bool IsReusable {
get {
return false;
}
}

}
}
}
8.Ajax无刷新显示照片列表
{
1.ASPX
{
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="03-PhotoList.aspx.cs" Inherits="_02_PhotoList" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
</style>
<script src="Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">

// 将序列化成json格式的日期(毫秒数)转成日期格式
function ChangeDataeFormat(cellval) {
var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
}

$(function () {
//div里照片列表没有加载完成显示的内容
$("#holder").text("正在加载数据....");
//去一半处理程序去获得json数据 ,加随机数防止读取缓存
$.getJSON("03-PhotoList.ashx?r=" + Math.random(), function (json) {
//清空DIV
$("#holder").text("");
//动态创建table
var $table = $("<table id='photos' cellspacing='opx'></table>");
//把table添加到div中
$("#holder").append($table);
//表头
var $tr = $("<tr><th>序号</th><th>标题</th><th>图片</th><th>点击次数</th><th>支持</th><th>反对</th><th>时间</th><th>操作</th></tr>");

$table.append($tr);

//遍历数组
for (var i = 0; i < json.length; i++) {
$tr = $("<tr></tr>");
$table.append($tr);
//序号
var $td = $("<td>" + (i + 1) + "</td>");
$tr.append($td);
//标题
$td = $("<td><a href='06-PhotoDetail.aspx?pid=" + json[i].PId + "'>" + json[i].PTitle + "</a></td>");
$tr.append($td);
//图片
$td = $("<td><a href='06-PhotoDetail.aspx?pid=" + json[i].PId + "'><img src='09-CreateMiniPhoto.ashx?url="+json[i].PUrl+"'></a></td>");
$tr.append($td);
//点击次数
$td = $("<td>" + json[i].PClicks + "</td>");
$tr.append($td);
//支持,自定义属性PId,保存pid的值
$td = $("<td><a pid='" + json[i].PId + "' href='javascript:void(0)'><img src='85.gif' border='0px'/><span>" + json[i].PUp + "</span></a></td>");

//给支持按钮注册事件
$("a", $td).click(function () {
//获得pid
var pid = $(this).attr("pid");
//当前点击的a标签
var $link = $(this);
//get方式去处理顶的操作,返回字符串
$.get("04-UpClick.ashx?pid=" + pid + "&_=" + Math.random(), function (msg) {
// -1失败 -2请求错误
if (msg != -1 && msg != -2) {
//支持成功
//获取点击次数
//获取a标签中的span标签
var $span = $("span", $link);
//将数据库读取的数据显示
$span.text(msg);

} else {
alert("支持失败");
}
});
//取消a标签后续操作
return false;
})
$tr.append($td);

//反对
$td = $("<td><a pid='" + json[i].PId + "' href='javascript:void(0)'><img src='86.gif' border='0px' /><span>" + json[i].PDown + "</span></a></td>");
//给反对按钮注册事件
$("a", $td).click(function () {
var pid = $(this).attr("pid");
//当前点击的a标签
var $link = $(this);

$.get("05-DownClick.ashx?pid=" + pid + "&_=" + Math.random(), function (msg) {
// -1失败 -2请求错误
if (msg != -1 && msg != -2) {
//支持成功
//获取点击次数
//获取a标签中的span标签
var $span = $("span", $link);
$span.text(msg);

} else {
alert("反对失败");
}
});
return false;
})
$tr.append($td);
//时间,调用ChangeDataeFormat方法
$td = $("<td>" + ChangeDataeFormat(json[i].PTime) + "</td>");
$tr.append($td);
//操作
$td = $("<td>编辑 <a pid='" + json[i].PId + "' href='javascript:void(0)'>删除</a></td>");
//给删除标签注册事件
$("a", $td).click(function () {
var pid = $(this).attr("pid");
$.get("10-DeletePhoto.ashx?pid=" + pid, function (msg) {
if (msg == 1) {
alert("删除成功");
location.href = "03-PhotoList.aspx";
} else {
alert(msg);
}
})
})
$tr.append($td);

}
})
})

</script>
</head>
<body>
<form id="form1" runat="server">
<center>
<h3>照片列表</h3>

<div id="holder"></div>
</center>
</form>
</body>
</html>

}
2.ashx
{
<%@ WebHandler Language="C#" Class="_03_PhotoList" %>

using System;
using System.Web;
using System.Web.Script.Serialization;
using MyPhotos.BLL;
using MyPhotos.Model;
using System.Collections.Generic;

public class _03_PhotoList : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";

PhotosBLL bll = new PhotosBLL();
List<Photos> list = bll.GetAllPhotos();

JavaScriptSerializer jss = new JavaScriptSerializer();
string json =jss.Serialize(list);
context.Response.Write(json);
}

public bool IsReusable {
get {
return false;
}
}

}
}

}
9.无刷新评论
{
1.添加评论
{
//窗体加载事件
$(function () {
//加载评论列表
loadComments();
//给评论按钮注册事件
$("#btnSend").click(function () {
//获得隐藏域的pid 和评论内容
var pid = $("#hdPid").val();
var text = $("#txtReply").val();
//组装成json对象
var data = { "pid": pid, "text": text };
//发给增加评论的一般处理程序
$.post("08-AddComments.ashx", data, function (msg) {
if (msg == "1") {
//加载评论列表
loadComments();
} else {
alert("评论失败");
}
});

})
})
}
2.评论列表
{
//加载评论列表
function loadComments() {
//清空之前的评论
$("#reply").empty();
//根据详细表中的隐藏域的值得到pid
var pid = $("#hdPid").val();
$.getJSON("07-GetComments.ashx?pid=" + pid + "&_=" + Math.random(), function (json) {
for (var i = 0; i < json.length; i++) {
var $table = $("<table class='re'></table>");
$("#reply").prepend($table);

var $tr = $("<tr><td>" + json[i].CText + "</td></tr>");
$table.append($tr);

$tr = $("<tr><td>" + ChangeDateFormat(json[i].CTime) + "</td></tr>");
$table.append($tr);

$tr = $("<tr></tr>");
//支持
$td = $("<td><a pid='" + json[i].PId + "' href='javascript:void(0)'><img src='85.gif' border='0px'/><span>" + json[i].PUp + "</span></a></td>");

//给支持按钮注册事件
$("a", $td).click(function () {
var pid = $(this).attr("pid");
//当前点击的a标签
var $link = $(this);

$.get("04-UpClick.ashx?pid=" + pid + "&_=" + Math.random(), function (msg) {
// -1失败 -2请求错误
if (msg != -1 && msg != -2) {
//支持成功
//获取点击次数
//获取a标签中的span标签
var $span = $("span", $link);
$span.text(msg);

} else {
alert("支持失败");
}
});
return false;
})
$tr.append($td);
$table.append($tr);
}
});
}
}
}
10.无刷新支持和反对
{
{
//支持,自定义属性PId,保存pid的值
$td = $("<td><a pid='" + json[i].PId + "' href='javascript:void(0)'><img src='85.gif' border='0px'/><span>" + json[i].PUp + "</span></a></td>");

//给支持按钮注册事件
$("a", $td).click(function () {
//获得pid
var pid = $(this).attr("pid");
//当前点击的a标签
var $link = $(this);
//get方式去处理顶的操作,返回字符串
$.get("04-UpClick.ashx?pid=" + pid + "&_=" + Math.random(), function (msg) {
// -1失败 -2请求错误
if (msg != -1 && msg != -2) {
//支持成功
//获取点击次数
//获取a标签中的span标签
var $span = $("span", $link);
//将数据库读取的数据显示
$span.text(msg);

} else {
alert("支持失败");
}
});
//取消a标签后续操作
return false;
})
$tr.append($td);
}

//一般处理程序
{
<%@ WebHandler Language="C#" Class="_04_UpClick" %>

using System;
using System.Web;
using MyPhotos.BLL;
using MyPhotos.Model;

public class _04_UpClick : IHttpHandler
{
// -1失败 -2请求错误
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
PhotosBLL pBLL = new PhotosBLL();

string s = context.Request.QueryString["pid"];
int pid;
if (int.TryParse(s, out pid))
{
if (pBLL.UpdateUpClick(pid))
{
Photos p = pBLL.GetPhotoByPid(pid);
if (p != null)
{
context.Response.Write(p.PUp.ToString());
}
}
else
{
context.Response.Write("-1");
}
}
else
{
context.Response.Write("-2");
}
}

public bool IsReusable
{
get
{
return false;
}
}

}
}
}

 

 

 

 

 

 

 

 

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表