Pages

Thursday, November 11, 2010

Debug C MEX S-Functions

You can use your C compiler to debug Simulink C MEX S-functions. This Technical Note describes how to debug S-functions using the following compilers:
Microsoft Visual C/C++ .NET compiler (version 7.0)
Microsoft Visual C/C++ compiler (version 6.0)
Watcom compiler (version 11.0)
UNIX compilers
All of these examples assume some knowledge of the compiler's debugging capabilities. Refer to your compiler documentation for further information on debugging files. The examples included in this Technical Note require sfundebug.mdl and timestwo.c.
Download these files and place them into a working directory.
Microsoft Visual C/C++ .NET
Open the Simulink model sfundebug.mdl.
To debug a MEX-file from within MATLAB, you must first compile the MEX-file with the -g option to the MEX function. The -g option builds the MEX-file with debugging symbols included. mex -g timestwo.cThis will create timestwo.mexw32. You should now simulate the model to make sure it executes properly.
Start the Microsoft Development Environment. Do not exit your MATLAB session.
From the Microsoft menu, select Tools -> Debug Process�
In the Process GUI that opens, select the MATLAB.exe process and click Attach
In the GUI that opens, select Native as the Type and click Ok. You should now be attached to the MATLAB process. You can now close the Process GUI if you wish.
Open the source files by selecting File -> Open->File� Set a breakpoint on the desired line of code by right-clicking on the line of code, and selecting Insert Breakpoint. If you have not run the model yet and the breakpoint shows up with a �?� in it, do not worry. The .mexw32 file will load when you run the model.
Start the simulation, and you should be running the S-function in the Microsoft Development Environment. For more information on the how to use the debugging features in the Microsoft environment, refer to the Microsoft Development Environment documentation.
Microsoft Visual C/C++ 6.0
Open the Simulink model sfundebug.mdl.
To debug a MEX-file from within MATLAB, you must first compile the MEX-file with the -g option to the MEX function. The -g option builds the MEX-file with debugging symbols included.mex -g timestwo.c
This will create timestwo.mexw32. You should now simulate the model to make sure it executes properly.
Exit your MATLAB session.
Open a DOS window (Start -> Programs -> Command Prompt), and change directories to the directory where your S-function and .mexw32 file are located. Then type:msdev timestwo.mexw32 This will start up the Microsoft Visual C/C++ compiler. This command will fail if msdev.exe is not on the system path. If you receive an error message when executing the msdev command, you will need to add the compiler directories to your system path. You should refer to the compiler documentation for more information on defining the system path for your compiler.
In the Microsoft environment, select Settings from the Project menu. In the dialog box that opens, select the Debug tab. In the edit box labeled Executable for debug session, enter the full path to where the MATLAB executable resides. For example, if you have MATLAB installed in a directory $MATLAB under Windows, you would enter $MATLAB\bin\win32\matlab.exe. The other edit boxes in this dialog box should remain empty.
Open the source files by selecting File -> Open. Set a breakpoint on the desired line of code by right-clicking with your mouse on the line of code, and selecting Insert/Remove Breakpoint.
From the Build menu, select Debug, and click Go. A dialog box will appear that warns you that the MATLAB executable (matlab.exe) does not have debugging information. This is expected, as we do not ship a debug version of MATLAB. Click OK to close this dialog box.
A new MATLAB session will start. You should be in the directory where your model and S-function are located. Open the model by typingsfundebug at the MATLAB prompt.
Start the simulation, and you should be running the S-function in the Microsoft Visual C/C++ environment. For more information on how to use the debugging features in the Microsoft environment, refer to the Microsoft Development Studio or Microsoft Visual Studio documentation.
Watcom 11.0
Open the Simulink model sfundebug.mdl.
To debug a MEX-file from within MATLAB, you must first compile the MEX-file with the -g option to the MEX function. The -g option builds the MEX-file with debugging symbols included. mex -g timestwo.c This will create timestwo.mexw32.
You should now simulate the model to make sure it executes properly.
Exit your MATLAB session.
Open up a DOS window (Start -> Programs -> Command Window), and type the following to open the Watcom compiler:Wdw This command will fail if Wdw.exe is not on the system path. If you receive an error message when executing the Wdw command, you will need to add the compiler directories to your system path. You should refer to the compiler documentation for more information on defining the system path for your compiler.
The Watcom Debugger starts and a New Program window opens. Type the full path to where MATLAB resides on your system in the Program Name field. For example:C:\matlab\bin\win32\matlab.exe Click OK to close this dialog box.
From the Break menu, select ON IMAGE LOAD and type the name of S-function in capital letters. For example:TIMESTWO Then select ADD and click OK. Note: You should only enter TIMESTWO. You do not need to enter the entire path to timestwo or timestwo.mexw32 .
From the RUN menu, click GO to start debugging your S-function.
When MATLAB starts, change directories to the location where you saved the model and the S-function. Note: MATLAB may start minimized.
Open the model and start the simulation.
Open the source file by double-clicking on timestwo in the MODULE window. This brings up the source code, timestwo.c, for setting breakpoints.
You should now be able to debug your S-function in the Watcom environment. For more information about how to debug in this environment, refer to the documentation for the Watcom compiler.
UNIX Compilers
Open the Simulink model sfundebug.mdl.
To debug a MEX-file from within MATLAB, you must first compile the MEX-file with the -g option to the MEX function. The -g option builds the MEX-file with debugging symbols included.mex -g timestwo.c You should now simulate the model to make sure it executes properly.
Exit your MATLAB session.
Start MATLAB with the debugger using the following command:matlab -D The -D flag starts MATLAB from within the debugger specified. For example, to use the dbx debugging tool on Solaris, you would enter the following command: matlab -Ddbx
Once the debugger has loaded, continue loading MATLAB by typing run at the debugger prompt.(dbx) run Running: matlab (process id 9375)
NOTE: If you are using MATLAB R12 or R12.1, use the following instead: (dbx) run -nojvm Running: matlab (process id 9375)
After MATLAB starts, enable debugging by typing the following at the MATLAB command prompt:dbmex on
Open the model and start the simulation. This will bring you into the debugger.
Set breakpoints in the source code:(dbx) stop in mdlOutputs
(2) stop in `timestwo.mexsol`timestwo.c`mdlOutputs
(dbx) file timestwo.c
Issue the cont command to continue.(dbx) cont
Once a breakpoint is hit, use the debugger routines to continue debugging the S-function.For more information about how to debug in this environment, refer to the documentation for the UNIX compiler.

Wednesday, September 15, 2010

VC2008中使用GSL

DOWNLOAD AND INSTALL GSL SOFTWARE

1.Download gsl-1.8.exe from http://sourceforge.net/project/showfiles.php?group_id=23617&package_id=19804
(contains binaries and .lib files)
2.Execute and finish the installation.

3.Download gsl-1.8-src.exe from http://sourceforge.net/project/showfiles.php?group_id=23617&package_id=19804
4.Execute and finish the installation.

INSTALL VISUAL C++ EXPRESS
If you have not installed Visual C++ 2005 express, use this link :
http://msdn.microsoft.com/vstudio/express/downloads/
select visual C++ express

BUILD GSL LIBRARIES FOR Visual studio
1. Launch Visual C++ Studio
2. Open project C:\Program Files\GnuWin32\src\gsl\1.8\gsl-1.8\VC8\libgsl.sln (assuming default path - replace if it is a different location)
3. Do a build all
4.Verify that after build is complete, new files are generated in subfolders in C:\Program Files\GnuWin32\src\gsl\1.8\gsl-1.8\VC8\libgsl

CONFIGURE PATH SETTINGS IN VISUAL C++ STUDIO
1.Launch Visual C++ studio
2.Select Tools->Options Menu
3.On the tree display in the Options dialog box, select branch for Projects and solutions->VC++ directories
4.On the right side of the dialog, select Executable files in the "show directories for" combo box and add the following paths:
C:\Program Files\GnuWin32\src\gsl\1.8\gsl-1.8\VC8\libgslcblas\Debug-DLL
C:\Program Files\GnuWin32\src\gsl\1.8\gsl-1.8\VC8\libgsl\Debug-DLL

5.In the "show directories for" combo box select "Include files" and add the following path:
C:\Program Files\GnuWin32\include

6.In the "show directories for" combo box select "Library files" and add the following paths:
C:\Program Files\GnuWin32\src\gsl\1.8\gsl-1.8\VC8\libgsl\Debug-DLL
C:\Program Files\GnuWin32\src\gsl\1.8\gsl-1.8\VC8\libgslcblas\Debug-DLL

HOW DO I USE GSL LIBRARY IN MY VC++ PROJECT?
1.Launch Visual studio
2.Open your VC++ project.
3.select menu Project -> properties
4.In the property pages dialog, select tree item "configration properties->Linker->Input
5.On the right hand side details, choose the field "Additional Dependencies" and append the following entries by clicking the ... button:
libgsl_dll_d.lib
libgslcblas_dll_d.lib


--------------------------------------------------
原文链接http://ixpress.spaces.live.com/blog/cns!8BCB40263F366272!683.entry
GSL是权威的免费科学计算库,翻译成中文就是非常牛叉的意思。经过大半上午的摸索,终于把他们之间的配合搞清楚了。下面开始方法介绍。
1. 下载最新版GSL
@ http://gnuwin32.sourceforge.net/packages/gsl.htm 最新的好像是1.9,不过这里只有1.8,估计1.9还在测试,不过无所谓。
需要下载的是前两个文件:Complete package, except sources和Sources。然后安装。

2. 配置VS和GSL
在VS的菜单tools->options->project and solutions->VC++ directiories里面设置include,bin,lib,sources的文件夹,分别对应gsl的安装目录。include就到gsl的 include就行了,不要到include/gsl下面
然后打开GSL的src文件夹,下面有个VC8文件夹,打开里面的libgsl.sln工程文件并编译(把四种库,debug release 静态 动态全编译了)。然后打开输出文件夹,把lib文件拷到gsl根目录的lib,把dll拷到system32

3. 写程序
工程向导win32 控制台程序。生成之后在工程配置里面找到C/C++ Generation下面的Runtime Libary,改成/MT或者/MTD。
链接gsl的库有两种,静态的和动态的
静态要加入libgsl.lib 和 libgslcblas.lib (release) 或者 libgsl_d.lib 和 libgslcblas_d.lib(debug)
动态dll要加入libgsl_dll.lib 和 libgslcblas_dll.lib (release) 或者 libgsl_dll_d.lib 和 libgslcblas_dll_d.lib(debug),此外还要写上#define GSL_DLL
加库可以这样
#pragma comment(lib,"libgsl.lib")
#pragma comment(lib, "libgslcblas.lib")

Monday, August 30, 2010

The Stats on Internet Porn

来源:onlinemba.com

Sunday, August 15, 2010

Yahoo Redesigns Image and Video Search Pages to Show Trending Results

Yahoo announced today it redesigned Yahoo! Image and Video search results pages to include the most popular trending topics that people are searching for.

These new pages are no longer bland and boring, and now shows up to five pages of topics that are trending in search. One really cool feature it added is the ability to turn on the auto-scroll feature so you don’t have to scroll through the pages manually.

Yahoo said it has already seen double digit percentage increases in engagement for both image and video search since it launched the new home pages, and a 60% increase in time spent on the image search home page.

Here are screen shots of the new look taken from the YSearch Blog:

yahoo image search


yahoo video search


This is great news for anyone who blogs about current events and performs SEO tactics on images to acquire a new and increased source of traffic to their websites.

Monday, July 12, 2010

云计算

云计算

  近来云计算越来越热门了,云计算已经被看作 IT 业的新趋势。云计算可以粗略地定义为使用自己环境之外的某一服务提供的可伸缩计算资源,并按使用量付费。可以通过 Internet 访问 “云” 中的任何资源,而不需要担心计算能力、带宽、存储、安全性和可靠性等问题。

  先要介绍一下云计算系统的结构。图 1 显示云计算的各个层以及现有的一些服务。


图 1. 云计算的层和现有服务


  基础设施即服务(Infrastructure-as-a-service, IaaS)是指以服务的形式租借基础设施(计算资源和存储)。IaaS让用户可以租借计算机(即虚拟机)和数据中心,可以指定特定的服务质量约束,比如可以运行某些操作系统和软件。Amazon EC2在这层中作为IaaS,向用户提供虚拟主机。

  平台即服务(Platform-as-a-Service, PaaS)主要关注软件架构或服务,提供在基础设施中进行“云”计算所用的API。Apache Hadoop 作为PaaS,它构建在虚拟主机上,提供云计算平台。





Amazon EC2

  Amazon EC2 是一个Web服务,它允许用户请求具有各种资源(CPU,磁盘,内存等)的虚拟主机。用户只需按使用的计算时间付费,其它事情全部交给Amazon处理。

  这些实例(Amazon Machine Image, AMI)基于Linux,可以运行您所需要的任何应用程序和软件。在从Amazon租借主机之后,可以像对待物理主机一样使用一般的SSH工具设置连接和维护主机。

  部署Hadoop云计算框架的最好方法是把它全部部署在AMI上,这样可以利用云资源,不需要考虑计算能力,带宽,存储等问题。

  对EC2的详细内容可以参考如下链接:http://www.ibm.com/developerworks/cn/web/ar-cloudaws3/





Apache Hadoop

MapReduce

  Apache Hadoop 是一个软件框架(平台),它可以分布式的操纵大量数据。它出现于2006年,由Google、Yahoo、IBM等公司支持。可以认为它是一种PaaS模型。

  它的设计核心是MapReduce实现和HDFS(Hadoop Distributed File System),它们源自MapReduce(由一份Google文件引入)和Google File System。

  MapRedue是Google引入的一个软件框架,它支持在计算机(即节点)集群上对大型数据集进行分布式计算。它由两个部分组成:映射(Map)和缩减(Reduce)。

  在映射过程中,主节点接收输入,把输入分割成更小的子任务,然后把这些子任务分配到工作节点上。

  工作节点处理这些小任务,把结果返回给主节点。

  然后在缩减过程中,主节点把所有子任务的结果组合成输出,这就是原任务的结果。图2 说明了MapReduce流程的概念。

  MapReduce 的优点是它允许对映射和缩减操作进行分布式处理。因为每个映射操作都是独立的,所有映射都可并行执行,这会减少总的计算时间。


图 2. Hadoop 集群的概念视图和 MapReduce 的流程


集群的概念视图

HDFS

  从最终用户的角度看,HDFS就像是传统的文件系统一样。可以使用目录路径对文件进行CRUD操作。但是,由于分布式存储的性质,有“NameNode”和“DataNode”的概念,它们承担各自的责任。

  NameNode 是 DataNode 的主节点。它在HDFS中提供元数据服务。元数据说明DataNode的文件映射。它还接收操作命令并决定哪些DataNode应该执行操作和复制。

  DataNode 作为HDFS的存储块。还响应从NameNode接收的块创建、删除、复制等命令。

  对HDFS的完整介绍可以参考官方网站。



JobTracker 和 TaskTracker

  在提交应用程序时,应该提供包含在HDFS中的输入目录和输入目录。JobTracker作为启动MapReduce应用程序的单一控制点,它决定应该创建多少个TaskTracker和子任务,然后把每个子任务分配给TaskTracker。每个TaskTracker向JobTracker报告状态和完成后的任务。

Tuesday, June 22, 2010

金山岭司马台长城

在北京的时间也快两年了,一直想去长城,由于在京郊一直没去。这次趁着端午三天假去了金山岭司马台这两段野长城。
2010.6.15,联系了网上口碑很好的徐大叔,吃住就定在他家了。背了瓶1.5L的水,1个木瓜从知春路去西直门,天很热,太阳很大,暗暗为明天担心。买了4449(北京北站-古北口)的车票,11.5元/人,下午4点多开,晚上8点多到,车上人很少,一路上好多山,好多隧道。 到了古北口站,徐大叔到火车站接站。经过一段小道到了他家,等了会儿就开餐,晚餐很丰盛,久违的红豆饭很合胃口,一下吃了三碗,为第二天登长城存储了能量。然后就休息了,早上6点就起了,吃了早饭,吃得也很饱。然后和北邮毕业旅游的十几个人一块拼车去金山岭,100元一车包来回,一车可坐8人。到了金山领,买了门票(25元),沿着长城向司马台走,到了司马台买了票,20元,走到司马台出口,此处一边归北京,另一边归河北。下山坐火车回徐大叔家午饭。吃完饭大叔送我们坐3:30的公交,可惜没等着。于是就到火车站坐火车,上了火车没多久就开始下雨了,雷电交加,下得很大,到了住处10点多了。
此行运气不错,由于晚上要下雨,白天太阳不大,气温也还好。这两段长城都很有气势,蜿蜒在山脊上,有处残破的地方和古罗马的斗兽场有着相似的沧桑之美。

Wednesday, June 2, 2010

猕猴桃

太厚的西瓜皮


Saturday, May 29, 2010

很牛的Picasa

Picasa网络相册中添加了一个“名称标签”的功能很强,内部的人脸检测和人脸识别正确率做得很高,加上友好的标注界面,让用户可以迅速地标完整个相册中的人脸,让整个相册按人脸进行组织。我猜其内部包含:
1. 一个多视角人脸检测器(MVFD),先检测出所有人脸
2. 人脸聚类算法将检测的人脸进行聚类,将按聚类从大到小先呈现给用户加注标签(大类代表此人在相册中占主导地位)。
3. 每个聚类中首先第一轮呈现给用户的照片是经典视角的脸,用户标注完后,呈现第二轮的(这中间应该有个学习的过程,在线学习。)

比较两个大文件是否相同

可以计算它们的MD5,看MD5值是否相同
//Code for calculate MD5
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography; namespace MD5
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
FileStream fs = new FileStream(@"F:\tiny_images.bin", FileMode.Open); //The file path
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(fs);
fs.Close();
foreach (byte hex in hash)
sb.Append(hex.ToString("x2"));
string md5sum = sb.ToString();
}
}
}

Friday, May 28, 2010

Robot Vision

Pictures taken by a robot can often have significantly different properties, both in terms of image quality and viewing geometry, when compared to those taken by a human.

Thursday, May 27, 2010

VS不能调试

To do this:
1) Goto Project->Properties
2) Make sure "Configuration" at the top is "Debug"
3) On the left, select "C/C++", then "General"
4) On the right, change "Debug information format" to "Program Database for edit and continue (/ZI)"
5) On the left, Select "Optimization"
6) On the right, Change "Optimization" to "Disabled (/Od)"
7) On the left, select "Code Generation"
8) On the right, change "Runtime library" to "Multi-Threaded Debug (/MTd)"
9) On the left, expand "Linker" and select "Debugging"
10) On the right, change "Generate Debug info" to "Yes (/DEBUG)"
11) Rebuild your project.

Tuesday, May 25, 2010

Human Computation

CAPTCHA

A CAPTCHA or Captcha (pronounced /ˈkæptʃə/) is a type of challenge-response test used in computing to ensure that the response is not generated by a computer. The process usually involves one computer (a server) asking a user to complete a simple test which the computer is able to generate and grade. Because other computers are unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human. Thus, it is sometimes described as a reverse Turing test, because it is administered by a machine and targeted to a human, in contrast to the standard Turing test that is typically administered by a human and targeted to a machine.It is a contrived acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart."
Applications

CAPTCHAs are used to prevent automated software from performing actions which degrade the quality of service of a given system, whether due to abuse or resource expenditure. CAPTCHAs can be deployed to protect systems vulnerable to e-mail spam, such as the webmail services of Gmail, Hotmail, and Yahoo! Mail.

CAPTCHAs found active use in stopping automated posting to blogs, forums and wikis, whether as a result of commercial promotion, or harassment and vandalism. CAPTCHAs also serve an important function in rate limiting, as automated usage of a service might be desirable until such usage is done in excess, and to the detriment of human users. In such a case, a CAPTCHA can enforce automated usage policies as set by the administrator when certain usage metrics exceed a given threshold. The article rating systems used by many news web sites are another example of an online facility vulnerable to manipulation by automated software.

Circumvention

There are a few approaches to defeating CAPTCHAs:

* exploiting bugs in the implementation that allow the attacker to completely bypass the CAPTCHA,
* improving character recognition software, or
* using cheap human labor to process the tests (see below).
CAPTCHA is vulnerable to a relay attack that uses humans to solve the puzzles. One approach involves relaying the puzzles to a group of human operators who can solve CAPTCHAs. In this scheme, a computer fills out a form and when it reaches a CAPTCHA, it gives the CAPTCHA to the human operator to solve.

Spammers pay about $0.80 to $1.20 for each 1,000 solved captchas to companies employing human solvers in Bangladesh, China and India.

Another approach involves copying the CAPTCHA images and using them as CAPTCHAs for a high-traffic site owned by the attacker. With enough traffic, the attacker can get a solution to the CAPTCHA puzzle in time to relay it back to the target site. In October 2007, a piece of malware appeared in the wild which enticed users to solve CAPTCHAs in order to see progressively further into a series of striptease images. A more recent view is that this is unlikely to work due to unavailability of high-traffic sites and competition by similar sites.

These methods have been used by spammers to set up thousands of accounts on free email services such as Gmail and Yahoo!. Since Gmail and Yahoo! are unlikely to be blacklisted by anti-spam systems, spam sent through these compromised accounts is less likely to be blocked.

Human solvers are a potential weakness for strategies such as Asirra. If the database of cat and dog photos can be downloaded, then paying workers $0.01 to classify each photo as either a dog or a cat means that almost the entire database of photos can be deciphered for $30,000.

Monday, May 17, 2010

Read file larger than 2GB

fopen
fseek(out,offset,SEEK_SET); /*the values used by fseek and ftell are long (not unsigned) so you may have trouble with files greater than 2GB*/
_fseeki64(out, offset, SEEK_SET);//可以读>2GB文件

Thursday, April 15, 2010

MEM

Maximum Entropy Model (MEM) is to model all known, and assume nothing about the unknown.
知之为知之,不知为不知。

Tuesday, April 13, 2010

Word写论文-公式输入

Alt+=直接进入公式输入模式
好多简单的公式已经可以像Latex中直接用命令输入,比如上标直接^,下标直接_,希腊字母可以直接\sigma
集合的花体
\mathcal{D}

在Design的Scripts中,以前一直没有找到。

Latex作图

Visio: File->Page Setup, Page Size (Same as printer paper size),所作图需比printer paper size小,作完后Page Setup (Size to fit drawing content)

File: Print -> .ps (Properties -> Advanced -> PostScript Options -> PostScript Output Option

.ps->.eps

epstopdf, .eps->.pdf

批量:for %i in (*.eps) DO epstopdf %i



\begin{figure*}[t]
\centering \includegraphics[width=1.0\textwidth]{Fig/ImgRank.pdf}
\caption{ The top 20 search results of the query ``waterfall'' with
the two ranking options. (a) Ranking by uploading time. (b) Ranking
by interestingness. We can see that many images are irrelevant to
the query (marked with red border) or close to others (marked with
blue or green border).}\label{Fig1}
\end{figure*}



ps2pdf .ps->.pdf



\displaystyle\max

\displaystyle\sum,使上下标位于上下方

Location tag tells where the tag appears in one image. Each image is partitioned into 3-by-3 equal grids, each grid corresponds one location tag as shown in Fig. 5 and 9 location tags are defined in total. The location tag for each tag is given according to which grid the centroid of its corresponding image region dropped into.

Monday, January 11, 2010

关于HttpWebRequest.AddRange()方法的参数

先讲一个故事吧!

我:“Server,请告诉我那个文件有多大?”(当你和Server对话时必须很有礼貌)

Server:“好吧,孩子,那是一个相当大的文件,6个G。你知道的,我很聪明,那就是为什么我是Server你是Client,你可以请求这个文件的一部分。告诉我你想要文件的哪一部分,随你从什么地方开始到什么地方结束,我会把那部分文件给你发过去。”

我:“你看,我已经下载了那个文件的前5个G,让我看看...,嗯...6-5...,怎么计算才最简单呢?嗯...我想我正好需要最后一个G。”

我的程序:webRequest.Headers.Add("range", 5 Gb)

WebRequest:“Oh,不是这样的,你不可以这样,你要用AddRange方法,我会帮助你做好的。”

我:“好吧,我再来...”

我的程序:webRequest.AddRange(from)

编译器:“Oh,你个小笨蛋!你想这个Int64的变量试试吗?我会看着你...”

我:“什么?!WebRequest?难道你不把一个Int64变量当做一个合法的值吗?”

WebRequest:“事实上...我恐怕是这样的。你不得不一次下载完这个大文件...嘿!但是你可以等到.net 4.5,你可能用一些更好用的方法,比如说P2P、增强的设计模式、DTC或其他更多的...”

我:“OK!听起来不错!但是...现在,我还是想用一些现成的办法!难道我还要自已新实现一个吗?”

WebRequest:“好的,但我还是恐怕是的,但你可以首先在一些论坛问一下,我非常确信你不是第一个遇到这个问题的人。我记得我爷爷,WinINet,或多或少的也有这个问题。这是个遗传...或者被设计,就象我们经常说的。”

我:“...有点象是旧事重提了...”

我翻译的不是很好,原文请看:http://objectmix.com/dotnet/252325-httpwebrequest-inconsistency-8-a.html

解决办法请继续看。

WebRequest.ContentLength属性是Int64型的,但是AddRange方法只接受Int32型的参数,所在我们在分段下载大于2个G的文件时,在大于(Int32.MaxValue)的地方时,我们就无法实现分段下载了,意味着大于2GB之后的文件必须用一个线程一次下完,否则文件大于2GB的部分我们无法下载。

我也反编过HttpWebRequest,其中有一个私有方法,AddRange(string rangeSpecifier,string from,string to)。但我忘了可以用反射来得到这个方法并调用之,看了上篇帖子后才恍然大悟,其中提到了两种方法,一种是利用反射,一种是利用动态写入一个新方法来实现。(调用私有方法)
两段代码如下:
利用反射:
Type t = typeof(HttpWebRequest);
object[] args = new object[3];
req = (HttpWebRequest)HttpWebRequest.Create(txtURL.Text);
args[0] = "bytes";
args[1]=start.ToString();
args[2]=end.ToString();
MethodInfo[] mi = t.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic);
for (MethodI = 0; MethodI < mi.Length; MethodI++)
{
if (mi[MethodI].Name == "AddRange") break;
}
mi[MethodI].Invoke(req, args);

动态方法:

public delegate void _AddRange(HttpWebRequest httpWebRequest, string rangeSpecifier, string from, string to);
static public _AddRange delegateAddRange;

static AddRangeCodeGenerator()
{
Type stringType = typeof(string);
DynamicMethod dynamicMethod = new DynamicMethod("AddRange", typeof(void), new Type[] {
typeof (HttpWebRequest), stringType, stringType, stringType },
typeof(AddRangeCodeGenerator), true);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();

ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Ldarg_2);
ilGenerator.Emit(OpCodes.Ldarg_3);
ilGenerator.Emit(OpCodes.Call, typeof(System.Net.HttpWebRequest).GetMethod("AddRange",
BindingFlags.Instance | BindingFlags.NonPublic));
ilGenerator.Emit(OpCodes.Pop);
ilGenerator.Emit(OpCodes.Ret);

delegateAddRange = dynamicMethod.CreateDelegate(typeof(_AddRange)) as _AddRange;
}


这两种解决方案都可以算得上是无所不用其极了。呵呵,希望能对某些人有用。
 

Locations of visitors to this page

Web Counters
Cheap Hotel Rates