/// <include file='doc\ActiveXMessageFormatter.uex' path='docs/doc[@for="ActiveXMessageFormatter.InitStreamedObject"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public static void InitStreamedObject(object streamedObject)
        {
            IPersistStreamInit persistStreamInit = streamedObject as IPersistStreamInit;

            if (persistStreamInit != null)
            {
                persistStreamInit.InitNew();
            }
        }
Example #2
0
        private void StoreIEDocObject(object sender, AxSHDocVw.DWebBrowserEvents2_NavigateComplete2Event e)
        {
            //////////
            // Keep a ref to the doc object
            //////////
            this._documentObject = (IPersistStreamInit)this._webBrowser.Document;

            //////////
            // Tell the user to load xml
            //////////
            //((mshtml.IHTMLDocument2)this._documentObject).body.innerHTML
            //	= "<Font face='arial' color='red' size=4>Please open an xml document</Font>";
        }
Example #3
0
        private void btnInit_Click(object sender, EventArgs e)
        {
            IPersistStreamInit psi = _obj as IPersistStreamInit;

            if (psi != null)
            {
                try
                {
                    psi.InitNew();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Example #4
0
        public static void SaveObjectToStream(object obj, Stream stm)
        {
            IStreamImpl istm = new IStreamImpl(stm);

            IPersistStream ps = obj as IPersistStream;

            if (ps != null)
            {
                ps.Save(istm, false);
            }
            else
            {
                IPersistStreamInit psi = (IPersistStreamInit)obj;

                psi.Save(istm, false);
            }
        }
Example #5
0
        public static void LoadObjectFromStream(object obj, Stream stm)
        {
            IStreamImpl istm = new IStreamImpl(stm);

            IPersistStream ps = obj as IPersistStream;

            if (ps != null)
            {
                ps.Load(istm);
            }
            else
            {
                IPersistStreamInit psi = (IPersistStreamInit)obj;

                psi.InitNew();
                psi.Load(istm);
            }
        }
Example #6
0
        private void frmMain_Load(object sender, System.EventArgs e)
        {
            this._ofd.Filter = "Assemblies |*.dll; *.exe";

            //////////
            // Load the stylesheet IE uses for displaying XML
            //////////
            MSXML2.FreeThreadedDOMDocument _doc = new MSXML2.FreeThreadedDOMDocumentClass();
            _doc.load("res://msxml.dll/defaultss.xsl");
            this._defaultStylesheet            = (MSXML2.XSLTemplate) new MSXML2.XSLTemplateClass();
            this._defaultStylesheet.stylesheet = _doc;

            //////////
            // Register a handler to pick up a ref to the doc model
            //////////
            this._webBrowser.NavigateComplete2
                += new AxSHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(
                       StoreIEDocObject);

            //////////
            // Surf to about:blank, to get an instance of the doc model
            //////////
            object _url             = "about:blank";
            object _flags           = new object();
            object _targetFrameName = new object();
            object _postData        = new object();
            object _headers         = new object();

            this._webBrowser.Navigate2(
                ref _url, ref _flags, ref _targetFrameName, ref _postData, ref _headers);

            this._documentObject = (IPersistStreamInit)this._webBrowser.Document;

            if (AssemblyName != string.Empty)
            {
                _showEvidence(AssemblyName);
            }
        }
Example #7
0
        public string GetHTMLSource(HtmlDocument Document, Encoding Encode)
        {
            if (Document == null)
            {
                return(string.Empty);
            }

            //Declare vars
            int                HRESULT;
            IStream            pStream            = null;
            IPersistStreamInit pPersistStreamInit = null;

            // Query for IPersistStreamInit.
            pPersistStreamInit = Document.DomDocument as IPersistStreamInit;
            if (pPersistStreamInit == null)
            {
                return(string.Empty);
            }

            //Create stream, delete on release
            HRESULT = CreateStreamOnHGlobal(IntPtr.Zero, true, out pStream);
            if ((pStream == null) || (HRESULT != S_OK))
            {
                return(string.Empty);
            }

            //Save
            HRESULT = pPersistStreamInit.Save(pStream, false);
            if (HRESULT != S_OK)
            {
                return(string.Empty);
            }

            //Now read from stream....

            //First get the size
            long ulSizeRequired = (long)0;

            ////LARGE_INTEGER
            //long liBeggining = (long)0;
            System.Runtime.InteropServices.ComTypes.STATSTG statstg = new System.Runtime.InteropServices.ComTypes.STATSTG();
            pStream.Seek(0, (int)tagSTREAM_SEEK.STREAM_SEEK_SET, IntPtr.Zero);
            pStream.Stat(out statstg, (int)tagSTATFLAG.STATFLAG_NONAME);

            //Size
            ulSizeRequired = statstg.cbSize;
            if (ulSizeRequired == (long)0)
            {
                return(string.Empty);
            }

            //Allocate buffer + read
            byte[] pSource = new byte[ulSizeRequired];
            pStream.Read(pSource, (int)ulSizeRequired, IntPtr.Zero);

            #region Auto-Encoding (Работает не всегда)
            ////UTF-8: EF BB BF
            ////UTF-16 big endian byte order: FE FF
            ////UTF-16 little endian byte order: FF FE
            ////UTF-32 big endian byte order: 00 00 FE FF
            ////UTF-32 little endian byte order: FF FE 00 00
            //Encoding enc = null;
            //if (pSource.Length > 8)
            //{
            //    // Check byte order mark
            //    if ((pSource[0] == 0xFF) && (pSource[1] == 0xFE)) // UTF16LE
            //        enc = Encoding.Unicode;

            //    if ((pSource[0] == 0xFE) && (pSource[1] == 0xFF)) // UTF16BE
            //        enc = Encoding.BigEndianUnicode;

            //    if ((pSource[0] == 0xEF) && (pSource[1] == 0xBB) && (pSource[2] == 0xBF)) //UTF8
            //        enc = Encoding.UTF8;

            //    if (enc == null)
            //    {
            //        // Check for alternating zero bytes which might indicate Unicode
            //        if ((pSource[1] == 0) && (pSource[3] == 0) && (pSource[5] == 0) && (pSource[7] == 0))
            //            enc = Encoding.Unicode;
            //    }
            //}

            //if (enc == null) enc = Encoding.UTF8;

            //int bomLength = enc.GetPreamble().Length;

            //return enc.GetString(pSource, bomLength, pSource.Length - bomLength);
            #endregion

            return(Encode.GetString(pSource));
        }
Example #8
0
        public static void LoadDocument(ref HTMLDocument doc, String documentVal, bool LoadAsAnsi, bool CreateSite, Encoding EncodingToAddPreamble)
        {
            if (doc == null)
            {
                throw new HtmlEditorException("Null document passed to LoadDocument");
            }

            IHTMLDocument2 htmldoc = (IHTMLDocument2)doc;

            bool isWin98 = (System.Environment.OSVersion.Platform == PlatformID.Win32Windows);

            if (documentVal == string.Empty)
            {
                documentVal = "<html></html>";
            }

            if (CreateSite)
            {
                //set client site to DownloadOnlySite, to suppress scripts
                DownloadOnlySite ds = new DownloadOnlySite();
                IOleObject       ob = (IOleObject)doc;
                ob.SetClientSite(ds);
            }

            IStream stream = null;

            if (isWin98 | LoadAsAnsi)
            {
                win32.CreateStreamOnHGlobal(Marshal.StringToHGlobalAnsi(documentVal), 1, out
                                            stream);
            }
            else
            {
                if (!isBOMPresent(documentVal))
                //add bytemark if needed
                {
                    if (EncodingToAddPreamble != null)
                    {
                        byte[] preamble      = EncodingToAddPreamble.GetPreamble();
                        String byteOrderMark = EncodingToAddPreamble.GetString(preamble, 0, preamble.Length);
                        documentVal = byteOrderMark + documentVal;
                    }
                }

                win32.CreateStreamOnHGlobal(Marshal.StringToHGlobalUni(documentVal), 1, out stream);
            }

            if (stream == null)
            {
                throw new HtmlEditorException("Could not allocate document stream");
            }


            if (isWin98)
            {
                //fix string termination on Win98
                ulong  thesize = 0;
                IntPtr ptr     = IntPtr.Zero;

                int iSizeOfInt64 = Marshal.SizeOf(typeof(Int64));
                ptr = Marshal.AllocHGlobal(iSizeOfInt64);

                if (ptr == IntPtr.Zero)
                {
                    throw new HtmlEditorException("Could not load document");
                }

                //seek to end of stream
                stream.Seek(0, 2, ptr);
                //read the size
                thesize = (ulong)Marshal.ReadInt64(ptr);
                //free the pointer
                Marshal.FreeHGlobal(ptr);

                //truncate the stream
                stream.SetSize((long)thesize);

                //2nd param, 0 is beginning, 1 is current, 2 is end

                if (thesize != (ulong)documentVal.Length + 1)
                {
                    //fix the size by truncating the stream
                    Debug.Assert(true, "Size of stream is unexpected", "The size of the stream is not equal to the length of the string passed to it.");
                    stream.SetSize(documentVal.Length + 1);
                }
            }

            //set stream to start

            stream.Seek(0, 0, IntPtr.Zero);
            //2nd param, 0 is beginning, 1 is current, 2 is end

            IPersistStreamInit persistentStreamInit = (IPersistStreamInit)
                                                      doc;

            if (persistentStreamInit != null)
            {
                int iRetVal = 0;
                iRetVal = persistentStreamInit.InitNew();
                if (iRetVal == HRESULT.S_OK)
                {
                    iRetVal = persistentStreamInit.Load(stream);

                    if (iRetVal != HRESULT.S_OK)
                    {
                        throw new HtmlEditorException("Could not load document");
                    }
                }
                else
                {
                    throw new HtmlEditorException("Could not load document");
                }
                persistentStreamInit = null;
            }
            else
            {
                throw new HtmlEditorException("Could not load document");
            }

            stream = null;
        }
Example #9
0
        public static String GetDocumentSource(ref HTMLDocument doc, Encoding enc)
        {
            if (doc == null)
            {
                return(null);
            }

            bool IsUnicodeDetermined = false;

            Encoding theEncoding = enc;

            if (theEncoding == null)
            {
                theEncoding = Encoding.GetEncoding(0);
                //Windows default
            }

            if (theEncoding != Encoding.GetEncoding(0))
            {
                //Don't try to detect unicode if we were
                //passed an encoding other than the default
                IsUnicodeDetermined = true;
            }

            // use the routine from htmlwrapper
            MemoryStream memstream = new MemoryStream();
            ComStream    cstream   = new ComStream(memstream);

            IPersistStreamInit pStreamInit = (IPersistStreamInit)doc;

            pStreamInit.Save(cstream, false);

            StringBuilder Result = new StringBuilder();

            //goto start of stream
            memstream.Seek(0, SeekOrigin.Begin);

            int iSize = 2048;

            byte[] bytedata   = new byte[2048];
            int    iBOMLength = 0;

            while (true)
            {
                iSize = memstream.Read(bytedata, 0, bytedata.Length);
                if (iSize > 0)
                {
                    if (!IsUnicodeDetermined)
                    {
                        //look for byte order mark
                        bool IsUTF16LE    = false;
                        bool IsUTF16BE    = false;
                        bool IsUTF8       = false;
                        bool IsBOMPresent = false;

                        if ((bytedata[0] == 0xFF) & (bytedata[1] == 0xFE))//UTF16LE
                        {
                            IsUTF16LE    = true;
                            IsBOMPresent = true;
                        }

                        if ((bytedata[0] == 0xFE) & (bytedata[1] == 0xFF))// UTF16BE
                        {
                            IsUTF16BE    = true;
                            IsBOMPresent = true;
                        }

                        if ((bytedata[0] == 0xEF) & (bytedata[1] == 0xBB) & (bytedata[2] == 0xBF)) //UTF8
                        {
                            IsUTF8       = true;
                            IsBOMPresent = true;
                        }


                        //look for alternate zeroes

                        if (!IsUTF16LE & !IsUTF16BE & !IsUTF8)
                        {
                            if ((bytedata[1] == 0) & (bytedata[3] == 0) & (bytedata[5] == 0) & (bytedata[7] == 0))
                            {
                                IsUTF16LE = true; //best guess
                            }
                        }

                        if (IsUTF16LE)
                        {
                            theEncoding = Encoding.Unicode;
                        }
                        else if (IsUTF16BE)
                        {
                            theEncoding = Encoding.BigEndianUnicode;
                        }
                        else if (IsUTF8)
                        {
                            theEncoding = Encoding.UTF8;
                        }

                        if (IsBOMPresent)
                        {
                            //strip out the BOM
                            iBOMLength = theEncoding.GetPreamble().Length;
                        }

                        //don't repeat the test
                        IsUnicodeDetermined = true;
                    }

                    Result.Append(theEncoding.GetString(bytedata, iBOMLength, iSize));
                }
                else
                {
                    break;
                }
            }
            memstream.Close();

            return(Result.ToString());
        }
Example #10
0
        private async Task <bool> ParseHTML(HttpContent content)
        {
            UpdateStatus(">> Trying to parse a HTML document...");

            //Stream st = content.ReadAsStreamAsync().Result;

            string s = await content.ReadAsStringAsync();

            UpdateStatus(">> Loading a HTML document...");

            mshtml.HTMLDocument   hd   = new mshtml.HTMLDocument();
            mshtml.IHTMLDocument2 hdoc = (mshtml.IHTMLDocument2)hd;

            IPersistStreamInit ips = (IPersistStreamInit)hdoc;

            ips.InitNew();

            hdoc.designMode = "On";
            hdoc.clear();
            hdoc.write(s);
            hdoc.close();

            // In Delphi, it's just
            // hdoc:= CreateComObject(Class_HTMLDocument) as IHTMLDocument2;
            // (hdoc as IPersistStreamInit).Load(TStreamAdapter.Create(Response.Stream));

            int i = 0;

            while (hdoc.readyState != "complete")
            {
                await Task.Delay(100);

                if (i > 500)
                {
                    throw new Exception(string.Format("The document {0} timed out while loading", "IHTMLDocument2"));
                }
                i++;
            }

            if (hdoc.readyState == "complete")
            {
                UpdateStatus(">> Checking HTML link tags...");

                IHTMLElementCollection ElementCollection = hdoc.all;
                foreach (var e in ElementCollection)
                {
                    if ((e as IHTMLElement).tagName == "LINK")
                    {
                        string re = (e as IHTMLElement).getAttribute("rel", 0);
                        if (!string.IsNullOrEmpty(re))
                        {
                            if (re.ToUpper() == "EDITURI")
                            {
                                string hf = (e as IHTMLElement).getAttribute("href", 0);
                                if (!string.IsNullOrEmpty(hf))
                                {
                                    _serviceDocKind = _serviceDocumentKind.RSD;
                                    _serviceDocUrl  = hf;

                                    Debug.WriteLine("ServiceDocumentKind is: RSD " + _serviceDocUrl);

                                    UpdateStatus("Found a link to a RSD documnet.");
                                }
                            }
                            else if (re.ToUpper() == "SERVICE")
                            {
                                string ty = (e as IHTMLElement).getAttribute("type", 0);
                                if (!string.IsNullOrEmpty(ty))
                                {
                                    if (ty == "application/atomsvc+xml")
                                    {
                                        string hf = (e as IHTMLElement).getAttribute("href", 0);
                                        if (!string.IsNullOrEmpty(hf))
                                        {
                                            _serviceDocKind = _serviceDocumentKind.AtomSrv;
                                            _serviceDocUrl  = hf;

                                            Debug.WriteLine("ServiceDocumentKind is: AtomSrv " + _serviceDocUrl);

                                            UpdateStatus("Found a link to an Atom service documnet.");
                                        }
                                    }
                                }
                            }
                            else if (re.ToUpper() == "ALTERNATE")
                            {
                                string ty = (e as IHTMLElement).getAttribute("type", 0);
                                if (!string.IsNullOrEmpty(ty))
                                {
                                    if (ty == "application/atom+xml")
                                    {
                                        string hf = (e as IHTMLElement).getAttribute("href", 0);
                                        if (!string.IsNullOrEmpty(hf))
                                        {
                                            Debug.WriteLine("Atom feed found.");
                                            try
                                            {
                                                _atomFeedUrl = new Uri(hf);
                                            }
                                            catch { }

                                            UpdateStatus("Found a link to an Atom feed.");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }
Example #11
0
        private void frmMain_Load(object sender, System.EventArgs e)
        {
            this._ofd.Filter = "Assemblies |*.dll; *.exe";

            //////////
            // Load the stylesheet IE uses for displaying XML
            //////////
            MSXML2.FreeThreadedDOMDocument _doc = new MSXML2.FreeThreadedDOMDocumentClass();
            _doc.load("res://msxml.dll/defaultss.xsl");
            this._defaultStylesheet = (MSXML2.XSLTemplate)new MSXML2.XSLTemplateClass();
            this._defaultStylesheet.stylesheet = _doc;

            //////////
            // Register a handler to pick up a ref to the doc model
            //////////
            this._webBrowser.NavigateComplete2
                += new AxSHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(
                    StoreIEDocObject);

            //////////
            // Surf to about:blank, to get an instance of the doc model
            //////////
            object _url = "about:blank";
            object _flags = new object();
            object _targetFrameName = new object();
            object _postData = new object();
            object _headers = new object();
            this._webBrowser.Navigate2(
                ref _url, ref _flags, ref _targetFrameName, ref _postData, ref _headers);

            this._documentObject = (IPersistStreamInit)this._webBrowser.Document;

            if (AssemblyName != string.Empty)
                _showEvidence(AssemblyName);
        }
Example #12
0
        private void StoreIEDocObject(object sender, AxSHDocVw.DWebBrowserEvents2_NavigateComplete2Event e)
        {
            //////////
            // Keep a ref to the doc object
            //////////
            this._documentObject = (IPersistStreamInit)this._webBrowser.Document;

            //////////
            // Tell the user to load xml
            //////////
            //((mshtml.IHTMLDocument2)this._documentObject).body.innerHTML
            //	= "<Font face='arial' color='red' size=4>Please open an xml document</Font>";
        }
        public HtmlRenderer(IArachnodeDAO arachnodeDAO)
        {
            Type htmldoctype = Type.GetTypeFromCLSID(Iid_Clsids.CLSID_HTMLDocument, true);

            //Using Activator inplace of CoCreateInstance, returns IUnknown
            //which we cast to a IHtmlDocument2 interface
            MSHTML = (IHTMLDocument4)Activator.CreateInstance(htmldoctype);

            IPersistStreamInit ips = (IPersistStreamInit)MSHTML;

            ips.InitNew();

            IOleObject oleObject = (IOleObject)MSHTML;
            //Set client site
            int iret = oleObject.SetClientSite(this);

            CrawlRequestTimeoutInMinutes = 1;

            //Getting exceptions when trying to get change notification through IPropertyNotifySink and connectionpointcontainer.
            //So, using this technique.
            Thread t = new Thread(() =>
            {
                string previousReadyState = "";
                while (true)
                {
                    try
                    {
                        if (_parse.WaitOne())
                        {
                            if (DateTime.Now.Subtract(_parseStartTime).TotalMinutes < CrawlRequestTimeoutInMinutes)
                            {
                                string currentReadyState = ((IHTMLDocument2)MSHTML).readyState;

                                if (string.Compare(currentReadyState, previousReadyState, true) != 0)
                                {
                                    previousReadyState = currentReadyState;

                                    ReadyState = ReadyState.Uninitialized;
                                    switch (currentReadyState.ToLower())
                                    {
                                    case "loading":
                                        ReadyState = ReadyState.Loading;
                                        break;

                                    case "loaded":
                                        ReadyState = ReadyState.Loaded;
                                        break;

                                    case "interactive":
                                        ReadyState = ReadyState.Interactive;
                                        ModifyDOM(((IHTMLDocument2)MSHTML), true);
                                        break;

                                    case "complete":
                                        ReadyState = ReadyState.Complete;
                                        break;

                                    default:
                                        ReadyState = ReadyState.Uninitialized;
                                        break;
                                    }

                                    if (ReadyStateChange != null)
                                    {
                                        ReadyStateChange(this, new ReadyStateChangeEventArgs(ReadyState, ((IHTMLDocument2)MSHTML)));
                                    }
                                }

                                if (ReadyState == ReadyState.Complete)
                                {
                                    EndRendering();

                                    previousReadyState = "";
                                }
                            }
                            else
                            {
                                throw new Exception("The AbsoluteUri timed out while rendering.");
                            }

                            Thread.Sleep(100);
                        }
                    }
                    catch (Exception exception)
                    {
                        EndRendering();

                        previousReadyState = "";

                        arachnodeDAO.InsertException(AbsoluteUri, AbsoluteUri, exception, false);
                    }
                }
            });

            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        }
Example #14
0
        public void LoadDocument(String documentVal)
        {
            if ((documentVal != string.Empty) | (!this.bLoadDocumentWhenReady))
            {
                //if doc is waiting to load, it is already in string variable
                sDocument = documentVal;
                this.bLoadDocumentWhenReady = false;
            }
            else
            {
                this.bLoadDocumentWhenReady = false;
                this.iLoadAttempts         += 1;
            }

            if (!IsCreated)
            {
                throw new HtmlEditorException("Document not created");
            }

            if ((this.m_htmldoc.readyState.ToLower() != "complete") & (this.m_htmldoc.readyState.ToLower() != "interactive"))
            //try to load on interactive as well as complete

            {
                if (iLoadAttempts < 2)
                {
                    this.bLoadDocumentWhenReady = true;
                    return;
                }
                else
                {
                    throw new HtmlEditorException("Document not ready");
                }
            }


            if ((sDocument == null) || (sDocument == String.Empty))
            {
                sDocument = "<html><body></body></html>";
            }

            UCOMIStream stream = null;

            if (this.mIsWin98 | this.mAlwaysLoadAnsi)
            {
                ComSupport.CreateStreamOnHGlobal(Marshal.StringToHGlobalAnsi(sDocument), 1, out
                                                 stream);
            }
            else
            {
                ComSupport.CreateStreamOnHGlobal(Marshal.StringToHGlobalUni(sDocument), 1, out
                                                 stream);
            }


            if (stream == null)
            {
                throw new HtmlEditorException("Could not allocate document stream");
            }

            if (this.mIsWin98)
            {
                //This code fixes a problem in Win98 - Framework bug? - where the string
                //is sometimes incorrectly terminated
                //It assumes an ANSI string

                ulong  thesize = 0;
                IntPtr ptr     = IntPtr.Zero;

                int iSizeOfIntPtr = Marshal.SizeOf(typeof(Int64));
                ptr = Marshal.AllocHGlobal(iSizeOfIntPtr);

                if (ptr == IntPtr.Zero)
                {
                    throw new HtmlEditorException("Could not load document");
                }

                //seek to end of stream
                stream.Seek(0, 2, ptr);
                //read the size
                thesize = (ulong)Marshal.ReadInt64(ptr);
                //free the pointer
                Marshal.FreeHGlobal(ptr);

                //2nd param, 0 is beginning, 1 is current, 2 is end

                if (thesize != (ulong)sDocument.Length + 1)
                {
                    //fix the size by truncating the stream
                    Debug.Assert(true, "Size of stream is unexpected", "The size of the stream is not equal to the length of the string passed to it.");
                    stream.SetSize((sDocument.Length) + 1);
                }
            }

            //set stream to start
            stream.Seek(0, 0, IntPtr.Zero);

            IPersistStreamInit persistentStreamInit = (IPersistStreamInit)
                                                      this.m_htmldoc;

            if (persistentStreamInit != null)
            {
                int iRetVal = 0;
                iRetVal = persistentStreamInit.InitNew();
                if (iRetVal == HRESULT.S_OK)
                {
                    //this is a fix for exception raised in UpdateUI
                    site.mFullyActive = false;

                    iRetVal = persistentStreamInit.Load(stream);

                    if (iRetVal != HRESULT.S_OK)
                    {
                        throw new HtmlEditorException("Could not load document");
                    }
                }
                else
                {
                    throw new HtmlEditorException("Could not load document");
                }
                persistentStreamInit = null;
            }
            else
            {
                throw new HtmlEditorException("Could not load document");
            }

            stream             = null;
            this.iLoadAttempts = 0;
        }
Example #15
0
        public override bool GetBuffer(GetBufferCallback callBack)
        {
            this.getBufferCallback = callBack;

            if (this.buffer != null && callBack != null)
            {
                callBack(this.buffer);
                return(true);
            }

            if (this.m_pIWebBrowser2 == null)
            {
                SetState(BrowserStatus.Error);
                isRefreshingForBuffer = false;
                return(false);
            }

            IHTMLDocument2 document = this.m_pIWebBrowser2.Document as IHTMLDocument2;

            if (document == null)
            {
                SetState(BrowserStatus.Error);
                isRefreshingForBuffer = false;
                return(false);
            }

            IPersistStreamInit ips = document as IPersistStreamInit;

            if (ips == null)
            {
                SetState(BrowserStatus.Error);
                isRefreshingForBuffer = false;
                return(false);
            }

            try
            {
                IStream istream;

                CreateStreamOnHGlobal(IntPtr.Zero, true, out istream);

                if (istream == null)
                {
                    SetState(BrowserStatus.Error);
                    isRefreshingForBuffer = false;
                    return(false);
                }

                int cb;
                unsafe
                {
                    int hr = ips.Save(istream, false);

                    if (hr != HRESULT.S_OK)
                    {
                        Marshal.ThrowExceptionForHR(hr);
                        SetState(BrowserStatus.Error);
                        return(false);
                    }

                    istream.Seek(0, 0, IntPtr.Zero);

                    byte[]        buffer = new byte[1024];
                    StringBuilder sb     = new StringBuilder();

                    int *  pcb        = &cb;
                    IntPtr readOffset = new IntPtr(pcb);

                    do
                    {
                        istream.Read(buffer, 1024, readOffset);
                        sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(buffer, 0, cb));
                    } while (cb > 0);

                    istream = null;
                    ips     = null;

                    if (sb.Length <= 0)
                    {
                        SetState(BrowserStatus.Error);
                        isRefreshingForBuffer = false;
                        return(false);
                    }

                    isRefreshingForBuffer = false;
                    this.buffer           = sb.ToString();
                }
            }
            catch (Exception e)
            {
                // workaround a bug on IE
                // when there's a "no-cache" http header
                // the HTML Source is invisible, so to fix it,
                // we need to refresh the page..
                if (e is FileNotFoundException)
                {
                    // Call refresh unless called before...
                    if (isRefreshingForBuffer || m_pIWebBrowser2 == null)
                    {
                        SetState(BrowserStatus.Error);
                        return(false);
                    }

                    isRefreshingForBuffer = true;
                    SetState(BrowserStatus.Processing);
                    m_pIWebBrowser2.Refresh();

                    return(true);
                }
                else
                {
                    SetState(BrowserStatus.Error);
                    return(false);
                }
            }

            if (callBack != null)
            {
                callBack(this.buffer);
            }

            return(true);
        }