Fork me on GitHub

2015年3月

为什么Visual Studio不能在调试时使用lambda表达式

一、引子

相信很多人都有这样的经历,在Visual Studio的Watch窗口中查看一个List类型的变量,如果这个List中的元素太多,有时想使用LINQ的Where方法筛选一下,类似于下图中的代码:

code

假设我们断在图示断点所在位置,这时我们在Watch窗口中查看personList变量是没问题的,但是如果我只想查看满足Age==20personList,则会看到Visual Studio提示错误:Expression cannot contain lambda expressions

watch

这个问题一直困扰我很久,为什么在Visual Studio中不能在Watch窗口中使用lambda表达式呢?今天忍不住Google了一把,才发现这并不是我一个人的需求,网上有大把大把的人表示不理解为什么Visual Studio不提供这一功能,以至于Visual Studio官方的uservoice上积累了将近一万人的投票,建议Visual Studio引入这个功能。并且好消息是,在Visual Studio最新的2015版本中终于加入了这一特性。

二、原因初探

查看在uservoice下面的回复,我意识到为什么这一特性姗姗来迟,原来是因为这确实是一件很复杂的事。在Stackoverflow上也有很多相关的提问,其中有一篇JaredPar在评论中给出了很精彩的回复。我将他的回复原文摘抄下来放在下面:

No you cannot use lambda expressions in the watch / locals / immediate window. As Marc has pointed out this is incredibly complex. I wanted to dive a bit further into the topic though. What most people don't consider with executing an anonymous function in the debugger is that it does not occur in a vaccuum. The very act of definining and running an anonymous function changes the underlying structure of the code base. Changing the code, in general, and in particular from the immediate window, is a very difficult task. Consider the following code.

void Example() {
  var v1 = 42;
  var v2 = 56; 
  Func<int> func1 = () => v1;
  System.Diagnostics.Debugger.Break();
  var v3 = v1 + v2;
}

This particular code creates a single closure to capture the value v1. Closure capture is required whenever an anonymous function uses a variable declared outside it's scope. For all intents and purposes v1 no longer exists in this function. The last line actually looks more like the following

var v3 = closure1.v1 + v2;

If the function Example is run in the debugger it will stop at the Break line. Now imagine if the user typed the following into the watch window

(Func<int>)(() => v2);

In order to properly execute this the debugger (or more appropriatel the EE) would need to create a closure for variable v2. This is difficult but not impossible to do. What really makes this a tough job for the EE though is that last line. How should that line now be executed? For all intents and purposes the anonymous function deleted the v2 variable and replaced it with closure2.v2. So the last line of code really now needs to read

var v3 = closure1.v1 + closure2.v2;

Yet to actually get this effect in code requires the EE to change the last line of code which is actually an ENC action. While this specific example is possible, a good portion of the scenarios are not. What's even worse is executing that lambda expression shouldn't be creating a new closure. It should actually be appending data to the original closure. At this point you run straight on into the limitations ENC. My small example unfortunately only scratches the surface of the problems we run into. I keep saying I'll write a full blog post on this subject and hopefully I'll have time this weekend.

大意是讲由于lambda表达式涉及到了C#的闭包,而由于C#闭包的特性,导致在调试时如果在Watch窗口中输入lambda表达式将会修改原有代码结构,这并不是不可能,但是确实是一件非常困难且巨大的工程。

三、理解C#的lambda表达式和闭包

好奇心驱使我使用.NET Reflector查看了一下生成的exe文件,看到了下面这样的代码:

[CompilerGenerated]
private static bool <Main>b__0(Person x)
{
    return x.Age < 20;
}

[CompilerGenerated]
private static void <Main>b__1(Person x)
{
    Console.WriteLine(x.Name);
}

private static void Main(string[] args)
{
    personList.Where<Person>(Program.<Main>b__0).ToList<Person>().ForEach(Program.<Main>b__1);
    Console.Read();
}

可以看到lambda表达式被转换成了带有[CompilerGenerated]特性的静态方法,这也就意味着如果我们在调试的时候在Watch中每写一个lambda表达式,Visual Studio都需要动态的创建一个新的静态方法出来然后重新编译。这恐怕是最简单的情形,对调试器而言只是插入一个新的方法然后重新编译而已,Visual Studio已经支持运行时修改代码了,所以这种情形实现起来应该是没问题的。但是复杂就复杂在并不是每个lambda表达式都是这样简单,闭包特性的引入使得lambda表达式中的代码不再只是上下文无关的一个静态方法了,这使得问题变得越来越有意思。我们看下面的示例代码,其中用到了C#的闭包特性:

static void TestOne()
{
    int x = 1, y = 2, z = 3;
    Func<int> f1 = () => x;
    Func<int> f2 = () => y + z;
    Func<int> f3 = () => 3;

    x = f2();
    y = f1();
    z = f1() + f2();

    Console.WriteLine(x + y + z);
}

再看反编译的代码:

[CompilerGenerated]
private sealed class <>c__DisplayClass6
{
    // Fields
    public int x;
    public int y;
    public int z;

    // Methods
    public int <TestOne>b__4()
    {
        return this.x;
    }

    public int <TestOne>b__5()
    {
        return this.y + this.z;
    }
}

[CompilerGenerated]
private static int <TestOne>b__6()
{
    return 3;
}

private static void TestOne()
{
    <>c__DisplayClass6 CS$<>8__locals7 = new <>c__DisplayClass6();
    CS$<>8__locals7.x = 1;
    CS$<>8__locals7.y = 2;
    CS$<>8__locals7.z = 3;
    Func<int> f1 = new Func<int>(CS$<>8__locals7.<TestOne>b__4);
    Func<int> f2 = new Func<int>(CS$<>8__locals7.<TestOne>b__5);
    Func<int> f3 = new Func<int>(Program.<TestOne>b__6);
    CS$<>8__locals7.x = f2();
    CS$<>8__locals7.y = f1();
    CS$<>8__locals7.z = f1() + f2();
    Console.WriteLine((int) (CS$<>8__locals7.x + CS$<>8__locals7.y + CS$<>8__locals7.z));
}

从生成的代码可以看到编译器帮我们做了很多事情,lambda表达式只是语法糖而已。简单的lambda表达式被转换成带有[CompilerGenerated]特性的静态方法,使用闭包特性的lambda表达式被转换成带有[CompilerGenerated]特性的封装(sealed)类,并将所有涉及到的局部变量移到该类中作为该类的public字段,表达式本身移到该类中作为该类的public方法。而且下面所有对闭包涉及到的变量的操作都转换成了对类的字段的操作。 所以回到上文中JaredPar给出的解释,当我们在调试器中输入lambda表达式(Func)(() => v2)时可能存在两种不同的解决方法:

  1. 该方法中已经存在一个闭包,则需要将v2变量提到该闭包类中,并添加一个() => v2方法;
  2. 新建一个闭包类,将v2变量移到该类中,并添加一个() => v2方法;

但是这还远远不够,所有涉及到v2变量的操作,都需要调整为类似于CS$<>8__locals7.v2这样的代码,哦,想想就觉得好麻烦。

四、解决方法

先不谈Visual Studio 2015已经引入这个特性吧,我还没尝试过,也不知道是怎么实现的。暂时我还是在用Visual Studio 2010,所以如果想在老版本中提供这样的功能,就得另谋他策。下面是一些已知的解决方法,我仅是记下来而已,也没尝试过,等试过再写篇新博客记录下吧。

  1. 使用动态LINQ 参考链接中列出了一些动态LINQ的实现,其中用的比较多的应该是Scott提供的LINQ动态查询库,这样在调试时可以使用personList.Where("Age = @0", 20)来替代personList.Where(x => x.Age == 20)
  2. 使用一个VS的开源插件:Extended Immediate Window for Visual Studio
  3. 升级成Visual Studio 2015 ;-)

参考

  1. Allow the evaluation of lambda expressions while debugging
  2. VS debugging “quick watch” tool and lambda expressions
  3. 闭包在.NET下的实现,编译器玩的小把戏
  4. C#与闭包
  5. LINQ to SQL实战 动态LINQ的几种方法
  6. Extended Immediate Window for Visual Studio (use Linq, Lambda Expr in Debugging)
扫描二维码,在手机上阅读!

PHP的类自动加载机制

假设我们有一个php文件需要引用5个不同的类文件,可能会写出下面这样的代码:

require_once ("A.php");
require_once ("B.php");
require_once ("C.php");
require_once ("D.php");
require_once ("E.php");

$a = new A();
$b = new B();
$c = new C();
$d = new D();
$e = new E();

随着类的增多,文件之间依赖关系的复杂化,这里的require也会越来越多,程序员在编写代码的时候很容易忘记或者漏掉某个require,而且在每个php文件中都大量充斥着这种代码,看着真心累。 在PHP5中为这个问题提供了一个解决方案,这就是类的自动加载机制(autoload),这个机制可以使得程序在真正使用某个类时才开始加载这个类,所以也可以叫做类的延迟加载(lazy loading)。PHP提供了两种方法来达到这个目的:

  1. __autoload方法
  2. SPL的autoload机制

使用__autoload方法,可以将类名和所需要的类文件建立一个映射关系,一般情况是让类名和文件名保持一致,让PHP自动的去加载这些类。一个典型的__autoload方法如下:

function __autoload($classname) {
    require_once ($classname . ".php");
}
 
$a = new A();
$b = new B();
$c = new C();
$d = new D();
$e = new E();

参考

  1. php _autoload自动加载类与机制分析
  2. PHP自动加载__autoload的工作机制
  3. PHP的类自动加载机制
  4. PHP SPL,被遗落的宝石
扫描二维码,在手机上阅读!

通过FiddlerScript实现根据条件重发请求

Fiddler是个强大的Web调试工具,具体的功能不在此多述,可以参考后面的链接以及Fiddler官网的手册。本文主要介绍Fiddler的重发请求功能,并通过自定义脚本实现根据条件来重发请求。 在进行Web调试时,经常会遇到浏览器请求正常但是程序请求异常的情况,这时我们常常需要使用Fiddler对比这两个请求的异同,然后将一个请求改变参数或HTTP头进行重发来查看返回结果的差异,这样可以确定哪个参数或哪个HTTP头导致的问题。如下图重发可以有多种不同的选择,常用的有三个:

  1. Reissue Requests: 直接重发选定请求
  2. Reissue and Edit: 重发选定请求,并在请求之前断点,可以对请求进行修改
  3. Reissue from Composer: 将选定请求送到Composer窗口,和将请求拖拽到Composer效果是一样的,在Composer窗口中可以对请求有更精确的控制

replay

只简单的重发指定请求,或在指定请求上进行编辑往往是不够的,在项目中我们偶尔会遇到这样的情形:先发送请求A,然后根据请求A结果中的某个值来发送请求B,譬如有这样的两个接口:get_random_server.php接口通过接收的数据随机返回一个服务器ID,get_data.php接口则根据刚刚的服务器ID来获取数据。下面是一个示例:

  1. localhost/get_random_server.php?data=Hello -> 返回JSON结果:{ success: true, sid: 2 }
  2. localhost/get_data.php?sid=2

这个时候Fiddler的可扩展性就能大显神威了,可以通过两种方式实现Fiddler的扩展:FiddlerScript和插件机制,这里使用FiddlerScript就足够应付了。在Fiddler的菜单项Rules中选择Customize Rules...就可以打开Fiddler的自定义脚本文件CustomRules.js,该脚本一般保存在\Documents\Fiddler2\Scripts目录下。我推荐使用Fidder ScriptEditor进行脚本的编辑,Fidder ScriptEditor具有语法高亮和语法检查的功能,并在右侧面板提供了Fiddler内置的函数列表。 通过展开浏览右侧的函数列表,就基本上可以大概的了解到几个可能会用到的函数了:

  1. FiddlerApplication.oProxy.SendRequest
  2. FiddlerApplication.oProxy.SendRequestAndWait
  3. FiddlerObject.utilIssueRequest

我们先通过下面的代码来练练手,将下面的代码拷贝到CustomRules.js中并保存,Fidder ScriptEditor会自动检查语法错误,并重新加载脚本,无需重启Fiddler脚本即可生效。CustomRules.js使用的是JScript.Net语法,对于Javascipt或.C#程序员应该可以很快上手。这时在Fiddler中随便选择一条请求,点击右键,会发现最上面多了一个选择项Test Send Request,选择该项可以达到和Reissue Requests同样的功能,重发指定请求。

    public static ContextAction("Test Send Request")
    function SendRequest(oSessions: Session[]) {
        
        if (oSessions.Length == 0) return;
        FiddlerApplication.Log.LogString("Sending...");
        
        var selected: Session = oSessions[0];
        
        var oSD = new System.Collections.Specialized.StringDictionary();
        var res = FiddlerApplication.oProxy.SendRequestAndWait(selected.oRequest.headers, selected.RequestBody, oSD, null);
        FiddlerApplication.Log.LogString("Request has been Send.");
        FiddlerApplication.Log.LogString(res.GetResponseBodyAsString());
    }

SendRequest/SendRequestAndWait函数有一个不方便之处,他的两个参数oHeadersarrRequestBodyBytes分别是HTTPRequestHeadersByte[]类型,为了调用这个方法必须将HTTP的header和body转换为这两个类型,不如字符串来的简便。这个时候utilIssueRequest函数正好满足我们的定制需要,可以精确的控制一个请求的细节,类似于Composer中的Raw。下面的代码是一个使用utilIssueRequest函数的实例,具体的HTTP请求以字符串的形式拼接起来。

    public static ContextAction("Probe this!")
    function ProbeSession(oSessions: Session[]) {
        
        if (oSessions.Length == 0) return;
        FiddlerApplication.Log.LogString("Probing...");
        
        var selected: Session = oSessions[0];
        var raw = "";
        
        // methods
        var method:String = selected.RequestMethod;
        var url:String = selected.fullUrl;
        var protocol = "HTTP/1.1";
        FiddlerApplication.Log.LogString(method + " " + url + " " + protocol);
        raw += method + " " + url + " " + protocol + "\r\n";
        
        // headers
        for (var i:int = 0; i < selected.oRequest.headers.Count(); i++) {
            var header = selected.oRequest.headers[i];
            FiddlerApplication.Log.LogString(header);
            raw += header + "\r\n";
        }
        
        // body
        FiddlerApplication.Log.LogString("---");
        var body = selected.GetRequestBodyAsString();
        FiddlerApplication.Log.LogString(body);
        raw += "\r\n" + body;
        
        FiddlerObject.utilIssueRequest(raw);
        FiddlerApplication.Log.LogString("Request has been Send.");
    }

HTTP请求的格式如下:

POST http://localhost/get_random_server.php HTTP/1.1
Host: localhost
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 23

data=%E4%BD%A0%E5%A5%BD

后面的工作就水到渠成了,通过SendRequestAndWait获取请求A的结果,解析请求A结果获取sid参数,然后拼接HTTP请求调用utilIssueRequest函数,此处从略。

参考

  1. FiddlerScript Editor
  2. Search Sequential Pages for Target String
  3. HTTP协议详解
  4. Fiddler 教程
扫描二维码,在手机上阅读!

WebRequest.Create报异常:The specified registry key does not exist

在Visual Studio中调试网络程序时经常报下面这样的异常,异常的类型是IOException,内容为The specified registry key does not exist,展开里面的详情更是一头雾水,不知道到底是什么错误,而且这个异常只会报一次,后面的请求都是正常。

io_exception

今天忍不住Google了一把,才明白原来是.Net Framework的一次安全更新(MS12-074)导致的,要避免每次都无厘头的抛这样的异常也很简单,向注册表中添加一条记录LegacyWPADSupport即可。 32位版本:

Registry location: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework  
DWORD (32-bit) Value name: LegacyWPADSupport
Value data: 0

64位版本:

Registry location: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework
DWORD (32-bit) Value name: LegacyWPADSupport
Value data: 0

reg

参考:

HttpClient request throws IOException

扫描二维码,在手机上阅读!