zoukankan      html  css  js  c++  java
  • WebDev.WebServer 学习

         自从Vs2005起,Vs开发环境便自带了WebDev.WebServer,就是这个图标,它实际上是一个小型的Web服务器,专用于.net平台。大家经常调试程序它还是相当的方便,经过小小的配置就可以指向某个文件夹,使该文件夹成为网站目录已供访问。
        WebDev.WebServer确实很轻便,同时它本身是.net程序,才2个文件,作为测试和演示环境是非常的好用,在xp也能很好的运行,Xp的IIS5实在是不方便用。
        但是自带的WebDev.WebServer只能用于本机,那是因为MS对其进行了限制,因为作出它的目的,本身是为了Vs的开发更方便而已,但是很多测试也是基于网络的,至少你不希望别人测试一些网站,总得来用你的电脑吧。
        WebDev.WebServer一共是两个文件,一个是WebDev.WebServer.exe,另一个是WebDev.WebHost.dll,另外说一下WebDev.WebServer是安装开发环境才有的,不是安装.net framework里面的东东,所以你提取这两个文件都需要已经安装有开发环境下来进行。

     新建一个项目 StartExamples

    在Program类中加入以下代码:

     internal static class Program
        {
            [STAThread]
            
    private static void Main(string[] args)
            {
                
    string currentDirectory = Environment.CurrentDirectory;
                
    string appName = "";
                ProcessParameters(args, 
    ref currentDirectory, ref appName);

                
    string devServerExecutable = GetDevServerExecutable(CheckQsf40(currentDirectory));
                
    string portNumber = GetPortNumber();

                
    if (!File.Exists(devServerExecutable)){
                    Console.WriteLine(
    "Cannot find the ASP.NET Development Server!");
                }
    else{
                    StartProcess(devServerExecutable, portNumber, currentDirectory, appName);
                }
            }
            
    private static void ProcessParameters(string[] args, ref string physPath, ref string appName)
            {
                
    foreach (string str in args)
                {
                    
    if (str.StartsWith("-path:", StringComparison.OrdinalIgnoreCase))
                    {
                        physPath 
    = str.Remove(06);
                    }
                    
    else if (str.StartsWith("-appname:", StringComparison.OrdinalIgnoreCase))
                    {
                        appName 
    = str.Remove(09);
                    }
                    
    else if (str.StartsWith("-help", StringComparison.OrdinalIgnoreCase) || str.StartsWith("-?", StringComparison.OrdinalIgnoreCase))
                    {
                        ShowHelp();
                    }
                }
            }
            
    private static void ShowHelp()
            {
                MessageBox.Show(
    "Usage: {0} [-path:<path to root of web>] [-appname:/<name of web application>]"
                    Application.ExecutablePath.Substring(Application.ExecutablePath.LastIndexOf(
    @"\"+ 1));
            }
            
    private static string GetDevServerExecutable(bool check40)
            {
                
    string str = string.Empty;
                
    string path = string.Empty;
                
    if (check40)
                {
                    path 
    = string.Format(@"{0}\Microsoft Shared\DevServer\10.0\WebDev.WebServer40.exe", Environment.GetEnvironmentVariable("CommonProgramFiles"));
                    
    if (File.Exists(path)){
                        str 
    = path;
                    }
    else{
                        path 
    = string.Format(@"{0}\Microsoft Shared\DevServer\10.0\WebDev.WebServer40.exe", Environment.GetEnvironmentVariable("CommonProgramFiles(x86)"));
                        
    if (File.Exists(path)){
                            str 
    = path;
                        }
                    }
                }
                
    if (str.Length == 0){
                    path 
    = string.Format(@"{0}\Microsoft Shared\DevServer\10.0\WebDev.WebServer20.exe", Environment.GetEnvironmentVariable("CommonProgramFiles"));
                    
    if (File.Exists(path)){
                        str 
    = path;
                    }
    else{
                        path 
    = string.Format(@"{0}\Microsoft Shared\DevServer\10.0\WebDev.WebServer20.exe", Environment.GetEnvironmentVariable("CommonProgramFiles(x86)"));
                        
    if (File.Exists(path)){
                            str 
    = path;
                        }
                    }
                }
                
    if (str.Length == 0){
                    path 
    = string.Format(@"{0}\Microsoft Shared\DevServer\9.0\WebDev.WebServer.exe", Environment.GetEnvironmentVariable("CommonProgramFiles"));
                    
    if (File.Exists(path)){
                        str 
    = path;
                    }
    else{
                        path 
    = string.Format(@"{0}\Microsoft Shared\DevServer\9.0\WebDev.WebServer.exe", Environment.GetEnvironmentVariable("CommonProgramFiles(x86)"));
                        
    if (File.Exists(path)){
                            str 
    = path;
                        }
                    }
                }
                
    if (str.Length != 0){
                    
    return str;
                }
                
    string str3 = "50727";
                RegistryKey key 
    = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework\policy\v2.0");
                
    if ((key != null&& (key.ValueCount > 0)){
                    str3 
    = key.GetValueNames()[0];
                }
    else{
                    MessageBox.Show(
    "Error while reading .NET Framework 2.0 configuration! Assuming default values.");
                }
                
    return string.Format(@"{0}\Microsoft.NET\Framework\v2.0.{1}\WebDev.WebServer.exe", Environment.GetEnvironmentVariable("WINDIR"), str3);
            }
            
    private static bool CheckQsf40(string physPath)
            {
                
    string path = physPath + @"\Web.Config";
                
    if (File.Exists(path)){
                    StreamReader reader 
    = new StreamReader(path);
                    
    string str2 = reader.ReadToEnd();
                    reader.Close();
                    
    return (str2.IndexOf("System.Data.Linq, Version=4.0.0.0"!= -1);
                }
                
    return false;
            }
            
    private static string GetPortNumber()
            {
                
    bool flag = false;
                TcpListener listener 
    = null;
                
    int port = 0;
                
    try
                {
                    listener 
    = new TcpListener(IPAddress.Any, 0x206d);
                    listener.ExclusiveAddressUse 
    = true;
                    listener.Start();
                    port 
    = ((IPEndPoint)listener.LocalEndpoint).Port;
                    listener.Stop();
                }
                
    catch (SocketException)
                {
                    flag 
    = true;
                }
                
    if (flag)
                {
                    
    try
                    {
                        listener 
    = new TcpListener(IPAddress.Any, 0);
                        listener.Start();
                        port 
    = ((IPEndPoint)listener.LocalEndpoint).Port;
                        listener.Stop();
                    }
                    
    catch (Exception)
                    {
                    }
                }
                
    if (port == 0)
                {
                    port 
    = 0x206d;
                }
                
    return port.ToString();
            }
            
    private static void StartProcess(string cassiniExecutable, string portNumber, string physPath, string appName)
            {
                Process process 
    = new Process();
                process.StartInfo.FileName 
    = cassiniExecutable;
                process.StartInfo.WindowStyle 
    = ProcessWindowStyle.Hidden;
                process.StartInfo.Arguments 
    = string.Format("/port:{0} /path:\"{1}\" /vpath:\"{2}\"", portNumber, physPath, appName);
                process.Start();
                
    new WaitMessageForm().ShowDialog();
                Process process2 
    = new Process();
                process2.StartInfo.UseShellExecute 
    = true;
                process2.StartInfo.FileName 
    = string.Format("http://localhost:{0}{1}", portNumber, appName);
                process2.Start();
            }
        }

    在StartExamples项目中加入 WaitMessageForm 窗体加入以下代码

    public class WaitMessageForm : Form
    {
        
    private IContainer components;
        
    private Label label1;

        
    public WaitMessageForm()
        {
            
    this.InitializeComponent();
        }
        
    private void InitializeComponent()
        {
            ComponentResourceManager manager 
    = new ComponentResourceManager(typeof(WaitMessageForm));
            
    this.label1 = new System.Windows.Forms.Label();
            
    this.SuspendLayout();
            
    // 
            
    // label1
            
    // 
            this.label1.AutoSize = true;
            
    this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            
    this.label1.Location = new System.Drawing.Point(2626);
            
    this.label1.Name = "label1";
            
    this.label1.Size = new System.Drawing.Size(51720);
            
    this.label1.TabIndex = 0;
            
    this.label1.Text = "Please wait while the ASP.NET Development Server is started...";
            
    this.label1.UseWaitCursor = true;
            
    // 
            
    // WaitMessageForm
            
    // 
            this.AccessibleDescription = "ASP.NET Development server loader";
            
    this.AccessibleName = "Start Examples";
            
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
            
    this.AutoScaleDimensions = new SizeF(6f, 13f);
            
    this.AutoScaleMode = AutoScaleMode.Font;


            
    this.CausesValidation = false;
            
    this.ClientSize = new System.Drawing.Size(57570);
            
    this.ControlBox = false;
            
    this.Controls.Add(this.label1);
            
    this.FormBorderStyle = FormBorderStyle.None;
            
    this.Name = "WaitMessageForm";
            
    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            
    this.Text = "Loading...";
            
    this.UseWaitCursor = true;
            
    this.ResumeLayout(false);
            
    this.PerformLayout();

        }
        
    protected override void OnLoad(EventArgs e)
        {
            
    base.OnLoad(e);
            Timer timer 
    = new Timer();
            timer.Interval 
    = 0xfa0;
            timer.Tick 
    += new EventHandler(this.closeTimer_Tick);
            timer.Start();
        }
        
    private void closeTimer_Tick(object sender, EventArgs e)
        {
            ((Timer)sender).Stop();
            ((Timer)sender).Dispose();
            
    base.Close();
        }
        
    protected override void Dispose(bool disposing)
        {
            
    if (disposing && (this.components != null))
            {
                
    this.components.Dispose();
            }
            
    base.Dispose(disposing);
        }
        

    } 

     运行效果

     

    快速启动WebDev.WebServer的方法

    直接通过文件夹的快捷菜单来启动WebDev.WebServer。

    简单来说就是建立一个注册表文件,写入下列内容:

    Windows Registry Editor Version 5.00

    [HKEY_LOCAL_MACHINESOFTWAREClassesFoldershellVS2005 WebServer]
    @="启动Web服务器"

    [HKEY_LOCAL_MACHINESOFTWAREClassesFoldershellVS2005 WebServercommand]
    @="C:\Windows\Microsoft.NET\Framework\v2.0.50727\Webdev.WebServer.exe /port:8080 /path:"%1""

      注意这里是依照安装了VS2005的情况,如果是VS2008的话,Webdev.WebServer.exe的目录变了,应当做如下改写:

    [HKEY_LOCAL_MACHINESOFTWAREClassesFoldershellVS2008 WebServer]
    @="启动Web服务器"

    [HKEY_LOCAL_MACHINESOFTWAREClassesFoldershellVS2008 WebServercommand]
    @="C:\Program Files\Common Files\Microsoft Shared\DevServer\9.0\Webdev.WebServer.exe /port:8080 /path:"%1""

      如果安装VS的时候没有选择默认的安装目录,请自行修改以上内容。

      建立这个注册表文件以后,只要双击写入到注册表就可以了,想要启动,只要在文件夹上单击右键就OK了。

    快速启动WebDev.WebServer的方法快速启动WebDev.WebServer的方法

      这个时候可以看到Webdev.WebServer已经启动,打开浏览器就可以访问了。

      

    见可以写一个bat文件,内容为:
    set path=%path%;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
    WebDev.WebServer.EXE /path:”C:\Inetpub\wwwroot”
    这样每次启动就比较方便了。
     

    作者:罗敏贵
    邮箱:minguiluo@163.com
    QQ群:34178394 建群 主要是寻找志同道合的人士一起学习和讨论自己的所学所思
    出处:http://luomingui.cnblogs.com/
    说明:专注于微软平台项目架构、熟悉设计模式、架构设计、敏捷个人和项目管理。现主要从事WinForm、ASP.NET、等方面的项目开发、架构、管理工作。文章为作者平时里的思考和练习,可能有不当之处,请博客园的园友们多提宝贵意见。
    知识共享许可协议本作品采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可。

  • 相关阅读:
    swig编译GDAL的C#库时遇到的代码安全问题及解决方法
    AE + GDAL实现影像按标准图幅分割(下)
    AE + GDAL实现影像按标准图幅分割(上)
    ArcEngine保存栅格数据至rastercatalog
    通过日志解决问题的一个小例子-http换端口
    firewall-cmd命令的富语言(richlanguage)示例
    VMware空虚拟机通过网络安装系统时获取不到IP地址情况(基于Linux的DHCP服务器)
    Linux中tune2fs命令的-o选项
    date -d
    tmp/ 和 var/tmp/ 的区别
  • 原文地址:https://www.cnblogs.com/luomingui/p/2104477.html
Copyright © 2011-2022 走看看