Blaze

Back Again

 

2006年6月23日

eVC++就是eVC++啊

在VC++6.0正常的一段代码:

void CMessageboxView::OnLButtonDown(UINT nFlags, CPoint point) 
{
    MessageBox(
"LButtonDown");
    
// TODO: Add your message handler code here and/or call default
    CView::OnLButtonDown(nFlags, point);
}

在eVC++4.0中编译错误:
error C2664: 'MessageBoxW' : cannot convert parameter 1 from 'char [4]' to 'const unsigned short *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
Error executing cl.exe.

 于是进行显式类型转换,改为MessageBox((LPCTSTR)"LButtonDown");
成功地弹出了消息框,但是里面地文字是乱码.但是这段代码在VC++6.0中是完全正常的.
如图:

于是改用如下代码:
void CMessageboxView::OnLButtonDown(UINT nFlags, CPoint point) 
{
    CString myStr
="LButtonDown";
    MessageBox((LPCTSTR)myStr);
    
// TODO: Add your message handler code here and/or call default
    CView::OnLButtonDown(nFlags, point);
}
乱码没有了:


问了一下wangxz,他说应该用MessageBox(_T("LBUTTONDOWN")); ,即加入一个_T宏,用来把ANSI字符串转换为 UniCode.因为Wince只支持UNICODE,因此调用API时要使用宽字符串。(LPCTSTR)"LBUTTONDOWN"中字符串本身仍然是ANSI字符串,前面加强制转换并没有解决问题。_T是在TCHAR.H中定义的一个宏,它会根据你编译环境中UNICODE宏的设置来确定是将后面的字符串编译成ANSI的还是UNICODE的
在VC下,由于PC上的Windows系统同时支持ANSI和UNICODE,所以可以用,但如果你在编译环境中定义了UNICODE宏,也会出现问题。
而定义一个CString中间变量的办法之所以可以用是因为CString重载了(LPCTSTR)这个强制转换运算符,这样就由CString完成了从ANSI字符串向UNICODE字符串的转换。

posted @ 2006-06-23 14:38 Blaze 阅读(1047) 评论(0) 编辑

VC++常用数据类型及其操作详解[徐兆元]

摘要: VC++常用数据类型及其操作详解(未完待续)-------西安邮电学院计算机系 徐兆元(FLxyzsby@163.com FLxyzsby@yahoo.com.cn)2004/08/03一.VC常用数据类型列表 Type Default Size Description 基 础 类 型 全 是 小 写 说明:这些基础数据类型对于MFC还是API都是被支持的 boolean unsigned 8 b...阅读全文

posted @ 2006-06-23 13:39 Blaze 阅读(2064) 评论(0) 编辑

2006年6月14日

From VB.NET to C# and Back Again [By Darren Neimke and Scott Mitchell ]

Introduction
In classic ASP, ASP pages could be developed using a number of different scripting languages, such as VBScript, JScript, PerlScript, and even Python. In ASP.NET, developers can use an even wider array of programming languages, from COBOL.NET to Perl.NET, to even crazier languages, like Objective CAML.NET. ASP.NET Web pages can also be created using Visual Basic.NET, C# (a Java-like language), and JScript.NET.

 

With classic ASP, the most popular scripting language, by far, was VBScript. Nearly every code example you'll find on the Web or in a book on ASP uses VBScript. With ASP.NET, however, a large number of developers are starting to use C#, Microsoft's newest language offering. As explained by Anders Hejlsberg (creator of C#), C# is Java-like language that borrows the good parts of Java and C/C++ and removes the bad parts. In the end, C#'s syntax is a lot like Java's (of which JScript is derived from, so if you're familiar with JScript, moving to C# will be easy enough).

In any case, as more and more developers begin using C#, more and more ASP.NET examples using C# will appear on the Web and in books. In my latest book, ASP.NET: Tips, Tutorials, and Code, all of the code examples are provided in both C# and VB.NET. Many ASP.NET Web sites have sections that show code exclusively in C#. While those familiar with Java, C/C++, or JScript may find this trend toward C# code samples a pleasant one, developers who have been using Visual Basic their entire career may be a bit disconcerted. They may find a perfect article showing C# code to accomplish some task they need to accomplish, but, if they don't understand C#, the code will look like gobbledygook to them. The same thing goes for developers who are fluent with Java and may be flabbergasted when examining a chunk of VB.NET code.

Ultimately, it is the .NET Framework of Classes that provides the functionality to perform tasks, while the languages themselves - VB.NET, C# etc. - are simply used to connect into it. For example, if you were connecting to a Microsoft Access database, you'd use the OleDbConnection class in the System.Data.OleDb namespace of the .NET Framework. (If you are unfamiliar with the .NET Framework you may wish to read this short summary on the .NET Framework.) Since the classes and methods used by an ASP.NET Web page, regardless of what language it is written in, are the same, the only differences between a C# and VB.NET code is its syntax. This article, then, will examine the syntactical differences between C# and VB.NET, and serve as a means for easily converting from one language to another.

Preliminary Syntactical Differences Between C# and VB.NET
One of the major differences between VB.NET and C# is that C# is case-sensitive while VB.NET is not. That is, in VB.NET the variable strName can be defined as strName and used throughout the ASP.NET Web page as strname, StrName, or any other case combination. In C#, however, case matters, so strname and StrName are considered two different variables. Where this really can be confounding is when using classes and methods in the .NET Framework. For example, notice the following statement written in VB.NET syntax:

response.write("Hello, World!")

However, in the .NET Framework the Response object is defined as Response (note the capital R) and the Write method is capitalized too. Hence, in C# code you'd need to have:

Response.Write("Hello, World!");

If you did not capitalize the R and W you would receive an error message when trying to view the ASP.NET Web page through a browser.

In every programming language, two very important things are the statement delimiters and block delimiters. Statement delimiters are the delimiters used to separate each statement from one another. Note the semicolon at the end of the above C# example; in C#, the semicolon is the statement delimiter. In VB.NET, each statement is delimited by a carraige return, meaning, essentially, each line of code goes on its own line. Since C#'s statement delimiter is the semicolon (;), at the end of each statement you must have a semicolon. A block is a set of grouped statements. For example, if you have an If statement in VB.NET with the following form:

If booleanValue then
            Statement1
            Statement2
            ...
            StatementN
            End If
            

The statements Statement1 through StatmentN are all in a block. Note that the block is marked by the beginning If statement and the closing End If. In C#, curly braces are used as block delimiters. That is, in C# our if code would look like:

if (booleanValue)
            {
            Statement1
            Statement2
            ...
            StatementN
            }
            

Note that if must be lowercase, and that there is no then keyword. Also, the booleanValue must be surrounded by parenthesis. These curly braces ({ ... }) are used whenever a block is needed in C#, such as bodies of functions, while statements, for statements, etc. Note that VB.NET uses more explicit block delimiters, such as Function ... End Function, While ... End While, For ... Next, etc.

Some other minor differences: in VB.NET we specify commented lines using the apostrophe ('); in C# we can have single line comments, marked by //, or we can create mutli-line comments using the delimiters /* and */. That is, everything between those delimiters is considered a comment.

Declaring Variables
In VB.NET variables are declared via the Dim statement, in the following syntax:

Dim VariableName as Type [ = value]

The VariableName is the name of the variable (such as strName, the Type is the type of the variable (such as Integer or String), and the = value is an optional addition, which sets the variable to a specified value. For example, if we wanted to create an Integer named iAge with an initial value of 23, we could do:

Dim iAge as Integer = 23

In C#, the syntax is just a little different. We omit the Dim statement and place the Type before the VariableName, like so:

Type VariableName [ = value];

// an example
int iAge = 23;

Note that there are some differences in the type names between C# and VB.NET. The following table lists some of the common data types in VB.NET and their equivalent names in C#. Realize, though, that despite these minor differences in the spelling of the data types that these data types map back to the same data types specified in the .NET Framework. That is, a VB.NET Integer and a C# int are both instances of the System.Int32 .NET Framework structure. In fact, instead of specifying iAge and Integer or int in the above examples, we could have said: Int32 iAge = 23; or Dim iAge as Int32 = 23, which would have had the same effect as declaring it an Integer or int.

Differences in Data Type Names
VB.NET C#
Integer int
String string
Single float

There are still many syntactical differences we need to examine between VB.NET and C#, including differences in operator, array, and function usage, declaration, and allocation. We'll examine all of these pertinent issues in Part 2.

In Part 1 we examined some of the primary differences between the syntax of VB.NET and C#. Additionally, we looked at how to two languages declared variables differently. In this part we'll look at each language's use of operators, arrays, and functions!


Examining the Operators
VB.NET and C# have roughly the same set of operators. For example, to perform addition between two numbers, use the + operator in either language. The one major difference is the string concatenation operator. VB.NET uses the ampersand (&), while C# uses the +. Both languages also have a short-hand notation for this - &= and +=, which takes a string on the left hand side and concatenates the string on the right hand side. That is, if we had:

// C# example...
someString += someOtherString;

' VB.NET example...
someString &= someOtherString

at the conclusion, someString would equal whatever value it equaled before we reached the line shown above, concatenated with the value of someOtherString More clearly, if someString initially equaled "Scott and someOtherString equaled "Mitchell", at the conclusion of the above line, someString would equal "Scott Mitchell".

Arrays in VB.NET and C#
Arrays in VB.NET and C# are created and managed a bit differently. First of all, to index an element in an array in VB.NET, you use parenthesis, as in the following example:

arrayVariable(index)

In C#, however, square brackets are used, like so:

arrayVariable[index]

When creating arrays in VB.NET, the syntax used is, essentially, the syntax used to create any variable. If you wanted to create an array named ages with 0 to n Integer elements, you'd do:

Dim ages(n) as Integer

Again, note that this would create a total of n + 1 elements (0 .. n). In C#, the array declaration is a bit different:

int [] ages = new int[n];

Note that we place the [] before the variable name; this indicates that ages is going to be an array. Next, we have to allocate n ints by saying = new int[n]. Note that this creates a total of n elements, elements indexed from 0 to n - 1! This is different than in VB.NET, which creates a total of one extra element when compared to the way C# does it.

Creating and Using Functions and Procedures
In VB.NET there are two classes of functions: those that return values and those that don't. Those functions that don't return values are called subroutines, and are created a bit differently than functions. In VB.NET, to create a function, which returns a value, use the following syntax:

Function FunctionName(arg1 as Type, ... argN as Type) as ReturnType
    ...
    Return someVariableOfReturnType
End Function

Note that when creating a function you must specify a return type at the end of the first line of the function declaration. Then, somewhere in the body of the function (usually at the end), you must return a value of the proper ReturnType. Functions, of course, can take zero to many input parameters, arg1 through argN, each with their own Type. A subroutine (or procedure, as it's sometimes called), is defined a bit differently:

Sub ProcedureName(arg1 as Type, ... argN as Type)
    ...
End Sub

Note that the Sub keyword is used instead of the Function keyword, and that no value need be returned.

In C#, to create either a function or a procedure (a function that doesn't return a value) you must use the following syntax:

ReturnType FunctionName(Type arg1, ... Type argN)
{
    ...
    return someVariableOfReturnType
}

In C# if you don't want the function to return a value, specify the ReturnType as void. Note that the function's body is delimited by the curly braces ({ ... }) and that, as with the VB.NET function, we must have a return statement, returning a variable of the proper type (with functions whose ReturnType is void no return is necessary). Also note that in the function arguments the Type comes before the arg name, just like when declaring variables in C#.

Casting
While it may help to think of a variable as nothing but a simple value, a variable can be formally defined by a number of properties, such as its value, scope, lifetime, and type. The type of a variable determines the set of legal values that it can be assigned; for example, a variable of type integer (Int32) can be assigned values from -231..231-1. When you attempt to assign two variables of unequivalent types, say assigning a string to an integer, a process called casting must occur.

Essentially, casting is the process of converting a variable from one type to another (from a string to an integer in our previous example). Casting comes in two flavors: implicit and explicit. Implicit casting, as the name implies, happens automatically; with explicit casting, extra syntax must be used to specify that a cast should occur. VB.NET allows for a lot of implicit casting, while C# requires casts to be explicit. For example, if we wanted to have an ArrayList of Integer values, and then wanted to work with a particular values, we need to use explicit casting in C#:

ArrayList ages = new ArrayList();
ages.Add(23);
int x = ages[0]; // ERROR: ages[0] returns an object - need to cast to int

However, the above code (in VB.NET syntax, of course) will work fine. To cast in C#, simply place a (DesiredType) section in front of the variable you wish to cast. To make the above code compile, we need to cast s to an int:

ArrayList ages = new ArrayList();
ages.Add(23);
int x = (int) ages[0]; // No error due to explicit cast to int

Not all types can be casted to other types. If you attempt to illegally cast a type, you will get an error message informing you that the cast is illegal. In VB.NET, explicit casting can be used via the CType function. The syntax is as follows:

VariableOfTypeConvertToType = CType(ObjectToCast, ConvertToType)

Now that we've examined the fundamental differences between VB.NET and C#, let's examine an actual exercise of translating an ASP.NET Web page from C# to VB.NET. We'll do this in Part 3.

 

In Part 2 we looked at more advanced differences between VB.NET and C#: namely the differences in operator usage; array usage, declaration, and allocation; and the functional differences. In this final part, we will (finally) look at a complete C# ASP.NET Web page and convert it to C#!

Putting the Pieces Together - Converting an Actual ASP.NET Web Page
Now that we've examined the major syntactical differences between VB.NET and C#, let's attempt to apply what we've learned and convert a C# ASP.NET Web page to VB.NET. The following code, written in C#, reads in the Products table from the GrocerToGo database into an OleDbDataReader, and then uses data binding to bind the data reader to a DataGrid. The code is as follows:

<% @Import Namespace="System.Data" %>
            <% @Import Namespace="System.Data.OleDb" %>
            <script language="c#" runat="server">
            void Page_Load(Object sender, EventArgs e)
            {
            // 1. Create a connection
            const string strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source=C:\\Data\\GrocerToGo.mdb";
            OleDbConnection objConn = new OleDbConnection(strConnString);
            // You must open the db connection before populating the DataReader
            objConn.Open();
            // 2. Create a command object for the query
            const string strSQL = "SELECT * FROM Products";
            OleDbCommand objCmd = new OleDbCommand(strSQL, objConn);
            // 3. Create/Populate the DataReader
            OleDbDataReader objDR = objCmd.ExecuteReader(CommandBehavior.CloseConnection);
            // Do data binding
            dgProducts.DataSource = objDR;
            dgProducts.DataBind();
            }
            </script>
            <html>
            <body>
            <h1>The <code>Products</code> Table</h1>
            <asp:datagrid runat="server" id="dgProducts" ForeColor="White" BackColor="Navy"
            Font-Name="Verdana" BorderWidth="0" CellPadding="4"
            HeaderStyle-Font-Bold="True"
            HeaderStyle-Font-Size="Small"
            Font-Size="Smaller"
            HeaderStyle-BackColor="Gray"
            />
            </body>
            </html>
            
[View a live demo!]

One thing to notice that wasn't mentioned before: in the constant strConnString note that to specify a backslash (\) in a C# string, we must use two consecutive backslashes (\\). This is because the backslash is the C# escape character - that is, we can insert a newline character using \n, or tab using \t. Therefore, to let C# know that we want a plain-Jane backslash and not some escaped character, we have to use two backslashes.

Now, to convert this to VB.NET! First note that all of the code in the HTML section (between the <html> and the </html>) will need no changes - we just need to concern ourselves with the server-side script block (or code-behind page, if you're using that technique). First, let's change all of the function statements to VB.NET-proper function statements. That is:

void Page_Load(Object sender, EventArgs e)
{
   ...
}

becomes:

Sub Page_Load(sender as Object, e as EventArgs)
   ...
End Sub

Note that we created a Sub since the C# function's return value was void. We also got rid of the curly braces, replacing the last one with End Sub. Finally, in the subroutine's arguments, we reordered the Type and arg names such that the arg name comes first followed by the Type. Next, we'll want to do some ticky-tack changes, such as renaming all of the constant delimiters in C#, //, to their VB.NET equivalents, ', removing all of the semicolons, and changing the C# string concatenation operator of + to the VB.NET operator, &. Next, let's change all variable (and constant) declarations from the C# format of Type VariableName to the VB.NET format of Dim VariableName as Type; for example, we'll make the following (among other) changes:

const string strSQL = "SELECT * FROM Products"; -- becomes --
Const strSQL as String = "SELECT * FROM Products"

... and ...

OleDbCommand objCmd = new OleDbCommand(strSQL, objConn); -- becomes --
Dim objCmd as OleDbCommand = New OleDbCommand(strSQL, objConn)

Once we complete this we are, miraculously, done! The use of methods and objects from the .NET Framework (such as the OleDbCommand class, are identical regardless of the language being used. Note that translating from VB.NET to C# requires a bit more attention when it comes to the casing of classes and methods, since C# is case-sensitive. The final VB.NET translation can be seen below:

<% @Import Namespace="System.Data" %>
            <% @Import Namespace="System.Data.OleDb" %>
            <script language="VB" runat="server">
            Sub Page_Load(sender as Object, e as EventArgs)
            '1. Create a connection
            Const strConnString as String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=C:\Data\GrocerToGo.mdb"
            Dim objConn as New OleDbConnection(strConnString)
            objConn.Open()
            '2. Create a command object for the query
            Const strSQL as String = "SELECT * FROM Products"
            Dim objCmd as New OleDbCommand(strSQL, objConn)
            '3. Create/Populate the DataReader
            Dim objDR as OleDbDataReader
            objDR = objCmd.ExecuteReader()
            dgProducts.DataSource = objDR
            dgProducts.DataBind()
            End Sub
            </script>
            <html>
            <body>
            <h1>The <code>Products</code> Table - Looks Nice!</h1>
            <asp:datagrid runat="server" id="dgProducts" ForeColor="White" BackColor="Navy"
            Font-Name="Verdana" BorderWidth="0" CellPadding="4"
            HeaderStyle-Font-Bold="True"
            HeaderStyle-Font-Size="Small"
            Font-Size="Smaller"
            HeaderStyle-BackColor="Gray"
            />
            </body>
            </html>
            
Pretty neat, eh? Essentially, translating from one language to another is not difficult, especially if you have a nice algorithm to aid in the translation. In fact, you could take this one step further and write a translator that morphed VB.NET code to C# code, and back again! I do strongly encourage you to practice such translations every now and then - it will make you more familiar with both VB.NET and C# and, in the end, make you a more knowledgeable developer!

Happy Programming!

 

  • By Darren Neimke and Scott Mitchell
  • posted @ 2006-06-14 12:47 Blaze 阅读(580) 评论(0) 编辑

    2006年6月13日

    请不要做浮躁的人(老文了,还是转一下,共勉)

    1.不要看到别人的回复第一句话就说:给个代码吧!你应该想想为什么。当你自己想出来再参考别人的提示,你就知道自己和别人思路的差异。
    2.初学者请不要看太多太多的书那会误人子弟的,先找本系统的学,很多人用了很久都是只对部分功能熟悉而已,不系统还是不够的。
    3.看帮助,不要因为很难而自己是初学者所以就不看;帮助永远是最好的参考手册,虽然帮助的文字有时候很难看懂,总觉得不够直观。
    4.不要被对象、属性、方法等词汇所迷惑;最根本的是先了解最基础知识。
    5.不要放过任何一个看上去很简单的小问题--他们往往并不那么简单,或者可以引伸出很多知识点;不会举一反三你就永远学不会。
    6.知道一点东西,并不能说明你会写脚本,脚本是需要经验积累的。
    7.学脚本并不难,JSP、ASP、PHP等等也不过如此--难的是长期坚持实践和不遗余力的博览群书;
    8.看再多的书是学不全脚本的,要多实践
    9.把时髦的技术挂在嘴边,还不如把过时的技术记在心里;
    10.学习脚本最好的方法之一就是多练习;
    11.在任何时刻都不要认为自己手中的书已经足够了;
    12.看得懂的书,请仔细看;看不懂的书,请硬着头皮看;
    13.别指望看第一遍书就能记住和掌握什么——请看第二遍、第三遍;
    14.请把书上的例子亲手到电脑上实践,即使配套光盘中有源文件;
    15.把在书中看到的有意义的例子扩充;并将其切实的运用到自己的工作中;
    16.不要漏掉书中任何一个练习——请全部做完并记录下思路;
    17.当你用脚本到一半却发现自己用的方法很拙劣时,请不要马上停手;请尽快将余下的部分粗略的完成以保证这个代码的完整性,然后分析自己的错误并重新编写和工作。
    18.别心急,写脚本确实不容易;水平是在不断的实践中完善和发展的;
    19.每学到一个脚本难点的时候,尝试着对别人讲解这个知识点并让他理解----你能讲清楚才说明你真的理解了; 20.记录下在和别人交流时发现的自己忽视或不理解的知识点;
    21.保存好你做过的所有的源文件----那是你最好的积累之一;
    22.对于网络,还是希望大家能多利用一下,很多问题不是非要到论坛来问的,首先你要学会自己找答案,比如google、百度都是很好的搜索引擎,你只要输入关键字就能找到很多相关资料,别老是等待别人给你希望,看的出你平时一定也很懒!
    23,到一个论坛,你学会去看以前的帖子,不要什么都不看就发帖子问,也许你的问题早就有人问过了,你再问,别人已经不想再重复了,做为初学者,谁也不希望自己的帖子没人回的。
    24,虽然不是打击初学者,但是这句话还是要说:论坛论坛,就是大家讨论的地方,如果你总期望有高手总无偿指点你,除非他是你亲戚!!讨论者,起码是水平相当的才有讨论的说法,如果水平真差距太远了,连基本操作都需要别人给解答,谁还跟你讨论呢.

    浮躁的人容易问:我到底该学什么;----别问,学就对了;
    浮躁的人容易问:做程序有钱途吗;----建议你去抢银行;
    浮躁的人容易说:我要中文版!我英文不行!----不行?学呀!
    浮躁的人分两种:只观望而不学的人;只学而不坚持的人;
    浮躁的人永远不是一个高手。

    posted @ 2006-06-13 23:49 Blaze 阅读(148) 评论(0) 编辑

    2006年6月12日

    地球上最慢的网路不在巴布里亚新几内亚和尼泊尔之间,而在中国网通和电信之间!

    忍受不了上博客园那种乌龟一样的速度,问了dudu ,dudu推荐了一个叫统一加速器的家伙。
    http://dudu.cnblogs.com/archive/2006/06/05/418004.html
    试试之后老是掉线,于是扔了,看到有人推荐千度,不错的东东,特拿来分享。
    电信用户下载地址:http://www.1000du.net/down/1000duv1.1.rar
    网通用户下载地址:http://1000du.net/down/1000duv1.1.rar

    登陆:用户名:1000du.net 密码:123456

    posted @ 2006-06-12 22:14 Blaze 阅读(238) 评论(0) 编辑

    2006年6月9日

    [翻译]用TcpClient建立GPRS连接

    NETCF的HttpWebRequest在有线或者wifi网络不能使用时会自动建立GPRS连接。因此,当你请求一个http连接或者webservice连接时, 你不用专门为GPRS连接写代码。 但这对于低等的socket类(例如TcpClient 和 UdpClient并不可行。对于这些类,你就得用 Connection Manager APIs 来建立/断开连接了。为了方便大家更方便地操作GPRS 连接, 我写了一个托管的类。

        public class GPRSConnection
        
    {
            
    const int S_OK = 0;
            
    const uint CONNMGR_PARAM_GUIDDESTNET = 0x1;
            
    const uint CONNMGR_FLAG_PROXY_HTTP = 0x1;
            
    const uint CONNMGR_PRIORITY_USERINTERACTIVE = 0x08000;
            
    const uint INFINITE = 0xffffffff;
            
    const uint CONNMGR_STATUS_CONNECTED = 0x10;
            
    static Hashtable ht = new Hashtable();

            
    static GPRSConnection()
            
    {
                ManualResetEvent mre 
    = new ManualResetEvent(false);
                mre.Handle 
    = ConnMgrApiReadyEvent();
                mre.WaitOne();
                CloseHandle(mre.Handle);
            }


            
    ~GPRSConnection()
            
    {
                ReleaseAll();
            }


            
    public static bool Setup(Uri url)
            
    {
                
    return Setup(url.ToString());
            }


            
    public static bool Setup(string urlStr)
            
    {
                ConnectionInfo ci 
    = new ConnectionInfo();
                IntPtr phConnection 
    = IntPtr.Zero;
                
    uint status = 0;

                
    if (ht[urlStr] != null)
                    
    return true;

                
    if (ConnMgrMapURL(urlStr, ref ci.guidDestNet, IntPtr.Zero) != S_OK)
                    
    return false;
                
                ci.cbSize 
    = (uint) Marshal.SizeOf(ci);
                ci.dwParams 
    = CONNMGR_PARAM_GUIDDESTNET;
                ci.dwFlags 
    = CONNMGR_FLAG_PROXY_HTTP;
                ci.dwPriority 
    = CONNMGR_PRIORITY_USERINTERACTIVE;
                ci.bExclusive 
    = 0;
                ci.bDisabled 
    = 0;
                ci.hWnd 
    = IntPtr.Zero;
                ci.uMsg 
    = 0;
                ci.lParam 
    = 0;

                
    if (ConnMgrEstablishConnectionSync(ref ci, ref phConnection, INFINITE, ref status) != S_OK &&
                    status 
    != CONNMGR_STATUS_CONNECTED)
                    
    return false;

                ht[urlStr] 
    = phConnection;
                
    return true;
            }


            
    public static bool Release(Uri url)
            
    {
                
    return Release(url.ToString());
            }


            
    public static bool Release(string urlStr)
            
    {
                
    return Release(urlStr, true);
            }


            
    private static bool Release(string urlStr, bool removeNode)
            
    {
                
    bool res = true;
                IntPtr ph 
    = IntPtr.Zero;
                
    if (ht[urlStr] == null)
                    
    return true;
                ph 
    = (IntPtr)ht[urlStr];
                
    if (ConnMgrReleaseConnection(ph, 1!= S_OK)
                    res 
    = false;
                CloseHandle(ph);
                
    if (removeNode)
                    ht.Remove(urlStr);
                
    return res;
            }


            
    public static void ReleaseAll()
            
    {
               
    foreach(DictionaryEntry de in ht)
               
    {
                   Release((
    string)de.Key, false);
               }

               ht.Clear();
            }


            [StructLayout(LayoutKind.Sequential)]
            
    public struct ConnectionInfo
            
    {
                
    public uint cbSize;
                
    public uint dwParams;
                
    public uint dwFlags;
                
    public uint dwPriority;
                
    public int bExclusive;
                
    public int bDisabled;
                
    public Guid guidDestNet;
                
    public IntPtr hWnd;
                
    public uint uMsg;
                
    public uint lParam;
                
    public uint ulMaxCost;
                
    public uint ulMinRcvBw;
                
    public uint ulMaxConnLatency;
            }


            [DllImport(
    "cellcore.dll")]
            
    private static extern int ConnMgrMapURL(string pwszURL, ref Guid pguid, IntPtr pdwIndex);

            [DllImport(
    "cellcore.dll")]
            
    private static extern int ConnMgrEstablishConnectionSync(ref ConnectionInfo ci, ref IntPtr phConnection, uint dwTimeout, ref uint pdwStatus);

            [DllImport(
    "cellcore.dll")]
            
    private static extern IntPtr ConnMgrApiReadyEvent();

            [DllImport(
    "cellcore.dll")]
            
    private static extern int ConnMgrReleaseConnection(IntPtr hConnection, int bCache);

            [DllImport(
    "coredll.dll")]
            
    private static extern int CloseHandle(IntPtr hObject);
        }

     使用GRPS托管类, 调用Setup方法创建连接。下面是个例子。

            public void DoTcpConnection()
            
    {
                
    string url = "www.msn.com";
                
    bool res = GPRSConnection.Setup("http://" + url + "/");
                
    if (res)
                
    {
                    TcpClient tc 
    = new TcpClient(url, 80);
                    NetworkStream ns 
    = tc.GetStream();
                    
    byte[] buf = new byte[100];
                    ns.Write(buf, 
    0100);
                    tc.Client.Shutdown(SocketShutdown.Both);
                    ns.Close();
                    tc.Close();
                    MessageBox.Show(
    "Wrote 100 bytes");
                }

                
    else
                
    {
                    MessageBox.Show(
    "Connection establishment failed");
                }

            }

    Enjoy,

    Anthony Wong [MSFT]

    This posting is provided "AS IS" with no warranties, and confers no rights.

    posted @ 2006-06-09 16:27 Blaze 阅读(2587) 评论(5) 编辑

    2006年6月8日

    1年零2个月零25天 我回来了

    摘要: 高考完成 3个月的假期,回到离别了1年零2个月零25天的博客园。阅读全文

    posted @ 2006-06-08 19:04 Blaze 阅读(208) 评论(0) 编辑

    2005年3月13日

    .NET的Pascal--Chrome来了!

    摘要: Chrome是RemObjects推出的下一代Object Pascal语言,运行于.NET和Mono平台之上。在保留Object Pascal特性的同时,Chrome还借鉴了C#、Java、Eiffel等语言的优秀元素。 RemObjects Chrome Command Line Edition - 1.0.0.141 (Preview) Updated March 1, 2005 Publi...阅读全文

    posted @ 2005-03-13 13:43 Blaze 阅读(1646) 评论(3) 编辑

    2005年2月4日

    Gmail疯了?50个邀请!

    摘要: Look! 再次送Gmail邀请,要的请留言!阅读全文

    posted @ 2005-02-04 18:30 Blaze 阅读(2831) 评论(76) 编辑

    2005年1月30日

    检举个博客园的Bug!

    摘要: 查看图片的属性,得到的地址是http://www2.cnblogs.com/images/cnblogs_com/william_fire/封面2.jpg直接打开它是ResourceNoFound。我想寒枫是在主站上传的,而镜像上自动把地址改成了www2,但这时镜像是没有这个文件的。还有我在镜像上进管理页面总是JavaScript错误,大家有这种情况吗?阅读全文

    posted @ 2005-01-30 09:54 Blaze 阅读(854) 评论(2) 编辑

    仅列出标题  下一页

    导航

    统计

    公告