<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    如鵬網 大學生計算機學習社區

    CowNew開源團隊

    http://www.cownew.com 郵件請聯系 about521 at 163.com

      BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
      363 隨筆 :: 2 文章 :: 808 評論 :: 0 Trackbacks

    #

    在與COM對象交互的時候有的時候我們得到一個對象,我們想知道它的類型,可以使用Object.GetType()方法得到的類型卻是System.__ComObject,因為System.__ComObject是代表所有COM對象的,但是它對我們來說是沒有任何意義的。如果想得到System.__ComObject的真正類型只要使用Microsoft.VisualBasic.Information.TypeName(objWindow.Object)就可以了,如果是非VB.net工程需要引用Microsoft.VisualBasic.dll 才能保證編譯通過。
    12月6日添加說明:
    經過反編譯TypeName方法,發現其核心實現為:
        UnsafeNativeMethods.ITypeInfo pTypeInfo = null;
        string pBstrName = null;
        string pBstrDocString = null;
        string pBstrHelpFile = null;
        UnsafeNativeMethods.IDispatch dispatch = VarName as UnsafeNativeMethods.IDispatch;
        if (((dispatch != null) && (dispatch.GetTypeInfo(0, 0x409, out pTypeInfo) >= 0)) && (pTypeInfo.GetDocumentation(-1, out pBstrName, out pBstrDocString, out num, out pBstrHelpFile) >= 0))
        {
            str5 = pBstrName;
        }

    和猜想的一致,它確實是通過IDispatch接口來完成的(呵呵,貌似也只有這一種方式)
    posted @ 2007-12-05 13:01 CowNew開源團隊 閱讀(5693) | 評論 (0)編輯 收藏

            剛才客戶打電話過來說系統有問題,分析他發過來的日志后發現原來程序中用Integer.parserInt的方法把字符串形式的金額解析為整形,以前金額較小沒有發現問題,今天發了一筆大額交易,總金額是2150220201,正好比Integer在32位平臺上的最大值2147483647大一點點,所以發生了轉換異常。
    經驗再次提醒我們:
            為了防止精度、大金額溢出等問題,禁止在涉及到金額的地方使用integer、double、float等原始類型,統一使用BigDecimal、BigInteger。在python中也有對應的類型decimal類型用來進行不限精度的。
    posted @ 2007-12-04 14:52 CowNew開源團隊 閱讀(426) | 評論 (0)編輯 收藏

    去掉一個字符串中的$符號以及大括號中的字符(包括大括號)。
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class Main
    {
     public static void main(String[] args)
     {
      Pattern p = Pattern.compile("(\\$)|(\\{.+?\\})");
      Matcher m = p.matcher("abc$ggg{12dgd3}");
      System.out.println(m.replaceAll(""));
     }
    }

    posted @ 2007-11-26 14:46 CowNew開源團隊 閱讀(3019) | 評論 (1)編輯 收藏

    本章翻譯人 CowNew開源團隊 周曉

    記號詞表

    每一個文法都指定了帶有規則(子結構)和詞表語言結構。這些符號在運行時被轉換成整型的"記號類型"從而可以有效的比較。定義從符號到記號類型的映射的文件對ANTLR和ANTLR生成的分析器來說是基礎。 這份文檔描述了ANTLR使用和生成的這類文件,還介紹了用于控制詞表的選項。

    導言

    在分析時,一個語法分析器文法通過符號在它的詞表里引用記號要符合由詞法分析器或其他幾號流生成的Token對象。記號類型儲存在記號對象中,每種符號的值是唯一的,分析器比較這些整數來判斷記號類型。如果分析器期望下一個記號類型是23,但發現第一個超前掃描記號類型,LT(1).getType(),不是23,這時分析器拋出MismatchedTokenException異常。

    一個文法可能有一個導入詞表,經常也會有一個導出詞表,用于被其他文法引用。導入的詞表從未被修改,通過它可以知道詞表的"初始條件"。不要和導入詞匯混淆了。

    下面列出了最常見的問題:

    ANTLR如何決定哪一個詞法符號是什么記號類型?

    每個文法有一個記號管理器來管理文法的導出詞表。從文法的importVocab選項,記號管理器以 符號/記號類型 的形式被預載。這個選項強制ANTLR尋找有如下映射關系的文件:

    PLUS=44

    沒有importVocab選項,文法的記號管理器是空的(稍后會看見一個警告)。

    你的文法中的任意記號沒有預設值,它們被按照遇到的順序賦值。例如,在下面的文法中,記號A和B分別是4和5:

    class P extends Parser;
    a : A B ;

    詞法文件以如下形式命名: NameTokenTypes.txt.

    為什么記號類型從4開始?

    因為ANTLR在分析過程中需要一些特殊的記號類型,用戶定義的記號類型必須在3后開始。

    ANTLR生成什么樣的詞表文件?

    ANTLR為詞表V生成VTokenTypes.txtVTokenTypes.java,V是文法的名字或者是exportVocab選項指定的名字。文本文件有點像一個簡化的記號管理器,保存著ANTLR需要的一些信息,供定義在其他文件中的文法查看其詞表信息等等。Java文件是是一個包含了記號類型常量定義的接口。ANTLR生成的分析器實現了其中的一個接口,獲得所需要的記號類型定義。

    ANTLR怎樣同步符號類型在相同文件和不同文件間文法的映射?

    一個文法的導出詞表必須是另一個文法的導入詞表或者2個文法必須共享一個公共的導入詞表。

    設想p.g中有一個語法分析器P:

    // yields PTokenTypes.txt
    class P extends Parser;
    // options {exportVocab=P;} ---> default!
    decl : "int" ID ;

    l.g中有一個詞法分析器L

    class L extends Lexer;
    options {
    importVocab=P; // reads PTokenTypes.txt
    }
    ID : ('a'..'z')+ ;

    即使L主要是P的詞表中的值,但ANTLR生成的是LTokenTypes.txt和LTokenTypes。

    不同文件中的文法必須共享同樣的記號類型空間,使用importVocab選項去預載同樣的詞表。

    如果這些文法在同一個文件中,ANTLR會用同樣的方法處理它。然而,你可以通過設置它們的導出詞表到同一個文件來使這2個文法共享同一個詞表。例如,如果P和L在一個文件中,你可以這樣做:

    // yields PTokenTypes.txt
    class P extends Parser;
    // options {exportVocab=P;} ---> default!
    decl : "int" ID ;
    class L extends Lexer;
    options {
    exportVocab=P; // shares vocab P
    }
    ID : ('a'..'z')+ ;

    如果你沒有為L指定詞表,它將會選擇共享文件中導出的第一個詞表;在這里,它將共享P的詞表。

    // yields PTokenTypes.txt
    class P extends Parser;
    decl : "int" ID ;
    // shares P's vocab
    class L extends Lexer;
    ID : ('a'..'z')+ ;

    記號類型映射文件像這樣:

    P    // exported token vocab name
    LITERAL_int="int"=4
    ID=5

    文法繼承和詞表

    文法繼承父文法的規則,動作和選項,但是子文法使用什么詞表和記號詞表呢?ANTLR對子文法的處理就好像你復制粘貼父文法的所有非重載規則到子文法。因此,子文法記號的集合就是父文法和子文法的交集。所有的文法都導出詞表所以子文法導出并使用一個和父文法不同的詞表文件。除非你使用importVocab選項重載,否則子文法導入父文法的詞表。

    文法Q繼承P,會預先設置好P的詞表,就好像Q使用了importVocab=P選項。例如,下面的文法有2個記號符號。

    class P extends Parser;
    a : A Z ;

    子文法Q,最初和父文法有相同的詞表,但隨后會增加一些符號。

    class Q extends P;
    f : B ;

    在上面的情況,Q定義了幾個符號,B使得Q的詞表為{A,B,C}.

    一個子文法的詞表一般是父文法詞表的父集。注意重載規則不影響最初的詞表。

    如果你的子文法需要父文法未使用過的新詞法結構,你或許需要子語法分析器使用一個子詞法分析器。使用importVocab選項指定子詞法分析器的詞表來重載它初始的詞表。例如,假設語法分析器P使用詞法分析器PL。不用importVocab重載,Q的詞表將使用P的詞表,即PL的詞表。如果你想讓Q使用另一個詞法分析器的記號類型,比如說使用QL,那么做下面的事情:

    class Q extends P;
    options {
    importVocab=QL;
    }
    f : B ;

    Q的詞表現在和QL的詞表相同或者是QL詞表的父集。

    識別器生成次序

    如果你所有的文法在一個文件中,你就不用擔心ANTLR將會最先處理哪一個文法文件,不過你仍要擔心ANTLR處理文件中文法的次序。如果你嘗試去導入一個會被另一個文法導出的詞表,ANTLR將提示它不能讀取這個文件。下面的文法文件會造成ANTLR出錯:

    class P extends Parser;
    options {
    importVocab=L;
    }
    a : "int" ID;
    class L extends Lexer;
    ID : 'a';

    ANTLR在文法文件中還沒有發現文法L,所以它將提示不能發現LTokenTypes.txt。另一方面,如果LTokenTypes.txt存在(比如說在文法文件中還沒有P文法的時候ANTLR運行生成的),ANTLR將為P讀取這個文件,然后在處理L文法的時候覆蓋掉它。ANTLR不知道它要處理的文法恰好在一個文件中,所以它假設是要讀取從另一個文件生成的詞表。

    一般的,如果你想讓文法B使用文法A的記號類型(無論什么文法類型),你必須首先對A運行ANTLR。例如,一個樹文法用到了分析器文法的詞表,應該在ANTLR生成了分析器之后再去處理樹文法。

    例如,當你想讓一個詞法分析器和一個語法分析器共享同一個詞表空間的時候,你要做的就是去把它們放到同一個文件中,設置它們的導出詞表到同一個空間。如果它們在分開的文件中,把語法分析器的導入詞表選項設置為詞法分析器的導出詞表,除非記號都定義在語法分析器中,這時,換一下導入/導出的關系讓詞法分析器使用語法分析器的導出詞表。

    詞表的一些使用技巧

    如果你的文法在不同的文件中,你仍想讓它們共享全部或部分記號空間,該怎么辦。有2種解決方案:(1) 讓文法導入同樣的詞表 (2) 讓文法繼承同一個父文法,該父文法含有記號空間。

    第一個方案在下面情況使用,你有2個詞法分析器和2個語法分析器,語法分析器必須要處理從根本上就不同的輸入部分。ANTLR 2.6.0發行版examples/java/multiLexer中的例子就屬于這種情況。javadoc注釋和Java代碼部分的詞法分析和語法分析過程都不一樣。javadoc詞法分析器有必要識別"*/"中止注釋的詞法結構,但它一般讓Java語法分析器用打開/關閉的記號引用來嵌套運行javadoc語法分析器:

    javadoc
    : JAVADOC_OPEN
    {
    DemoJavaDocParser jdocparser =
    new DemoJavaDocParser(getInputState());
    jdocparser.content();
    }
    JAVADOC_CLOSE
    ;

    問題在于:javadoc詞法分析器定義了JAVADOC_CLOSE,即也定義了它的記號類型。不幸的是Java語法分析器的詞表基于Java詞法分析器而不是javadoc詞法分析器。 要讓javadoc詞法分析器和java詞法分析器都可以看到JAVADOC_CLOSE (并且有同樣的記號類型),2個詞法分析器都要導入含有這種記號類型定義的詞表。這里有DemoJavaLexer和DemoJavaDocLexer的頭部:

    class DemoJavaLexer extends Lexer;
    options {
    importVocab = Common;
    }
    ...
    class DemoJavaDocLexer extends Lexer;
    options {
    importVocab = Common;
    }
    ...

    CommonTokenTypes.txt有:

    Common // name of the vocab
    JAVADOC_CLOSE=4

    共享詞表的第二種方案在下面情況使用,你有1個語法分析器和3個不同的詞法分析器(比如說為不同類型的C)。如果你只想語法分析器空間利用率高,語法分析器必須可以訪問3個詞法分析器的詞表,去掉文法不用的結構(大概可以用語義斷言)。給出CLexer,GCCLexer和MSCLexer,CLexer作為父文法定義出所有記號的集合。例如,如果MSCLexer需要"_int32",那么在CLexer中定義一個所有詞法分析器可見的記號類型:

    tokens {
    INT32;
    }

    在MSCLexer中,你可以給它實際意義的字符。

    tokens {
    INT32="_int32"
    }

    用這種方法,3個詞法分析器共享同一個記號空間,允許你用一個語法分析器識別多種C的輸入。

    Version: $Id: //depot/code/org.antlr/release/antlr-2.7.6/doc/vocab.html#1 $
    posted @ 2007-11-24 17:40 CowNew開源團隊 閱讀(2209) | 評論 (0)編輯 收藏

    原文:http://blog.csdn.net/nileel/archive/2007/04/17/1567656.aspx

    Java和C#都提供了對網絡的不同抽象層,編程人員可以使用不同的網絡接口完成對網絡的操作。

    Java C#
    應答/請求:
    java.net.URL和java.net.URLConnection。
    System.Net.WebRequest。

    協議:
    TCP/IP協議使用java.net.Socket和java.net.ServerSocket;
    UDP協議使用java.net.DatagramSocket和java.net.MulticastSocket。
    CP/IP協議使用System.Net.Sockets.TCPListener和System.Net.Sockets.TCPClient;
    UDP協議使用TSystem.Net.Sockets.UDPClient

    原始套接字層:
    沒有。
    System.Net.Sockets.Socket


      應答/請求層可以用于HTTP類的請求,其中的一端開始啟動一個連接,發送一些字節的數據,然后停止,等待對方作為應答發回的一些字節。對于象流這樣更靈活的操作,協議層的用處更大。對于大多數的Java編程人員來說,除非需要完成性能非常高的網絡操作,不需要對套接字進行直接控制。如果需要。C#仍然提供了對原始的Berkeley套接字進行控制的能力。


    應答/請求層:

      這個層次抽象掉了所有網絡層的細節,提供了一個可以雙向傳輸數據的象流那樣的接口。Java可以接受HTTP URL,并通過下面的命令完成GET命令:

    URL url= new URL( "http://to.post.to.com" );
    URLConnection urlConnection url.openConnection();
    InputStream input urlConnection.getInputStream();
    ... read stuff from input ...
    input.close();

      C#通過System.Net.WebRequest對象完成同樣的功能:

     WebRequest request= WebRequestFactory.Create(
      "http://to.post.to.com" );
     Stream input request.GetResponse().GetResponseStream();
     ... read stuff from input ...
     input.Close();

      二種語言都隱藏了底層的套接字創建HTTP協議要求,而是提供了編程人員可以用來發送和接收數據的流。與C#中的Stream類一樣,WebRequest類有可以異步地獲得流進行寫或從中讀數據的流的方法,或者可以從中讀取數據的WebResponse對象。

      協議層:

      對于熟悉java.net.Socket的Java編程人員對于System.Net.Sockets.TCPClient應該非常熟悉,因為二者是非常相似的。由于編程人員無須處理套接字的實現,而只須返回一個可供使用的流,因此二者的API和功能都非常相似。

      在Java中可以使用下面的命令實現一個非常簡單的telnet客戶端:

    Socket telnet= new Socket( "telnet.host.com", 23 );
    OutputStream output= telnet.getOutputStream();
    InputStream input= telnet.getInputStream();

      二個流都可用于與telnet同telnet.host.com的連接中。同樣功能的程序可以以相同的風格在C#中用下面的方式實現:

    TCPClient telnet= new TCPClient( "telnet.host.com", 23 );
    Stream telnetStream= telnet.GetStream();
    StreamWriter output =new StreamWriter( telnetStream );
    StreamReader input =new StreamReader( telnetStream );


      接收TCP/IP連接在二種語言中幾乎是相同的。在Java中,可以用下面的命令建立、并接收TCP/IP連接:

    ServerSocket server= new ServerSocket( 23 );
    Socket accept =server.accept();


      在C#中的實現方式如下:

    TCPListener server= new TCPListener( 23 );
    server.Start();
    Socket accept= server.Accept();


      在二種語言中,每個接收的套接字都需要單獨處理。在Java中,比較好的方法(直到Java 1.4)是為每個接收的套接字產生一個線程。在C#中也可以作同樣的處理,Socket類提供了使用帶有select方法的事件驅動的接口。(在事件驅動方式下對套接字編程已經超出了本文的范圍。)

      原始套接字層:

      這一部分的內容對于大多數Java程序員來說都是陌生的。由于被java.net.Socket和 java.net.DatagramSocket二個類進行了抽象,只使用Java編程語言的編程人員幾乎無需了解Berkeley套接字的實現。通過對Berkeley Socket類進行操作,同樣可以實現Java中的流功能。
    至此,我們已經用C#中的命令實現了大多數在Java中被抽象的功能━━對I/O和網絡的操作。
    posted @ 2007-11-23 00:02 CowNew開源團隊 閱讀(608) | 評論 (0)編輯 收藏

    一篇介紹寫自定義瀏覽器的很好的文章:
    from:http://www.codeproject.com/csharp/ExtendedWebBrowser.asp

    Sample Image

    Contents

    1. Introduction
    2. The goals, challenges, and solutions
    3. Creating the extended WebBrowser component
    4. Using the component
    5. Conclusion

    1: Introduction

    .NET 2.0 has a new WebBrowser control in the System.Windows.Forms namespace. This control itself is very useful, but doesn't supply some events that might be needed in certain situations. This article explains how to extend the WebBrowser control and add functionality for things like pop-up blocking, script error handling, and handling new windows in a tabbed browser environment.

    For extending the WebBrowser control, some features are not documented in the Help files of the .NET Framework. Not letting us be stopped by the "This method supports the .NET Framework infrastructure and is not intended to be used directly from your code." message, it is possible to create an object that implements IWebBrowser2 and use all the functionality of the underlying browser. Besides this, DWebBrowserEvents2 can be implemented for adding events to the control.

    This article assumes that you have already some knowledge of the browser interfaces IWebBrowser2 and DWebBrowserEvents2. Some knowledge about COM Interop and interfaces is also required.

    2: The goals, challenges, and solutions

    The goals of this component are:

    • Handling script errors in a neat way
    • Blocking unwanted pop-ups
    • Enabling functionality for tabbed browsing or MDI browsing
    • Making sure that a window is closed when it is closed by script

    This section explains the problems associated with the goals and their solutions, in a short form. The next section goes more into the coding details.

    Handling Script Errors

    The WebBrowser control has a ScriptErrorsSuppressed property... Setting this property to true does actually a bit more than it is supposed to. It not only disables the script error dialog, but also the dialog for logging on to a secure website with user certificates... What if we still want that functionality, or we would like to be notified when a script error has taken place, or we would like to know all the details about the script error?

    The script error can be caught by the HtmlWindow.Error event. This event fires whenever a script error occurs, with all the details. The challenge is that HtmlWindow is to be accesed with the HtmlDocument object, which is not always available. HtmlDocument comes available as soon as the Navigated event is fired. But what if the user refreshes the browser with F5? Sorry, the Navigated event doesn't fire. After some testing, I found that the only reliable way was to use the DownloadComplete event, which is not part of the default WebBrowser control.

    Solution:

    1. Implement DWebBrowserEvents2
    2. Create a DownloadComplete event
    3. When DownloadComplete fires, subscribe to the HtmlWindow.Error event
    4. Use the error event for obtaining the script error information
    5. Set the Handled property to true to suppress the script error

    Blocking unwanted pop-ups

    Pop-ups are most of the time not very welcome, or could be inappropriate. To block these things, some additional information is needed. NewWindow3 gives this information when the user uses Windows XP SP2, or Windows 2003 SP1 or better. If this event is not fired, NewWindow2 takes its place. When NewWindow3 is fired, you can check:

    • If the user initiated the action that leads to the new window
    • If the user holds the override key (the Ctrl Key)
    • If it is a pop-up displayed because of a window that is closing
    • The URL that is going to be opened
    • And more...

    Using NewWindow3 clearly is very interesting for this purpose. To use this event, DWebBrowserEvents2 needs to be implemented.

    Solution:

    1. Implement DWebBrowserEvents2
    2. Create a new event and a new event arguments class
    3. Launch this event with the appropriate information
    4. After the event is fired, see if the navigation needs to be canceled

    Enabling functionality for tabbed browsing or MDI browsing

    Tabbed browsing seems to gain popularity these days. For Internet Explorer 7, this is one of the new features. The challenge in tabbed browsing is that you need to create a window when this is needed by scripts or links. Besides this, window name resolution should work over multiple windows or tabs. (For example: <A href="http://SomeSite" target="SomeWindowName"/>) To achieve this, the automation object (called ppDisp in the NewWindowX event, and Application in the IWebBrowser2 interface) should be passed from the new browser back to the event. To get access to the Application property, it is needed to get a reference to the underlying IWebBrowser2 interface.

    Solution:

    1. Override AttachInterfaces and DetachInterfaces
    2. Store a reference to the IWebBrowser2 interface object
    3. Create a property called Application that exposes the Application property of the interface
    4. Implement the DWebBrowserEvents2 interface
    5. Listen for NewWindow2 and/or NewWindow3 events
    6. Whenever an event is raised, create a new instance of the browser control
    7. Assign the event parameter ppDisp to the Application property of the new instance

    Making sure that a window is closed when it is closed by script

    When you invoke window.close() in JScript, it looks like the WebBrowser control hangs. Somehow, it can't be used for navigation, nor can it be used for anything else. It would be nice if we know when this happens. There are several events that fire when this happens, but none of the events gives us actually the information needed. Overriding WndProc and seeing if the parent is notified that the browser is destroyed, is the only reliable solution. (If someone knows how to get WindowClosing to work, it would be nice here!)

    Solution:

    1. Override WndProc
    2. Check for the message WM_PARENTNOTIFY
    3. Check for the parameter WM_DESTROY
    4. If this is the case, fire a new event (this event is called Quit, in the example)

    3: Creating the extended WebBrowser component

    From the last section, we have seen that all of this basically comes down to two things:

    1. Implement an object of type IWebBrowser2, for obtaining the Application property of the browser
    2. Implement DWebBrowserEvents2 for firing events

    Implementing IWebBrowser2

    The WebBrowser control has two methods that are undocumented: AttachInterfaces() and DetachInterfaces(). These methods need to be used when you want to obtain a reference to the IWebBrowser2 interface.

    Collapse
      /// <summary>
    /// An extended version of the <see cref="WebBrowser"/> control.
    /// </summary>
    public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser
    {
    private UnsafeNativeMethods.IWebBrowser2 axIWebBrowser2;
    /// <summary>
    /// This method supports the .NET Framework
    /// infrastructure and is not intended
    /// to be used directly from your code. 
    /// Called by the control when the underlying
    /// ActiveX control is created. 
    /// </summary>
    /// <param name="nativeActiveXObject"></param>
    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
    protected override void
    AttachInterfaces(object nativeActiveXObject)
    {
    this.axIWebBrowser2 =
    (UnsafeNativeMethods.IWebBrowser2)nativeActiveXObject;
    base.AttachInterfaces(nativeActiveXObject);
    }
    /// <summary>
    /// This method supports the .NET Framework infrastructure
    /// and is not intended to be used directly from your code. 
    /// Called by the control when the underlying
    /// ActiveX control is discarded. 
    /// </summary>
    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
    protected override void DetachInterfaces()
    {
    this.axIWebBrowser2 = null;
    base.DetachInterfaces();
    }
    ...
    }

    Next, we can add the Application property.

    /// <summary>
    /// Returns the automation object for the web browser
    /// </summary>
    public object Application
    {
    get { return axIWebBrowser2.Application; }
    }

    This property can be used for creating a new window, and redirecting the browser to this new window, when a new window event is fired.

    Implementing DWebBrowserEvents2

    The following events are implemented in this sample:

    • NewWindow2 and NewWindow3 (for blocking pop-ups and creating new windows)
    • DownloadBegin and DownloadComplete (for handling script errors)
    • BeforeNavigate2 (if you want to see where you're going before even starting to get there)

    To neatly implement DWebBrowserEvents2, it is best to create a privately nested class in the component. This way, all the events that are needed are on one place and easy to find. When we instantiate this class, we provide a reference to the caller, whose methods can be invoked for raising the events we need.

    Events are not attached at component construction, but a bit later. There are two methods here that provide this and can be overridden. These are CreateSink() and DetachSink(). When adding this all up, we get something like this (note that some code has been cut for readability):

    Collapse
      /// <summary>
    /// An extended version of the <see cref="WebBrowser"/> control.
    /// </summary>
    public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser
    {
    // ... (More code here)
    System.Windows.Forms.AxHost.ConnectionPointCookie cookie;
    WebBrowserExtendedEvents events;
    /// <summary>
    /// This method will be called to give
    /// you a chance to create your own event sink
    /// </summary>
    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
    protected override void CreateSink()
    {
    // Make sure to call the base class or the normal events won't fire
    base.CreateSink();
    events = new WebBrowserExtendedEvents(this);
    cookie = new AxHost.ConnectionPointCookie(this.ActiveXInstance,
    events, typeof(UnsafeNativeMethods.DWebBrowserEvents2));
    }
    /// <summary>
    /// Detaches the event sink
    /// </summary>
    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
    protected override void DetachSink()
    {
    if (null != cookie)
    {
    cookie.Disconnect();
    cookie = null;
    }
    }
    /// <summary>
    /// Fires when downloading of a document begins
    /// </summary>
    public event EventHandler Downloading;
    /// <summary>
    /// Raises the <see cref="Downloading"/> event
    /// </summary>
    /// <param name="e">Empty <see cref="EventArgs"/></param>
    /// <remarks>
    /// You could start an animation
    /// or a notification that downloading is starting
    /// </remarks>
    protected void OnDownloading(EventArgs e)
    {
    if (Downloading != null)
    Downloading(this, e);
    }
    // ... (More code here)
        #region The Implementation of DWebBrowserEvents2 for firing extra events
    //This class will capture events from the WebBrowser
    class WebBrowserExtendedEvents :
    UnsafeNativeMethods.DWebBrowserEvents2
    {
    public WebBrowserExtendedEvents() { }
    ExtendedWebBrowser _Browser;
    public WebBrowserExtendedEvents(ExtendedWebBrowser
    browser) { _Browser = browser; }
          #region DWebBrowserEvents2 Members
    // ... (More code here)
    public void DownloadBegin()
    {
    _Browser.OnDownloading(EventArgs.Empty);
    }
    public void DownloadComplete()
    {
    _Browser.OnDownloadComplete(EventArgs.Empty);
    }
    // ... (More code here)
          #endregion
    }
        #endregion
    }

    4: Using the component

    In the last section, we created a new component. Now, it's time to use the new events and get the maximum functionality out of the browser. For each of the goals, the details are explained here.

    Handling the script errors

    In the sample application, there is a tool window that simply shows a list of errors that occured, with their details. A single-instance class holds the script errors' information and notifies the subscribers when this information has been changed. For handling these script errors, the BrowserControl first attaches to the DownloadComplete event, and next subscribes to the HtmlWindow.Error event. When this event is fired, we register the script error and set the Handled property to true.

    Collapse
      public partial class BrowserControl : UserControl
    {
    public BrowserControl()
    {
    InitializeComponent();
    _browser = new ExtendedWebBrowser();
    _browser.Dock = DockStyle.Fill;
    // Here's the new DownloadComplete event
    _browser.DownloadComplete +=
    new EventHandler(_browser_DownloadComplete);
    // Some more code here...
    this.containerPanel.Controls.Add(_browser);
    // Some more code here...
    }
    void _browser_DownloadComplete(object sender, EventArgs e)
    {
    // Check wheter the document is available (it should be)
    if (this.WebBrowser.Document != null)
    // Subscribe to the Error event
    this.WebBrowser.Document.Window.Error +=
    new HtmlElementErrorEventHandler(Window_Error);
    }
    void Window_Error(object sender, HtmlElementErrorEventArgs e)
    {
    // We got a script error, record it
    ScriptErrorManager.Instance.RegisterScriptError(e.Url,
    e.Description, e.LineNumber);
    // Let the browser know we handled this error.
    e.Handled = true;
    }
    // Some more code here
    }

    Blocking unwanted pop-ups, and enabling functionality for tabbed browsing or MDI browsing

    Handling pop-ups should be user configurable. For the purpose of demonstration, I've implemented four levels, ranging from blocking nothing to blocking every new window. This code is part of the BrowserControl, and shows how to do this. After the new window is allowed, the example shows how to let the new browser participate in the window name resolution.

    Collapse
    void _browser_StartNewWindow(object sender,
    BrowserExtendedNavigatingEventArgs e)
    {
    // Here we do the pop-up blocker work
    // Note that in Windows 2000 or lower this event will fire, but the
    // event arguments will not contain any useful information
    // for blocking pop-ups.
    // There are 4 filter levels.
    // None: Allow all pop-ups
    // Low: Allow pop-ups from secure sites
    // Medium: Block most pop-ups
    // High: Block all pop-ups (Use Ctrl to override)
    // We need the instance of the main form,
    // because this holds the instance
    // to the WindowManager.
    MainForm mf = GetMainFormFromControl(sender as Control);
    if (mf == null)
    return;
    // Allow a popup when there is no information
    // available or when the Ctrl key is pressed
    bool allowPopup = (e.NavigationContext == UrlContext.None)
    || ((e.NavigationContext &
    UrlContext.OverrideKey) == UrlContext.OverrideKey);
    if (!allowPopup)
    {
    // Give None, Low & Medium still a chance.
    switch (SettingsHelper.Current.FilterLevel)
    {
    case PopupBlockerFilterLevel.None:
    allowPopup = true;
    break;
    case PopupBlockerFilterLevel.Low:
    // See if this is a secure site
    if (this.WebBrowser.EncryptionLevel !=
    WebBrowserEncryptionLevel.Insecure)
    allowPopup = true;
    else
    // Not a secure site, handle this like the medium filter
    goto case PopupBlockerFilterLevel.Medium;
    break;
    case PopupBlockerFilterLevel.Medium:
    // This is the most dificult one.
    // Only when the user first inited
    // and the new window is user inited
    if ((e.NavigationContext & UrlContext.UserFirstInited)
    == UrlContext.UserFirstInited &&
    (e.NavigationContext & UrlContext.UserInited)
    == UrlContext.UserInited)
    allowPopup = true;
    break;
    }
    }
    if (allowPopup)
    {
    // Check wheter it's a HTML dialog box.
    // If so, allow the popup but do not open a new tab
    if (!((e.NavigationContext &
    UrlContext.HtmlDialog) == UrlContext.HtmlDialog))
    {
    ExtendedWebBrowser ewb = mf.WindowManager.New(false);
    // The (in)famous application object
    e.AutomationObject = ewb.Application;
    }
    }
    else
    // Here you could notify the user that the pop-up was blocked
    e.Cancel = true;
    }

    The reason the event is called StartNewWindow is that the code design guidelines do not allow an event to begin with "Before" or "After". "NewWindowing" doesn't have the same kind of ring to it :)

    Using the Quit event

    When the Quit event is fired, it's simply a matter of finding the right window or tab to close, and Dispose the instance.

    5: Conclusion

    The WebBrowser control is a good control for enabling web content in Windows applications. The additions in this article can be used to overcome the obstacles that developers face when they have no control over what web pages or other content the user might visit with their application. Hopefully, the next version of the .NET Framework will give us a little extra.

    The sample application and source

    The sample application is not a flashy UI, but it does demonstrate everything about this article. The code is commented, and hopefully gives enough information for helping you put your own solution together.

    Acknowledgements

    I would like to thank the following persons that made part of this article possible:

    • The technique for DWebBrowserEvents2 was in the bug list of Microsoft .NET 2.0. This has been used with modification.
    • The technique for WndProc was told by someone called "JoeBlow" on the MSDN forums, who had it derived from the MSKB article #253219.

    This is my first article on The Code Project. Please excuse me for my English. Thanks for reading! If you can add anything or have suggestions or tips, please post a message below.

    License

    This code is copyrighted by The Wheel Automatisering in The Netherlands. Some rights are reserved.

    The code in this license may be used for any purpose, just let your users know where it came from, and share derived code under the same license as this one. Don't blame me if something goes wrong. More information can be found here.

    If you wish to use and/or publish this in commercial closed-source applications, you have my consent. You may use this code under your own license when you do so.

    History

    • 27th of March 2006: First post of this article.

    About Jeroen Landheer


    I am
    - born in The Netherlands
    - living in Chile together with my wife.
    - a Microsoft Certified Professional Developer on all 3 areas (Windows, Web and Enterprise)
    - an MCITP on Microsoft SQL Server 2005 (Database Administrator)
    - an active programmer for about 14 years.
    - a business owner, of a Dutch company called "The Wheel Automatisering" (http://www.thewheel.nl)
    - a coder in C#, VB.Net and Managed C++.
    - someone who likes to share knowledge

    For fun I like to go out with my dogs, enjoy the sun or write some articles that I share with the community.

    Click here to view Jeroen Landheer's online profile.

    posted @ 2007-11-20 13:27 CowNew開源團隊 閱讀(1760) | 評論 (0)編輯 收藏

    from ftplib import FTP
    import time,os,sys

    print "按回車開始備份"
    raw_input()

    ftp=FTP()
    ftp.set_debuglevel(2)
    ftp.connect('服務器IP', '21')
    ftp.login("用戶名","密碼")
    ftp.cwd('/wwwroot/bbs/DataBase')
    now = time.localtime()
    blocksize = 1024
    poststr = str(now.tm_year)+"-"+str(now.tm_mon)+"-"+str(now.tm_mday)
    filename=r'e:\網站備份\bbs\database\Dbbs7'+poststr+'.asp'
    if(os.path.isfile(filename)):
        print "文件已經存在"
        raw_input()
        sys.exit()
    file_handler = open(filename,'w').write
    ftp.retrbinary("RETR Dbbs7.asp", file_handler, blocksize)
    ftp.quit()
    print "下載完畢"
    raw_input()

     

    posted @ 2007-11-20 10:51 CowNew開源團隊 閱讀(471) | 評論 (0)編輯 收藏

    實現了一個簡單的請假審批功能,展示了一個常用JBPM API的使用,工程下載地址:

    http://www.tkk7.com/Files/huanzhugege/myjbpm002.zip
    posted @ 2007-11-19 20:17 CowNew開源團隊 閱讀(579) | 評論 (0)編輯 收藏

     

    已經可以比較好的運行JBPM了,但是如果能以圖形化的方式顯示工作流,并且把當前節點高亮顯示,這樣可用性就更好了,用戶可以很輕松的看到當前流程到哪個節點了。

           我發現JBPMstarters-kit的例子中就有類似的效果,所以決定分析一下它是怎么實現的。

           打開網頁,瀏覽到有顯示當前工作流節點的頁面,查看到此頁面的地址為task.jsp,發現其中的核心代碼如下:

    <jbpm:processimage task="${taskBean.taskInstanceId}"/>

           這里使用了JBPM提供的jbpm:processimage標簽,此標簽定義在jbpm.tld中,這個Tag的類為org.jbpm.webapp.tag.ProcessImageTag。所以只要使用這個標簽我們就可以很輕松的在Web頁面中顯示圖形化的工作流了。

           那么如果是在Swing、SWT等非Web界面中也想顯示這種效果怎么辦呢?那么讓我們來分析一下ProcessImageTag類。

     private void retrieveByteArrays() {

        try {

          FileDefinition fileDefinition = processDefinition.getFileDefinition();

          gpdBytes = fileDefinition.getBytes("gpd.xml");

          imageBytes = fileDefinition.getBytes("processimage.jpg");

        } catch (Exception e) {

          e.printStackTrace();

        }

     }

           gpd.xml中記錄的是節點的位置關系,processimage.jpg是圖形化的圖片(只是基圖,沒有高亮顯示當前節點),這兩個文件是JBPMEclipse插件自動生成的。

           得到流程實例當前節點的方法:

     private void initialize() {

        JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();

        if (this.taskInstanceId > 0) {

               TaskInstance taskInstance = jbpmContext.getTaskMgmtSession().loadTaskInstance(taskInstanceId);

               currentToken = taskInstance.getToken();

        }

        else

        {

               if (this.tokenInstanceId > 0)

                      currentToken = jbpmContext.getGraphSession().loadToken(this.tokenInstanceId);

        }

        processDefinition = currentToken.getProcessInstance().getProcessDefinition();

     }

           currentToken中可以得到當前節點在顯示的時候的長度、寬度、橫縱坐標等值。得到的方式如下:

     private int[] extractBoxConstraint(Element root) {

        int[] result = new int[4];

        String nodeName = currentToken.getNode().getName();

        XPath xPath = new DefaultXPath("http://node[@name='" + nodeName + "']");

        Element node = (Element) xPath.selectSingleNode(root);

        result[0] = Integer.valueOf(node.attribute("x").getValue()).intValue();

        result[1] = Integer.valueOf(node.attribute("y").getValue()).intValue();

        result[2] = Integer.valueOf(node.attribute("width").getValue()).intValue();

        result[3] = Integer.valueOf(node.attribute("height").getValue()).intValue();

        return result;

     }

           這樣用<div/>標簽就可以將當前節點框上一個紅色的框框了:

               jspOut.println("<div style='position:relative; background-image:url(" + imageLink + "); width: " + imageDimension[0] + "px; height: " + imageDimension[1] + "px;'>");

           //詳細代碼參考:writeTable方法

    原來高亮顯示是在原有的圖片上疊加一個高亮的框框實現的。所以如果要顯示在Swing、SWT中的話也只要參考這個思路,在當前節點位置顯示一個高亮的框框就可以了!

    posted @ 2007-11-19 17:44 CowNew開源團隊 閱讀(6051) | 評論 (8)編輯 收藏

    本版主要新增特性:
      1、對Show語句的支持

           自從CowNewSQL2.1開始,我們提供了對Show語句的支持,主要用來查看系統中的表定義、字段定義、支持的函數等。由于各個數據庫中取得這些元信息的方式各有不同,經常需要關聯查詢很多系統表才能搬到,為了簡化用戶的使用,我們創新性的設計了Show系列語句,這樣您至少使用非常短的語句就可以實現以前需要編寫很復雜的語句才能實現的功能。

           Show語句語法列表:

    1show  tables:顯示系統中默認Schema下的所有表的表名。

    2show  tables Schema名:顯示指定Schema下的所有表的表名。例子:show tables DEMO

    3show  functions:顯示系統支持的函數的列表。

    4show  functioncolumns:顯示系統支持的函數參數以及返回值的詳細說明。

    5show  tablecolumns 表名:顯示指定表的數據列信息。例子:show  tablecolumns table_1。
    2、提供了JDBC驅動的使用方式 

           自從CowNewSQL2.1開始,我們提供了以JDBC驅動方式使用的支持(支持最新的JDBC4.0標準)。通過這種方式用戶無需修改系統的任何代碼,只要修改原有的JDBC連接字符串就可以輕松的將CowNewSQL融入系統,使用CowNewSQLJDBC驅動后系統中所有的SQL語句在送到數據庫系統中執行前都將會自動進行翻譯。

           CowNewSQLJDBC驅動類為:com.cownew.cownewsql.imsql.jdbc.DBDriver;連接字符串格式為:jdbc:cownewsql:目標數據庫類型:目標數據庫JDBC驅動類:JDBC連接字符串。

    使用方式舉例:

           原有程序連接到Oracle數據庫,使用的Oracle驅動類為oracle.jdbc.driver.OracleDriver,JDBC連接字符串為:jdbc:oracle:thin:@192.168.88.128:1521:XE

           我們只要將CowNewSQLJar包(包括cownewsql***.jar、antlr.jar、commons-lang**.jarretrotranslator-runtime**.jar等)加入程序的ClassPath,然后修改使用的數據庫驅動為:com.cownew.cownewsql.imsql.jdbc.DBDriver,然后修改JDBC連接字符串為:jdbc:cownewsql:oracle:oracle.jdbc.driver.OracleDriver:jdbc:oracle:thin:@192.168.88.128:1521:XE

           這樣我們無需修改任何代碼就將CowNewSQL翻譯器輕松的植入了原有系統。
    3、增加了對Alter Table語句的支持;修正了Convert函數在各個數據庫中取值范圍不一致的Bug;改進了方言管理器的實現機制;修復了若干Bug。

    下載地址1:http://www.tkk7.com/Files/huanzhugege/cownewsql-2.1.zip
    下載地址2:http://www.cownew.com/Soft/UploadSoft/cownewsql-2.1.zip


    =======================================================================================
     

           由于種種原因,各個數據庫系統的SQL語句語法以及支持的函數都不盡相同,這造成了如下兩個問題:(1)系統在多個不同數據庫之間移植變得非常困難,特別是需要維護多個數據庫版本的時候;(2)開發人員必須對各種數據庫的語法差異非常了解,這加大了開發難度。

           雖然Hibernate通過HQL等技術部分的解決了跨數據庫移植的問題,但是在對性能要求比較高的場合還是需要直接使用SQL語句訪問數據庫的,在這種情況下如何編寫能被不同數據庫支持的SQL語句就成了。目前解決這種差異的最常用的技術就是SQL語句翻譯,使用SQL翻譯器可以將SQL語句翻譯為在不同的數據庫中支持的特定平臺的SQL語句。CowNewSQL就是這樣一款產品。

           CowNewSQL簡化了跨數據庫產品的開發,比如取當前日期在MSSQL中是“SELECT GETDATE()”,在MYSQL中是“SELECT NOW()”,在Oracle中是“SELECT SYSDATE FROM DUAL”,使用CowNewSQL以后您只要使用“SELECT NOW()”,那么CowNewSQL就會為您自動將其翻譯為對應數據庫平臺支持的SQL語句,而且CowNewSQL的兼容性也非常好,比如“SELECT NOW()”寫成“SELECT GETDATE()”同樣可以被正確的翻譯;取數據庫前10條記錄,在MSSQL中是“Select top 10 from T_1”、在MYSQL中是“SELECT  LIMIT 0, 10 ”、在Oracle中是“SELECT  FROM DUAL WHERE ROWNUM <= 10”,使用CowNewSQL以后您只要使用“Select top 10 from T_1”,那么CowNewSQL就會為您自動將其翻譯為對應數據庫平臺支持的SQL語句。

           CowNewSQL還通過變通的方式對目標數據庫不直接支持的語法進行了支持。比如MYSQL是不支持“select * from t1 where fid in(select fid from t2 limit 0,5)”這樣在子查詢中的Limit語句的,CowNewSQL通過將子查詢進行二次結果集包裝的方式巧妙的對其進行了支持,“delete from T_SaleInvoice where FId in(select top 5 FParentId from T_SaleInvoiceDetails)”通過CowNewSQL的翻譯以后就成了“DELETE FROM T_SaleInvoice WHERE FId IN (select * from(SELECT FParentId FROM T_SaleInvoiceDetails LIMIT 0, 5 ) t_temp_sub)”這樣被MYSQL支持的語法了;MYSQL中沒有提供計算兩個日期之間月份差異的函數,CowNewSQL通過組合其他日期函數的方式模擬了這個函數,這樣使用者只要使用MONTHS_BETWEEN函數即可了,無需關心內部的差異。

           CowNewSQL支持如下幾種類型的SQL語句:CreateTable/AlterTable/DropTable/CreateIndex/DropIndex/Select/Insert/Delete/Update/Show;支持子查詢、JoinUnion等高級的SQL特性;支持日期(包括取當前日期、從日期中提取任意部分、計算日期差異、日期前后推算等)、數學(包括取絕對值、取PI值、四舍五入、對數計算、隨機數等)、字符串(包括取子字符串、取字符串長度、字符串截斷、大小寫轉換等)、基本數據處理(包括數字字符串互轉、日期轉字符串、非空判斷等)等函數。

    posted @ 2007-11-17 15:27 CowNew開源團隊 閱讀(2924) | 評論 (10)編輯 收藏

    僅列出標題
    共30頁: First 上一頁 5 6 7 8 9 10 11 12 13 下一頁 Last 
    主站蜘蛛池模板: 亚洲中文字幕日本无线码| 一级毛片在线播放免费| 国产又长又粗又爽免费视频 | 24小时日本韩国高清免费| 亚洲a级成人片在线观看| 免费成人在线观看| 久久国产乱子免费精品| 亚洲偷自拍另类图片二区| 亚洲色成人中文字幕网站| 国产va精品免费观看| 黄 色一级 成 人网站免费| 亚洲AV无码久久久久网站蜜桃| 亚洲免费在线观看| 全免费毛片在线播放| 羞羞视频免费网站在线看| 中文字幕亚洲综合小综合在线| 亚洲一区二区三区香蕉| 免费无码一区二区三区蜜桃大| 成全视频在线观看免费| 亚洲国产美女精品久久久| 亚洲AV第一页国产精品| 免费国产一级特黄久久| 国产成人精品免费视频大全麻豆| 深夜免费在线视频| 亚洲日本天堂在线| 在线观看亚洲人成网站| 亚洲综合另类小说色区| 日本特黄特色aa大片免费| 国产成人精品免费视频大全麻豆| 四虎国产精品免费永久在线| 另类图片亚洲校园小说区| 亚洲综合久久一本伊伊区| 久久精品国产精品亚洲艾| 亚洲精品无码av天堂| 暖暖日本免费在线视频| 青娱乐免费在线视频| 久久WWW免费人成一看片| 成全视频免费观看在线看| 高清永久免费观看| 一区二区三区精品高清视频免费在线播放 | 国产99视频免费精品是看6|