使用WCF实现消息推送

 
使用WCF实现消息推送
1.协议
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace WCFHub.IService { [ServiceContract(CallbackContract=typeof(IEventCallback))] public interface IEventService { [OperationContract(IsOneWay = true)] void Subscribe(SubscribeArg a); [OperationContract(IsOneWay = true)] void Unsubscribe(ArgumentBase a); [OperationContract] DateTime Ping(); } public interface IEventCallback { [OperationContract(IsOneWay = true)] void OnMessageReceived(ArgumentBase a); } }
复制代码
 
2.实现
0
复制代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Concurrent; using System.ServiceModel; using System.ServiceModel.Channels; namespace WCFHub.IService { public class EventServiceImpl:IEventService { public static readonly ConcurrentDictionary<string, subscribecontext=""> _Subscribers = new ConcurrentDictionary<string, subscribecontext="">(); public string ClientIpAndPort() { OperationContext context = OperationContext.Current; MessageProperties properties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; return endpoint.Address + ":" + endpoint.Port.ToString(); } public void Subscribe(SubscribeArg a) { Console.WriteLine(ClientIpAndPort()); var callback = OperationContext.Current.GetCallbackChannel(); a.Username=a.Username.ToLower(); _Subscribers[a.Username]=new SubscribeContext(){Arg=a,Callback=callback}; #region 事件处理 ICommunicationObject obj = (ICommunicationObject)callback; obj.Closed += (s,e) => { Console.WriteLine("Closed"); }; obj.Faulted += (s, e) => { Console.WriteLine("Faulted"); }; obj.Closing += (s,e) => { Console.WriteLine("Closeing" + OperationContext.Current); var callback2=(IEventCallback)s; _Subscribers.ToList().ForEach(ent => { if (ent.Value.Callback == callback2) { RemoveSubscriber(ent.Value.Arg.Username); } }); }; #endregion } public void Unsubscribe(ArgumentBase a) { RemoveSubscriber(a.Model); } private static void RemoveSubscriber(string username) { username = username.ToLower(); if (_Subscribers.ContainsKey(username)) { SubscribeContext outObj = null; _Subscribers.TryRemove(username, out outObj); } } public static void PostData(ArgumentBase a) { Console.WriteLine("收到待发消息:" + a.Model); _Subscribers.ToList().ForEach(subscriber => { ICommunicationObject callback = (ICommunicationObject)subscriber.Value.Callback; if (((ICommunicationObject)callback).State == CommunicationState.Opened) { try { //此处需要加上权限判断、订阅判断等 subscriber.Value.Callback.OnMessageReceived(a); } catch (Exception ex) { RemoveSubscriber(subscriber.Value.Arg.Username); Console.WriteLine("PostData:" + ex.Message); } } else { RemoveSubscriber(subscriber.Value.Arg.Username); Console.WriteLine("PostData,用户链接已经关闭"); } }); } #region IEventService 成员 public DateTime Ping() { Console.WriteLine("Ping:" + ClientIpAndPort() +"," +DateTime.Now); return DateTime.Now; } #endregion } public class SubscribeContext { public SubscribeArg Arg { get; set; } public IEventCallback Callback { get; set; } } }
复制代码
 
3.实体类
0
复制代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WCFHub.IService { [Serializable] public class ArgumentBase { private int code; private string msg; private T model; public int Code { get { return code; } set { code = value; } } public string Msg { get { return msg; } set { msg = value; } } public T Model { get { return model; } set { model = value; } } } public class SubscribeArg : ArgumentBase { public String Username { get; set; } public List Alarms { get; set; } public SubscribeArg() { Alarms = new List(); } } }
复制代码
 
4.服务托管
0
复制代码
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.ServiceModel; using WCFHub.IService; namespace WCFHub.Win { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private ServiceHost _Host = new ServiceHost(typeof(EventServiceImpl)); private void Form1_Load(object sender, EventArgs e) { _Host.AddServiceEndpoint(typeof(IEventService), new NetTcpBinding(SecurityMode.None), "net.tcp://192.168.30.30:9999/EventService" ); _Host.Open(); Console.WriteLine("服务开启..."); } protected override void OnClosed(EventArgs e) { _Host.Close(); base.OnClosed(e); Console.WriteLine("服务关闭!"); } private void button1_Click(object sender, EventArgs e) { var data = new ArgumentBase() { Model = textBox1.Text + "," + DateTime.Now.ToString() }; EventServiceImpl.PostData(data); } } }
复制代码
 
5.客户端
0
复制代码
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 WCFHub.IService; using System.ServiceModel; using System.Threading; namespace WCFHub.WinClient { #region MessageReceive public delegate void MessageReceivedHandle(ArgumentBase a); public class NotifyManager : IEventCallback { public event MessageReceivedHandle MessageReceived; public static int C_MaxErrCount = 5; public static int C_HeartbeatInterval = 1000 * 10;//10秒一次心跳检测 IEventService _Proxy = null; private int ErrCounter = 0; public bool Enabled { get; set; } public NotifyManager() { Enabled = false; } private void Close() { if (_Proxy != null) { try { var comObj = _Proxy as ICommunicationObject; comObj.Abort(); } catch { } } } public void Start() { Enabled = true; StartInternal(); #region 心跳检测 var timer = new System.Timers.Timer(); timer.Enabled = false; timer.Interval = C_HeartbeatInterval; timer.Elapsed += (s, ie) => { try { WriteLine("心跳检测..."); timer.Enabled = false; _Proxy.Ping(); ErrCounter = 0; } catch (Exception ex) { WriteLine(ex.Message); ErrCounter++; if (ErrCounter >= C_MaxErrCount) { Close(); StartInternal(); } } finally { timer.Enabled = true; } }; timer.Start(); #endregion } private void StartInternal() { if (!Enabled) return; lock (this) { try { #region ErrCounter = 0; _Proxy = WCFHelper.Factory.CreateChannel(new InstanceContext(this)); var comObj = _Proxy as ICommunicationObject; comObj.Faulted += (s, ie) => { WriteLine("Faulted"); }; comObj.Closed += (s, ie) => { WriteLine("Closed!"); }; comObj.Closing += (s, ie) => { WriteLine("Closing!"); }; WriteLine("加载并配置完成!"); _Proxy.Subscribe(new SubscribeArg() { Username = Guid.NewGuid().ToString("N") }); WriteLine("注册成功!"); #endregion } catch (Exception ex) { WriteLine(ex.Message); } } } public void Stop() { Enabled = false; Close(); } public void WriteLine(string msg) { Console.WriteLine(msg + "," + DateTime.Now); } #region IEventCallback 成员 public void OnMessageReceived(ArgumentBase a) { if (MessageReceived != null) { MessageReceived(a); } } #endregion } #endregion public partial class Form1 : Form { private SynchronizationContext SyncContext = null; public Form1() { InitializeComponent(); SyncContext = SynchronizationContext.Current; } NotifyManager _NotifyManager = null; private void Form1_Load(object sender, EventArgs e) { _NotifyManager = new NotifyManager(); _NotifyManager.MessageReceived += OnMessageReceived; _NotifyManager.Start(); } protected override void OnClosed(EventArgs e) { if (_NotifyManager != null) { _NotifyManager.MessageReceived -= this.OnMessageReceived; _NotifyManager.Stop(); } base.OnClosed(e); } public void OnMessageReceived(ArgumentBase a) { Console.WriteLine("收到消息:" + a.Model +",InvokeRequired:" + this.InvokeRequired); if (this.InvokeRequired) { SyncContext.Post((d) => { textBox1.Text += a.Model + Environment.NewLine; }, null); } else { textBox1.Text += a.Model + Environment.NewLine; } } private void button1_Click(object sender, EventArgs e) { if (_NotifyManager != null) { Console.WriteLine((_NotifyManager as ICommunicationObject).State); } } } public class WCFHelper { private static DuplexChannelFactory _channelFac; public static DuplexChannelFactory Factory { get { if (_channelFac == null) { _channelFac = new DuplexChannelFactory(typeof(NotifyManager), new NetTcpBinding(SecurityMode.None), EndpointStr); } return _channelFac; } } private static string EndpointStr { get { return "net.tcp://192.168.30.30:9999/EventService"; } } } }
复制代码
 
标签: WCF消息推送
c# 使用多线程 匿名函数 
#region 事件
 
        Thread twork;
 
        protected override void OnLoad(EventArgs e)
 
        {
 
            base.OnLoad(e);
 
            twork = new Thread(DoWork);
 
            twork.Start();
 
        }
 
 
 
        protected override void OnHandleDestroyed(EventArgs e)
 
        {
 
            base.OnHandleDestroyed(e);
 
            if (twork!=null)
 
            {
 
                twork.Abort();
 
                twork.Join();
 
            }
 
        }
 
        #endregion
 
 
 
        #region 私有方法
 
        private void DoWork()
 
        {
 
            while (true)
 
            {
 
                if (this.FindForm() != null) //控件加载出来了 需要进行数据刷新操作
 
                {
 
                    //执行数据刷新操作
 
                    GetData();
 
                }
 
                Thread.Sleep(PublicDim.RealCarRefreshTime);
 
            }
 
        }
 
        private CarRecords carRecords = null;
 
        private void GetData()
 
        {
 
            if (qwSelectBayonet.SelectCodeList != null && qwSelectBayonet.SelectCodeList.Count > 0)
 
            {
 
                ArrayOfString arr=new ArrayOfString();
 
                foreach (string code in qwSelectBayonet.SelectCodeList)
 
                {
 
                    arr.Add(code);
 
                }
 
 
 
                #region 同步方式
 
                //List<extend_cliententity> listRealData = null;
 
                //try
 
                //{
 
                //    listRealData = PublicDim.WebserviceClient.GetRealTimeCarDataByRoadCodes_Extend_Client(arr);
 
                //}
 
                //catch(Exception ex)
 
                //{ }
 
 
 
                //if (listRealData != null && listRealData.Count > 0)
 
                //{
 
                //    List<extend_cliententity> listShow = listRealData.Take(200).Skip(0).ToList();
 
                //    if (listRealData!=null)
 
                //    {
 
                //        listRealData.Clear();
 
                //        listRealData = null;
 
                //    }
 
                //    GC.Collect();
 
                //    qpRealContent.Invoke((EventHandler)(delegate
 
                //    {
 
                //        if (carRecords != null)
 
                //        {
 
                //            carRecords.ClearAndRealease();
 
                //            carRecords.CloseWorkThread();
 
                //            carRecords.UpdateData();
 
                //        }
 
                //        else
 
                //        {
 
                //            qpRealContent.Controls.Clear();
 
                //            carRecords = new CarRecords();
 
                //            carRecords.IsReal = true;
 
                //            carRecords.ListRealData = listShow; //listRealData;
 
                //            carRecords.Height = qpRealContent.Height;
 
                //            carRecords.Width = qpRealContent.Width;
 
                //            qpRealContent.Controls.Add(carRecords);
 
                //            carRecords.Anchor = PublicDim.ControlsAnchor;
 
                //        }
 
                //    }));
 
                //}
 
                #endregion 
 
 
 
                #region 异步方式
 
                PublicDim.WebserviceClient.GetRealTimeCarDataByRoadCodes_Extend_ClientCompleted += WebserviceClient_GetRealTimeCarDataByRoadCodes_Extend_ClientCompleted;
 
                PublicDim.WebserviceClient.GetRealTimeCarDataByRoadCodes_Extend_ClientAsync(arr);
 
                #endregion
 
            }
 
        }
线程池
在C#编程语言中,使用线程池可以并行地处理工作,当强制线程和更新进度条时,会使用内建架构的ThreadPool类,为批处理使用多核结构,这里我们来看在C#编程语言中一些关于来自System.Threading的ThreadPool的用法的例子。
介绍
.NET Framework提供了包含ThreadPool类的System.Threading 空间,这是一个可直接访问的静态类,该类对线程池是必不可少的。它是公共“线程池”设计样式的实现。对于后台运行许多各不相同的任务是有用的。对于单个的后台线种而言有更好的选项。
线程的最大数量。这是完全无须知道的。在.NET中ThreadPool的所有要点是它自己在内部管理线程池中线程。多核机器将比以往的机器有更多的线程。微软如此陈述“线程池通常有一个线程的最大数量,如果所有的线程都忙,增加的任务被放置在队列中直到它们能被服务,才能作为可用的线程。”
用法位置
线程池类型能被用于服务器和批处理应用程序中,线程池有更廉价的得到线程的内部逻辑,因为当需要时这些线程已被形成和刚好“连接”,所以线程池风格代码被用在服务器上。
MSDN表述:“线程池经常用在服务器应用程序中,每一个新进来的需求被分配给一个线程池中的线程,这样该需求能被异步的执行,没有阻碍主线程或推迟后继需求的处理。”
ThreadPool  VS  BackgroundWorker
如果你正在使用Windows窗体,宁可使用BackgroundWorker来对付那些更简单的线程需求,BackgroundWorker在网络访问和其他一些简单的事情方面做得很好。但对于多处理器的批处理来说,你需要ThreadPool。
当你的程序要批处理时,考虑线程池
当你的程序产生很多(3个以上)线程时,考虑线程池
当你的程序使用Windows窗体时,考虑后台执行。
线程要考虑的事 同样,如何使用线程的细节能帮助发现最好的代码。下面比较线程情形和哪个类是最好的。
   你需要一个额外的线程   使用后台执行
   你有许多短期的线程     使用线程池 
需求
线程很重要,但对于那些不会花很长时间来执行且只做一件事情的大多数应用程序来说却并不重要的。线程对于界面可用性不是很重要的的应用程序而言也不是很重要,要尽量避免使用线程(译者注:比如进度条不是很重要的应用程序)。
连接方法
可使用QueueUserWorkItem连接方法(methods)到线程池。方法要运行在线程上,则必须把它连接到QueueUserWorkItem。如何实现呢?必须使用WaitCallback。在MSDN中,WaitCallback被描述成当线程池执行时要被调用的委托回调方法,是回调它的参数的委托。
WaitCallback
只需指定“new WaitCallback”语句作为ThreadPool.QueueUserWorkItem的第一个参数来使用WaitCallback.不需要任何其他的代码来使用这方法生效。
使用WaitCallback[c#]的例子
 
  1. void Example()  
  2.   
  3. {  
  4.   
  5.     // 连接 ProcessFile 方法到线程池.  
  6.   
  7.     //注意: 'a' 是一个作为参数的对象  
  8.   
  9.     ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessFile), a);  
  10.   
  11. }  
  12.   
  13. private void ProcessFile(object a)  
  14.   
  15. {  
  16.   
  17.     // 我被连接到线程池通过 WaitCallback.  
  18.   
  19. }  
 
 
 
参数
我们能通过定义一个特定的类并把一些重要的值放在类里面来使用参数,那么,方法接收了对象,就能通过对象向方法传递多个参数了。以下是一个早期的例子。
使用带参数QueueUserWorkItem 的例子[c#]
 
  1. //指定作为线程池方法的参数的类  
  2.   
  3. class ThreadInfo  
  4.   
  5. {  
  6.   
  7.     public string FileName { get; set; }  
  8.   
  9.     public int SelectedIndex { get; set; }  
  10.   
  11. }  
  12.   
  13. class Example  
  14.   
  15. {  
  16.   
  17.     public Example()  
  18.   
  19.     {  
  20.   
  21. // 声明一个新的参数对象  
  22.   
  23. ThreadInfo threadInfo = new ThreadInfo();  
  24.   
  25. threadInfo.FileName = "file.txt";  
  26.   
  27. threadInfo.SelectedIndex = 3;  
  28.   
  29. //发送自定义的对象到线程方法  
  30.   
  31. ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessFile), threadInfo);  
  32.   
  33.     }  
  34.   
  35.     private void ProcessFile(object a)  
  36.   
  37.     {  
  38.   
  39. ThreadInfo threadInfo = a as ThreadInfo;  
  40.   
  41. string fileName = threadInfo.FileName;  
  42.   
  43. int index = thread.SelectedIndex;  
  44.   
  45.     }  
  46.   
  47. }  
 
 
 
发生了什么事?我们发送两个值给这个线程化的ProcessFile方法,它需要知道文件名和选择索引,而我们在这个对象中把参数都发送了给它。
进度条
能通过从设计器中右边的工具盒面板中增加Windows窗体控件到你的窗体程序来使用进度条并设置 progressBar1.Value, progressBar1.Minimum 和progressBar1.Maximum。 progressBar1.Value是最小值和最大值中间的位置,以下代码用来初始化进度条:
设置进度条的例子 [C#]
 
  1. //设置进度条的长度.  
  2.   
  3. // 这里我们有6个单位来完成,所以6是最大值。  
  4.   
  5. // 最小值通常是0  
  6.   
  7. progressBar1.Maximum = 6; // 或其他数字  
  8.   
  9. progressBar1.Minimum = 0;  
 
 
 
进度条位置 你的进度条中的有颜色部分是当前值与最大值的百分比。所以,如果最大值是6,而值是3即表示做完了一半。
在进度条中调用Invoke(援引)
让我们看如何在进度条实例中使用Invoke方法。遗憾的是,你不能在辅助线程中访问Windows控件,因为UI线程是分离的,必须使用委托(delegate)和Invoke到进度条。
请求Invoke(调用)的例子[C#]
 
  1. public partial class MainWindow : Form  
  2.   
  3. {  
  4.   
  5. // 这是运行在UI线程来更新条的委托  
  6.   
  7.  public delegate void BarDelegate();  
  8.   
  9. //该窗体的构造器(由Visual Studio自己产生)  
  10.   
  11.     public MainWindow()  
  12.   
  13.     {  
  14.   
  15. InitializeComponent();  
  16.   
  17.     }  
  18.   
  19. //当按下按钮,启动一个新的线程  
  20.   
  21.     private void button_Click(object sender, EventArgs e)  
  22.   
  23.     {  
  24.   
  25. // 设定进度条的长度.  
  26.   
  27. progressBar1.Maximum = 6;  
  28.   
  29. progressBar1.Minimum = 0;  
  30.   
  31. // 给线程传递这些值.  
  32.   
  33. ThreadInfo threadInfo = new ThreadInfo();  
  34.   
  35. threadInfo.FileName = "file.txt";  
  36.   
  37. threadInfo.SelectedIndex = 3;  
  38.   
  39. ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessFile), threadInfo);  
  40.   
  41.     }  
  42.   
  43. // 运行在后台线程上的东西  
  44.   
  45.  private void ProcessFile(object a)  
  46.   
  47.     {  
  48.   
  49. // (省略)  
  50.   
  51. // 使用'a'做一些重要的事.  
  52.   
  53. // 告诉UI 我们已经完成了.  
  54.   
  55. try  
  56.   
  57. {  
  58.   
  59.     // 在窗体中调用委托 .  
  60.   
  61.     this.Invoke(new BarDelegate(UpdateBar));  
  62.   
  63. }  
  64.   
  65. catch  
  66.   
  67. {  
  68.   
  69.            //当一些问题发生后我们能使程序恢复正常  
  70.   
  71. }  
  72.   
  73.     }  
  74.   
  75.     //更新进度条.  
  76.   
  77.     private void UpdateBar()   
  78.   
  79.     {  
  80.   
  81. progressBar1.Value++;  
  82.   
  83. if (progressBar1.Value == progressBar1.Maximum)  
  84.   
  85. {  
  86.   
  87.     // 结束了,进度条满了.  
  88.   
  89. }  
  90.   
  91.     }  
  92.   
  93. }  
 
 
 
委托语法 以上代码的开始处,可以看到声明 UpdateBar 的委托。它告诉Visual Studio 和C# 需要来使用这个作为对象的方法。
更多需要的工作 以上程序演示了如何设定进度条的最大值和最小值,如何在工作完成后“Invoke”委托方法来增加进度条的大小。
在调试器中的线程
 这儿要显示如何在Visual Studio的调试器中查看线程。一旦你有一个运行的程序,你能采取这些措施来可视化你的线程。首先,以调试模式打开你的线程应用程序,一旦你的应用程序运行在调试器,告知它去做它的工作而且运行这些线程,通过绿色箭头运行调试器,当线程正在运行,在工具条中单击“pause"按钮。
下一步 调试>窗口>线程.该菜单项将打开一个类似下图的窗口,你能看见有多少线程正在线程池中运行。
0
 
四个辅助线程 上图显示了共有10个线程,但只有四个辅助线程(Worker Thread)在程序中被分配给MainWindow.ProcessFile.
约束辅助线程
如果你有一个双核或四核系统,你将考虑最多两个四个很费力的线程。我们能在运行的线程中保持一个_threadCount 字段并且跟踪它的数值。用这个线程计数字段,你将需要在C#语言中使用一个锁来避免造成这个字段读和写的错误,锁保护你的线程被其他线程所改变。
计数线程的例子 [C#]
 
  1. // 锁住这个对象.  
  2.   
  3. readonly object _countLock = new object();  
  4.   
  5. private void ProcessFile(object argument)  
  6.   
  7. {  
  8.   
  9. // 约束辅助线程的数量  
  10.   
  11. while (true)  
  12.   
  13.     {  
  14.   
  15. lock (_countLock)  
  16.   
  17. {  
  18.   
  19.     if (_threadCount < 4)  
  20.   
  21.     {  
  22.   
  23. // Start the processing  
  24.   
  25. _threadCount++;  
  26.   
  27. break;  
  28.   
  29.     }  
  30.   
  31. }  
  32.   
  33. Thread.Sleep(50);  
  34.   
  35.     }  
  36.   
  37.     // Do work...  
  38.   
  39. }  
 
 
 
我们看到什么 以是代码是异步执行的方法。只有其他辅助线程少于4个时它才会工作。这对于一个四核机器是好的。请看描述锁声明的更多上下文的文章
控制线程计数器
你可以在ThreadPool上使用SetMinThreads 来在连发活动中提高吞吐量和性能。以下是关于可使用的最佳的最小线程数量的材料。
总结
我们了解了如何在C#程序中使用线程池来有效管理多个线程,在Windows 窗体应用程序的进度条和用户界面中能给人留很深印象并且也不难实现。然而,线程带来了很多的复杂性并导致漏洞,线程池是一个有用的简化,但它仍然是困难的。
本文将向大家讲述如何使用系统自定义鼠标样式和使用图片鼠标样式。设置鼠标重要利用窗体一个属性 this.Cursor (当能当前代码在窗体类中)。
1 :使用系统自带鼠标样式 this.Cursor = Cursors.Cross;当能Cursors当中有众多的鼠标样式如向四个方向的箭头,十字架等
2 :使用图片作为鼠标样式,这个可是本文的关键了
①  首先定义一个Bitmap对象,如:
Bitmap bmp=new Bitmap("cursor.png");//cursor.png是你应用程序目录下的一张图片当能还支持jpg gif格式
② 创建一个鼠标对象
Cursor cursor = new Cursor(bmp.GetHicon());
  this.Cursor = cursor;
③ 完成。是不是很简单!去试试你的效果吧!
获取系统信息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Web;
 
namespace WebApplication2
{
///
/// SystemInfo 的摘要说明
///
public class SystemInfo : IHttpHandler
{
public string CpuID; //CPU的ID
public int CpuCount; //CPU的个数
public string[] CpuMHZ;//CPU频率 单位:hz
public string MacAddress;//计算机的MAC地址
public string DiskID;//硬盘的ID
public string DiskSize;//硬盘大小 单位:bytes
public string IpAddress;//计算机的IP地址
public string LoginUserName;//操作系统登录用户名
public string ComputerName;//计算机名
public string SystemType;//系统类型
public string TotalPhysicalMemory; //总共的内存 单位:M
 
public void ProcessRequest(HttpContext context)
{
CpuID = GetCpuID();
CpuCount = GetCpuCount();
CpuMHZ = GetCpuMHZ();
MacAddress = GetMacAddress();
DiskID = GetDiskID();
DiskSize = GetSizeOfDisk();
IpAddress = GetIPAddress();
LoginUserName = GetUserName();
SystemType = GetSystemType();
TotalPhysicalMemory = GetTotalPhysicalMemory();
ComputerName = GetComputerName();
 
context.Response.ContentType = "text/plain";
context.Response.Write("CpuID:"+ CpuID);
context.Response.Write("\r\n");
context.Response.Write("CpuCount:" + CpuCount);
context.Response.Write("\r\n");
context.Response.Write("CpuMHZ:" + CpuMHZ);
context.Response.Write("\r\n");
context.Response.Write("MacAddress:" + MacAddress);
context.Response.Write("\r\n");
context.Response.Write("DiskID:" + DiskID);
context.Response.Write("\r\n");
context.Response.Write("DiskSize:" + DiskSize);
context.Response.Write("\r\n");
context.Response.Write("IpAddress:" + IpAddress);
context.Response.Write("\r\n");
context.Response.Write("LoginUserName:" + LoginUserName);
context.Response.Write("\r\n");
context.Response.Write("SystemType:" + SystemType);
context.Response.Write("\r\n");
context.Response.Write("TotalPhysicalMemory:" + TotalPhysicalMemory);
context.Response.Write("\r\n");
context.Response.Write("ComputerName:" + ComputerName);
context.Response.Write("\r\n");
}
 
public bool IsReusable
{
get
{
return false;
}
}
 
string GetCpuID()
{
try
{
//获取CPU序列号代码
string cpuInfo = " ";//cpu序列号
ManagementClass mc = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
}
moc = null;
mc = null;
return cpuInfo;
}
catch
{
return "unknow ";
}
finally
{
}
 
}
public static int GetCpuCount()
{
try
{
using (ManagementClass mCpu = new ManagementClass("Win32_Processor"))
{
ManagementObjectCollection cpus = mCpu.GetInstances();
return cpus.Count;
}
}
catch
{
}
return -1;
}
public static string[] GetCpuMHZ()
{
ManagementClass mc = new ManagementClass("Win32_Processor");
ManagementObjectCollection cpus = mc.GetInstances();
 
string[] mHz = new string[cpus.Count];
int c = 0;
ManagementObjectSearcher mySearch = new ManagementObjectSearcher("select * from Win32_Processor");
foreach (ManagementObject mo in mySearch.Get())
{
mHz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString();
c++;
}
mc.Dispose();
mySearch.Dispose();
return mHz;
}
public static string GetSizeOfDisk()
{
ManagementClass mc = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moj = mc.GetInstances();
foreach (ManagementObject m in moj)
{
return m.Properties["Size"].Value.ToString();
}
return "-1";
}
string GetMacAddress()
{
try
{
//获取网卡硬件地址
string mac = " ";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
mac = mo["MacAddress"].ToString();
break;
}
}
moc = null;
mc = null;
return mac;
}
catch
{
return "unknow ";
}
finally
{
}
 
}
string GetIPAddress()
{
try
{
//获取IP地址
string st = " ";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
//st=mo[ "IpAddress "].ToString();
System.Array ar;
ar = (System.Array)(mo.Properties["IpAddress"].Value);
st = ar.GetValue(0).ToString();
break;
}
}
moc = null;
mc = null;
return st;
}
catch
{
return "unknow ";
}
finally
{
}
 
}
string GetDiskID()
{
try
{
//获取硬盘ID
String HDid = " ";
ManagementClass mc = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
HDid = (string)mo.Properties["Model"].Value;
}
moc = null;
mc = null;
return HDid;
}
catch
{
return "unknow ";
}
finally
{
}
 
}
///
/// 操作系统的登录用户名
///
///
string GetUserName()
{
try
{
string st = " ";
ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
 
st = mo["UserName"].ToString();
 
}
moc = null;
mc = null;
return st;
}
catch
{
return "unknow ";
}
finally
{
}
 
}
string GetSystemType()
{
try
{
string st = " ";
ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
 
st = mo["SystemType"].ToString();
 
}
moc = null;
mc = null;
return st;
}
catch
{
return "unknow ";
}
finally
{
}
 
}
string GetTotalPhysicalMemory()
{
try
{
 
string st = " ";
ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
 
st = mo["TotalPhysicalMemory"].ToString();
 
}
moc = null;
mc = null;
return st;
}
catch
{
return "unknow ";
}
finally
{
}
}
string GetComputerName()
{
try
{
return System.Environment.GetEnvironmentVariable("ComputerName");
}
catch
{
return "unknow ";
}
finally
{
}
}
}
}
C#压缩
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestAPP
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "dfsdfsdfsdfasdfasdfasdfasdfasdfasdfasdfasd";
            Console.WriteLine("s:"+s);
 
            s = Compress(s);
            Console.WriteLine("s1:" + s);
 
            s = Compress(s);
            Console.WriteLine("s2:" + s);
 
            s = Decompress(s);
            Console.WriteLine("s20:" + s);
 
            s = Decompress(s);
            Console.WriteLine("s10:" + s);
 
            Console.ReadKey();
        }
 
        ///
        /// 压缩字节数组
        ///
        ///
        public static byte[] Compress(byte[] inputBytes)
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                using (GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress, true))
                {
                    zipStream.Write(inputBytes, 0, inputBytes.Length);
                    zipStream.Close(); //很重要,必须关闭,否则无法正确解压
                    return outStream.ToArray();
                }
            }
        }
 
        ///
        /// 解压缩字节数组
        ///
        ///
        public static byte[] Decompress(byte[] inputBytes)
        {
 
            using (MemoryStream inputStream = new MemoryStream(inputBytes))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    using (GZipStream zipStream = new GZipStream(inputStream, CompressionMode.Decompress))
                    {
                        zipStream.CopyTo(outStream);
                        zipStream.Close();
                        return outStream.ToArray();
                    }
                }
 
            }
        }
 
        ///
        /// 压缩字符串
        ///
        ///
        ///
        public static string Compress(string input)
        {
            byte[] inputBytes = Encoding.Default.GetBytes(input);
            byte[] result = Compress(inputBytes);
            return Convert.ToBase64String(result);
        }
 
        ///
        /// 解压缩字符串
        ///
        ///
        ///
        public static string Decompress(string input)
        {
            byte[] inputBytes = Convert.FromBase64String(input);
            byte[] depressBytes = Decompress(inputBytes);
            return Encoding.Default.GetString(depressBytes);
        }
 
        ///
        /// 压缩目录
        ///
        ///
        public static void Compress(DirectoryInfo dir)
        {
            foreach (FileInfo fileToCompress in dir.GetFiles())
            {
                Compress(fileToCompress);
            }
        }
 
        ///
        /// 解压缩目录
        ///
        ///
        public static void Decompress(DirectoryInfo dir)
        {
            foreach (FileInfo fileToCompress in dir.GetFiles())
            {
                Decompress(fileToCompress);
            }
        }
 
        ///
        /// 压缩文件
        ///
        ///
        public static void Compress(FileInfo fileToCompress)
        {
            using (FileStream originalFileStream = fileToCompress.OpenRead())
            {
                if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                {
                    using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
                    {
                        using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                        {
                            originalFileStream.CopyTo(compressionStream);
                        }
                    }
                }
            }
        }
 
        ///
        /// 解压缩文件
        ///
        ///
        public static void Decompress(FileInfo fileToDecompress)
        {
            using (FileStream originalFileStream = fileToDecompress.OpenRead())
            {
                string currentFileName = fileToDecompress.FullName;
                string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
 
                using (FileStream decompressedFileStream = File.Create(newFileName))
                {
                    using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                    {
                        decompressionStream.CopyTo(decompressedFileStream);
                    }
                }
            }
        }
    }
}
获取HTTP内容!
public static string GetWebContent(string URL)
 
        {
 
            WebRequest req = WebRequest.Create(URL);
 
            req.Method = "GET";   //指定提交的Method,可以为POST和GET,一定要大写  
 
            WebResponse res = req.GetResponse();
 
            //System.Text.Encoding resEncoding = System.Text.Encoding.GetEncoding("utf8");//接收的编码   "gb2312"
 
            StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8); //resEncoding
 
            string content = reader.ReadToEnd();     //接收的Html  
 
            reader.Close();
 
            res.Close();
 
            return content;
 
        }
C# 判断url存在 下载url byte[]
public static byte[] GetWebContent(string URL)
{
WebClient client = new WebClient();
return client.DownloadData(URL);
}
 
private static bool UrlIsExist(String url)
{
System.Uri u = null;
try
{
u = new Uri(url);
}
catch { return false; }
bool isExist = false;
System.Net.HttpWebRequest r = System.Net.HttpWebRequest.Create(u)
as System.Net.HttpWebRequest;
r.Method = "HEAD";
try
{
System.Net.HttpWebResponse s = r.GetResponse() as System.Net.HttpWebResponse;
if (s.StatusCode == System.Net.HttpStatusCode.OK)
{
isExist = true;
}
}
catch (System.Net.WebException x)
{
try
{
isExist = ((x.Response as System.Net.HttpWebResponse).StatusCode !=
System.Net.HttpStatusCode.NotFound);
}
catch { isExist = (x.Status == System.Net.WebExceptionStatus.Success); }
}
return isExist;
}
c# json序列化反序列化
using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Text;
 
using System.Web.Script.Serialization; // 此命名空间对应的框架是 System.Web.Extensions
 
 
 
namespace ConsoleApplication1
 
{
 
    class Program
 
    {
 
        static JavaScriptSerializer serializer = new JavaScriptSerializer();
 
        static void Main(string[] args)
 
        {
 
            //序列化测试
 
            testjsonobject[] arrjsonobject=new testjsonobject[2];
 
            arrjsonobject[0] = new testjsonobject() { id = "1", name = "name1" };
 
            arrjsonobject[1] = new testjsonobject() { id = "1", name = "name1" };
 
 
            string jsonResult=serialization(arrjsonobject);
 
            Console.WriteLine("对象序列化后的结果:"+jsonResult);
 
 
            //反序列化测是
 
            testjsonobject[] obj=deserialization<testjsonobject[]>(jsonResult);
 
            if (obj != null)
 
            {
 
                Console.WriteLine("字符串反序列化后的对象:"+obj.ToString());
 
            }
 
            else
 
            {
 
                Console.WriteLine("字符串反序列化失败!");
 
            }
 
            
 
            Console.Read();
 
            
 
        }
 
 
 
        ///
 
        /// json 序列化
 
        ///
 
        ///
 
        static string serialization(testjsonobject[] arrjsonobject)
 
        {
 
            StringBuilder sb = new StringBuilder();
 
            serializer.Serialize(arrjsonobject, sb);
 
            return sb.ToString();
 
        }
 
        ///
 
        /// jason反序列化
 
        ///
 
        ///
 
        static T deserialization(string jsonString)
 
        {
 
            return serializer.Deserialize(jsonString);
 
        }
 
    }
 
 
 
    public class testjsonobject
 
    {
 
        public string id
 
        {
 
            get;
 
            set;
 
        }
 
 
        public string name
 
        {
 
            get;
 
            set;
 
        }
 
 
    }
 
}
 
 
C# WebClient实现采集
C#提交表单:
分类: C#2011-11-15 11:03 7115人阅读 评论(2) 收藏 举报
C#的提交表单方式主要有两种WebClient与HttpWebRequest,这里先介绍一种
 
 
  1. string postString = "arg1=a&arg2=b";//这里即为传递的参数,可以用工具抓包分析,也可以自己分析,主要是form里面每一个name都要加进来  
  2. byte[] postData = Encoding.UTF8.GetBytes(postString);//编码,尤其是汉字,事先要看下抓取网页的编码方式  
  3. string url = "http://localhost/register.php";//地址  
  4. WebClient webClient = new WebClient();  
  5. webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可  
  6. byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流  
  7. string srcString = Encoding.UTF8.GetString(responseData);//解码  
 
 
各位刚做网站的要注意了,如果自己的网页需要注册登录之类的,赶紧加个验证码吧,自动注册机、论坛灌水机等的都是用的类似的原理。
不过想当年自己选课的时候靠的就是这个啊,这也算是计算机系的优势吧!!!
大笑
 
分类: C#2011-11-19 23:21 8740人阅读 评论(3) 收藏 举报
上次介绍了用WebClient的方式提交POST请求,这次,我继续来介绍用其它一种方式
 
自认为与上次介绍的WebClient最大的不同之处在于HttpWebRequest更灵活,也更强大,比如,HttpWebRequest支持Cookie,而WebClient就不支持,因此,如果要登录某个网站才能进行某些操作的时候,HttpWebResponse就派上用场了。
 
补充:
WebClient是可以操作Cookie的,因为Cookie本质上就是个字符串,只要服务器返回的头是“SetCooie:xxx”,所以,按照返回的格式做下处理(不能原样返回,具体可以抓包分析下格式),存起来,然后在HTTP请求头上加上“Cookie:xxx”即可
 
首先要提下Referer还有Cookie
Referer:就是一般在浏览器中发送Http请求时带的头信息,被广泛用来统计点击信息,即从那个点击而来,所以有些网站也会用这个性质来防盗链,很多时候如果什么图片仅限内部交流之类的,就是用了这个原理。
Cookie:某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密),通常大家登录的时候就要用到它,登录后,网站会储存一个Cookie的东西在本地计算机上,然后每次访问网站时,便会把这个网站的Cookie也一并发送过去,服务器就凭借这个来确认你的身份。它是个重要信息,有些黑客也会通过盗取Cookie的方式来侵入你的账户。
 
好了,现在开始具体说明:
 
  1. HttpWebRequest request = (HttpWebRequest)WebRequest.Create("POST请求的地址");  
  2. request.CookieContainer = new CookieContainer();  
  3. CookieContainer cookie = request.CookieContainer;//如果用不到Cookie,删去即可  
  4. //以下是发送的http头,随便加,其中referer挺重要的,有些网站会根据这个来反盗链  
  5. request.Referer = “http://localhost/index.php”;  
  6. request.Accept = "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";  
  7. request.Headers["Accept-Language"] = "zh-CN,zh;q=0.";  
  8. request.Headers["Accept-Charset"] = "GBK,utf-8;q=0.7,*;q=0.3";  
  9. request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1";  
  10. request.KeepAlive = true;  
  11. //上面的http头看情况而定,但是下面俩必须加  
  12. request.ContentType = "application/x-www-form-urlencoded";  
  13. request.Method = "POST";  
  14.   
  15. Encoding encoding = Encoding.UTF8;//根据网站的编码自定义  
  16. byte[] postData = encoding.GetBytes(postDataStr);//postDataStr即为发送的数据,格式还是和上次说的一样  
  17. request.ContentLength = postData.Length;  
  18. Stream requestStream = request.GetRequestStream();  
  19. requestStream.Write(postData, 0, postData.Length);  
  20.   
  21. HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
  22. Stream responseStream = response.GetResponseStream();  
  23. //如果http头中接受gzip的话,这里就要判断是否为有压缩,有的话,直接解压缩即可  
  24. if (response.Headers["Content-Encoding"] != null && response.Headers["Content-Encoding"].ToLower().Contains("gzip"))  
  25. {  
  26.     responseStream = new GZipStream(responseStream, CompressionMode.Decompress);  
  27. }  
  28.   
  29. StreamReader streamReader = new StreamReader(responseStream, encoding);  
  30. string retString = streamReader.ReadToEnd();  
  31.   
  32. streamReader.Close();  
  33. responseStream.Close();  
  34.   
  35. return retString;  
 
 
 
当然,请注意,我只是把知识与大家分享,不是让大家去做损害他人网站的事。
反过来,作为Web开发人员,也要明白,不能相信客户端发送来的数据总是合法的,也不能以为他人只能通过浏览器来访问网站,上面就是个例子
而作为防范,验证码之类的可以防范大部分人了~只是,也别以为有了验证码就能防住所有人了,欲知后事如何,请听下回分解~
vb调用C#写的com组件.note.note
Set obj = CreateObject("ForceAnalyzer.FC")
MsgBox (obj.Test("ccc"))
MsgBox ("Hello")
C# 类方法 现实已过时Obsolete
using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
A a = new A(); // Warning
a.F(); // Error
}
}
 
//[Obsolete("This class is obsolete; use class B instead")]
[Obsolete]
class A
{
[Obsolete("This function is obsolete", false)]
//[Obsolete]
public void F() { }
}
 
[Obsolete]
class B
{
public void F() { }
}
}
 
posted @ 2020-12-23 21:04  devgis  阅读(382)  评论(0编辑  收藏  举报