locked
how to login website from WebBrowser Control RRS feed

  • Question


  • I am first programmer in VB....now i want to create one form to auto Login website in webbrowser Control,i have 2 Form

    • Form2 is WebBrowser
    • Form1 like my picture , it have 2 button
    • my requirement is : when user click Login Button... Form2 will login to website automatic but don't show up.....but when login already if user click Browser Button so just it show up. Here is website to login www.ssr138.com
    • Login Button = Form2 Login website auto but don't show form2 up
    • Browser Button = Form2 show up but it is show if user click Login Button success

    Please help, Thanks in advanced.


    Thursday, December 6, 2012 4:35 PM

All replies

  • The teacher made this task quite simple by desgining the webpage so you can easily get the objects on the webpage.  He hand generated the HTML code.  I went to the webpage a copied the important parts of the source code below.  I will not do the code for you but will give you the steps and will help if you have any problems

    In th ewebbrowser control

    1) Navigate to webpage

    2) Use the method webrowser1.document.GetElementByID("UserID") to get the element for the username on the webbpage.  Set the property innertext to the username on the form in your project

    3) Use the method webrowser1.document.GetElementByID("Password") to get the element for the password on the webbpage.  Set the property innertext to the password on the form in your project

    4) Use the method webrowser1.document.GetElementsByTagName("form") to get the element for the form on the webbpage.  This returns an elementcollection which is an array and have to use enumerable.  Since you only have one form on the webpage it wil be array index zero.  I usually set the returned object to a local variable 'form'. 

    5) Then submit the form using the instruction form.Submit.  the variable form is from step 4.

       <form name="login_form" action="LoginP.cfm" method="POST">
       <input name="UserId" type="text"  id="UserId" size="12" maxlength="14" tabindex="1" style="background:none; border-bottom-color:#000000; border:none; color:#000000; border-bottom-style:solid; border-bottom-width:1 px; font-size:14px">
       <input name="Password" type="password" id="Password" size="12" maxlength="15" tabindex="2"  style="background:none; border-bottom-color:#000000; border:none; color:#000000; border-bottom-style:solid; border-bottom-width:1 px; font-size:14px">


    jdweng

    Friday, December 7, 2012 8:48 AM
  • yes thanks for your help but maybe i can't use this way .....now let's me tell you more detail and hope you can help me !

    ComboBox : For select website to login
    Login :  For Login Website in ComboBox ( while user login already .....it will change link as Logout )
     
    More : For user click to watch website in another form with WebBrowser Control ( if user click login already ......it will open website automatic so user no need login again ....it will use session with Login Link )
     
    Now what I want it is Login and More ..................I need it login automatic when user click Login and when user click More ....webBrowser Form will open but no need login again
     
    Hope you can help me ! thank in advanced .

    Saturday, December 8, 2012 10:36 AM
  • I always recommend tackling one par t of the problem at a time.  You need to use the algorithm I provided to logon to the webpage.  There are a number of methods you can use to determine if you arre logged int o the webpage.  For example the Form will not be present once you have logged into the webpage so you can test if the form exist.  I suspect you don't know all the traps the teacher hasn't told you about that you are going to find out once you log into the webpage. Projects like this teachers want to show that they are smarter than the students.

    jdweng

    Saturday, December 8, 2012 11:09 AM
  • Dear Joel Engineer ,

    i just start with vb ....... can you give me some code .....i really need your help urgently,

    Please give some code ! but i ever tested with webrowser1.document.GetElementByID already....

    it just working with username/password only but for button to submit page not working.....

    Hope that you help me to show some code , also this is not for my teacher ......it is working for my boss .

    Thanks in advanced,

    sokunthor



    • Edited by sokunthor Saturday, December 8, 2012 3:24 PM
    Saturday, December 8, 2012 3:05 PM
  • Canyou provide the code you have working already


    jdweng

    Saturday, December 8, 2012 5:14 PM
  • Dear Joel Engineer,

    i will give my code to you now......but it is my thinking........not like my below picture

    also now this form and code not working yet.

    here is form, i have 3 form ( form1, BR , Browser)


    Form1 :


     

    BR = it is browser


    Browser : it is Browser also

    code in Form1 :

    Imports Microsoft.Win32
    Imports System.Windows
    Public Class Form1

        Private Sub Open1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles Open1.LinkClicked

            Dim br As New Browser(Cookies1.Text, "http://www.ssr138.com/number/front/Home.cfm")
            br.Show()
            ' Process.Start("SessionMerging0\DDMKUN")
        End Sub

        Private Sub Open2_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles Open2.LinkClicked
            Dim br As New Browser(Cookies2.Text, "http://www.ssr138.com/number/front/Home.cfm")
            br.Show()
            'Process.Start("SessionMerging1\DDM01")
        End Sub

        Private Sub Open3_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles Open3.LinkClicked
            Dim br As New Browser(Cookies3.Text, "http://www.ssr138.com/number/front/Home.cfm")
            br.Show()
        End Sub


        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            BR.Show()
            'SessionMergingDisable()
        End Sub

        Private Sub SessionMergingDisable()
            Dim RegistryPath As String = "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main"
            Dim ValueName = "SessionMerging"

            If My.Computer.Registry.GetValue(RegistryPath, ValueName, Nothing) Is Nothing Then
                ' Set webbrowser isolated session
                Process.Start("SessionMerging0\SessionMerging.reg")
            Else
                Dim SessionMergingCurrent As Int16 = Registry.GetValue(RegistryPath, ValueName, 0)

                If SessionMergingCurrent = 1 Then
                    ' Set webbrowser isolated session
                    Process.Start("SessionMerging0\SessionMerging.reg")
                End If
            End If

        End Sub

        Private Sub Cookies1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cookies1.TextChanged

        End Sub

        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            'Dim dr As New Browser
            'Browser.Show()
            Dim ele As HtmlElement = BR.WebBrowser1.Document.GetElementById("UserId")
            If ele IsNot Nothing Then
                ele.InnerText = "test"
            End If

            ele = BR.WebBrowser1.Document.GetElementById("Password")
            If ele IsNot Nothing Then
                ele.InnerText = "123456"
            End If

        End Sub
    End Class
    ------------------------------

    code in BR : have no code

    ------------------------------

    code in Browser :

    Imports System.Runtime.InteropServices
    Imports System.Net

    Public Class Browser

        Sub New()
            ' TODO: Complete member initialization
        End Sub

        <DllImport("wininet.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
        Private Shared Function InternetSetCookie(ByVal lpszUrl As String, ByVal lpszCookieName As String, ByVal lpszCookieData As String) As Boolean
        End Function

        <DllImport("wininet.dll", SetLastError:=True)> _
        Private Shared Function DeleteUrlCacheEntry(ByVal lpszUrlName As String) As Long
        End Function

        Public Sub New(ByVal cookies As String, ByVal pageUrl As String)


            Dim url As String = pageUrl
            ' This call is required by the designer.
            InitializeComponent()

            Me.Height = 720
            Me.Width = 1050


            If cookies <> "" Then
                Dim cc As Array = cookies.Split(";")

                If cc.Length > 0 Then
                    For Each i In cc
                        Dim c As Array = i.ToString.Split("=")

                        If c.Length > 1 Then
                            Dim cn As String = c(0)
                            Dim cv As String = c(1)

                            InternetSetCookie(url, cn, cv)
                        End If

                    Next
                End If
            End If


            WebBrowser1.Navigate(url)
            WebBrowser1.ScriptErrorsSuppressed = True

        End Sub

        Private Sub Browser_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'Dim container As New CookieContainer()

            'For Each cookie As String In WebBrowser1.Document.Cookie.Split(";"c)
            '    Dim name As String = cookie.Split("="c)(0)
            '    Dim value As String = cookie.Substring(name.Length + 1)
            '    Dim path As String = "/"
            '    Dim domain As String = "ssr138.com"
            '    'change to your domain name
            '    container.Add(New Cookie(name.Trim(), value.Trim(), path, domain))
            'Next

            'Return
        End Sub
    End Class
    ------------------------

    i can't do it like my first picture on first question......so just i try to do like this

    while open Form1 i will login website in BR.....then i will get Cookies from BR to TextBox in Form 1 then i can login again in Browser without login again......because i will use cookies in textbox that got from BR........i don't know that what i think right or not......if you can find another way to do for me......please design and coding new form for me please,

    Thanks in advanced ,

    Sokunthor



    • Edited by sokunthor Sunday, December 9, 2012 4:05 AM
    Sunday, December 9, 2012 3:46 AM
  • can you give me your email ? i want to send you full project ?
    Sunday, December 9, 2012 4:06 AM
  • It would be nice on the webpage if you added an ID to the Button like on the two textboxes.  I did not look at the cookies.  Here are the changes I made so far

    Imports Microsoft.Win32
    Imports System.Windows
    Public Class Form1
        Dim BR As Browser
        Dim DR As BR
        Private Sub Open1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles Open1.LinkClicked
            BR.GetCookie(Cookies1.Text, "http://www.ssr138.com/number/front/Home.cfm")
        End Sub
        Private Sub Open2_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles Open2.LinkClicked
            BR.GetCookie(Cookies2.Text, "http://www.ssr138.com/number/front/Home.cfm")
            'Process.Start("SessionMerging1\DDM01")
        End Sub
        Private Sub Open3_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles Open3.LinkClicked
            BR.GetCookie(Cookies3.Text, "http://www.ssr138.com/number/front/Home.cfm")
        End Sub
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            BR = New Browser()
            BR.Show()
            DR = New BR()
            DR.Show()
            'SessionMergingDisable()
        End Sub
        Private Sub SessionMergingDisable()
            Dim RegistryPath As String = "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main"
            Dim ValueName = "SessionMerging"
            If My.Computer.Registry.GetValue(RegistryPath, ValueName, Nothing) Is Nothing Then
                ' Set webbrowser isolated session
                Process.Start("SessionMerging0\SessionMerging.reg")
            Else
                Dim SessionMergingCurrent As Int16 = Registry.GetValue(RegistryPath, ValueName, 0)
                If SessionMergingCurrent = 1 Then
                    ' Set webbrowser isolated session
                    Process.Start("SessionMerging0\SessionMerging.reg")
                End If
            End If
        End Sub
        Private Sub Cookies1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cookies1.TextChanged
        End Sub
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            DR.Navigate("http://www.ssr138.com")
            DR.SetID("UserId", "test")
            DR.SetID("Password", "123456")
            DR.SubmitForm0()
        End Sub
    End Class

    Here is the Browser.  I didn't test these changes.  Just made it look like the BR Class

    Imports System.Runtime.InteropServices
    Imports System.Threading
    Imports System.Net
    Public Class Browser
        Private Shared DocumentDone As ManualResetEvent = New ManualResetEvent(False)
        Private Shared NavigatedDone As ManualResetEvent = New ManualResetEvent(False)
        Sub New()
            InitializeComponent()
            'WebBrowser1.Visible = True
            ' TODO: Complete member initialization 
        End Sub
        <DllImport("wininet.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
        Private Shared Function InternetSetCookie(ByVal lpszUrl As String, ByVal lpszCookieName As String, ByVal lpszCookieData As String) As Boolean
        End Function
        <DllImport("wininet.dll", SetLastError:=True)> _
        Private Shared Function DeleteUrlCacheEntry(ByVal lpszUrlName As String) As Long
        End Function
        Public Function GetCookie(ByVal cookies As String, ByVal pageUrl As String) As String
            Dim url As String = pageUrl
            ' This call is required by the designer.
            InitializeComponent()
            Me.Height = 720
            Me.Width = 1050
            If cookies <> "" Then
                Dim cc As Array = cookies.Split(";")
                If cc.Length > 0 Then
                    For Each i In cc
                        Dim c As Array = i.ToString.Split("=")
                        If c.Length > 1 Then
                            Dim cn As String = c(0)
                            Dim cv As String = c(1)
                            InternetSetCookie(url, cn, cv)
                        End If
                    Next
                End If
            End If
            WebBrowser1.Navigate(url)
            WebBrowser1.ScriptErrorsSuppressed = True
        End Function
        Public Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
            DocumentDone.Set()
        End Sub
        Public Sub WebBrowser1__Navigated(ByVal sender As Object, ByVal e As WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated
            NavigatedDone.Set()
        End Sub
    End Class

    Here is the new BR code. Iadded the library reference mshtml.  See commands below in code

    Imports System.Threading 'add reference on COM tab "Microsoft HTML Object Library" Imports mshtml Public Class BR Private Shared DocumentDone As ManualResetEvent = New ManualResetEvent(False) Private Shared NavigatedDone As ManualResetEvent = New ManualResetEvent(False) Sub New() ' This call is required by the Windows Form Designer. InitializeComponent() WebBrowser1.Visible = True ' Add any initialization after the InitializeComponent() call. End Sub Public Sub Navigate(ByVal URL As String) DocumentDone.Reset() WebBrowser1.ScriptErrorsSuppressed = True WebBrowser1.Navigate(URL) Do While (WebBrowser1.ReadyState <> WebBrowserReadyState.Complete) System.Windows.Forms.Application.DoEvents() Loop DocumentDone.WaitOne() End Sub Function GetTag(ByVal ID As String) As List(Of String) Dim results As List(Of String) = Nothing Dim TAGelement As System.Windows.Forms.HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName(Tag) If Not TAGelement Is Nothing Then results = New List(Of String) For Each element As HtmlElement In TAGelement results.Add(element.InnerText) Next End If Return results End Function Function SetTag0(ByVal ID As String, ByVal value As String) As List(Of String) Dim results As List(Of String) = Nothing Dim TAGelement As System.Windows.Forms.HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName(Tag) If Not TAGelement Is Nothing Then TAGelement(0).InnerText = value End If Return results End Function Function GetID(ByVal ID As String) As String Dim IDelement As HtmlElement = WebBrowser1.Document.GetElementById(ID) Return IDelement.InnerText End Function Function SetID(ByVal ID As String, ByVal value As String) As String Dim IDelement As HtmlElement = WebBrowser1.Document.GetElementById(ID) IDelement.InnerText = value Return IDelement.InnerText End Function Sub SubmitForm0() Dim inputTags As System.Windows.Forms.HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("Input") If Not inputTags Is Nothing Then Dim input3 As mshtml.IHTMLInputElement = inputTags(2).DomElement input3.form.submit() Do While (WebBrowser1.ReadyState <> WebBrowserReadyState.Complete) System.Windows.Forms.Application.DoEvents() Loop End If End Sub Public Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted DocumentDone.Set() End Sub Public Sub WebBrowser1__Navigated(ByVal sender As Object, ByVal e As WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated NavigatedDone.Set() End Sub End Class



    jdweng

    Sunday, December 9, 2012 2:44 PM
  • Dear jdweng,

    thanks you in advanced for your help,

    but now can you help me more ?

    I don't want BR and Browser start up with Form1.....also if i click Button1 to login ......BR login website but don't show up......

    Because customer need login only......they don't need to show BR to check website.

    But if they need to check website  ......they will click  Open1_LinkClicked

    and then WebBrowser Form will open ......but no need login again, maybe we need to set the same cookies when we click login First, right ?

    Please help .......i really need your help urgently.


    Sunday, December 9, 2012 4:37 PM
  • You can make the dialog invisible (visible = false) if you don't want to see then forms.  I puposely put the code into the contructor to give you a choice of either making the form visible or invisible.  Constructing the forms at initialization I think is the best way of orgainizing the code.  Then once you log in you get also get data from the webpage as required.  I don't think there is any reason why you can't keep the forms with the webpbrowser hidden while you application is running.

    jdweng

    Sunday, December 9, 2012 7:39 PM
  • Dear Joel Engineer

    I never done this way before, Please give me some code to do ,

    also while i Click Login Buton already.......BR login already done ,if user need to open webBrowser to check website, i wish the webBrowser use cookies with BR also.......so user no need login again.


    Monday, December 10, 2012 3:40 AM
  • I don't know what the webpage looks like after you login.  I suspect the tag "UserID" when login will return a blank when you are not logged in and return the userID when you are logged in.  I don't know for sure without looking at the source code after you are logged in and comparing with the webpage before logging in.

    jdweng

    Monday, December 10, 2012 4:48 AM
  • Really difficult for me to do it, you see this pic
    Login ( Blue Color) only work to login website
    More (Blue Color) click to show WebBrowser......but user no need login again

    also this software can login user more than 100 users but i just print sreen 1 user for you.
    i can't do it like this picture so just try step by step like below code .....

    now it still hopeless because i can't complete it.......
    hope that you can help.............thanks in advanced

    Monday, December 10, 2012 4:56 AM
  • I worked on your project a few hours last night.  I close to gettig the solution.  I'm using the HTTPWebRequest class to connect to the webpage which supports the cookies.  I'm using wireshark to verify that I'm properly making a connection and returning the data from the webpage.  I've verieifed that the cookies I added to the header is being sent properly.  For some reason, I'm getting 1257 bytes in the receive data but the characters are not encoded properly.  The wireshark is showing the data received at the ethernet card being right.  Put the response I get in the software isn't right.  I suspect the problem has to do the with chunk data that is being recieved.

    jdweng

    Monday, December 10, 2012 12:54 PM
  • Dear Joel Engineer

    Can you give some source code ......i never done it before....hope that you give some code to me as example !

    Thank in advanced for your help .


    Monday, December 10, 2012 4:24 PM
  • I will send an update when I get it working.  I've been working on my own projects and keep on getting into issues with HttpWebRequest for the last year.  I never get the code to work properly at every website so this problem.  So this has been a good oportunity to get my code problem solved as well as your problem.


    jdweng

    Monday, December 10, 2012 5:42 PM
  • Dear Joel Engineer

    Thanks you in advanced for your help, also now i got a hope from you ......

    If you free , Please help me more, if i can done this project before your help , i will tell you by this website.

    Thanks

    Tuesday, December 11, 2012 7:07 AM
  • I still trying to get a good solution to the chunked GZIP recieve data.  I hate the string class because it mixes one byte and two byte characters into a single array and it is simple to convert to a byte[].  The HttpResponse.Read() returns a integer which I need to convert to a stream so the GZIP uncompress method will convert the receive data into the html webpage format.  The website is HTML 1.1 which is chunked and the GZIP data starts after the headers.  I think I have to do the following steps

    1) Read the Response Stream and store into a string.  Response string returns an integer so you have to ahndle the odd byte situation.

    2) Convert the string into byte().

    3) Store the byte() into a stream.  GZip requires a stream as an input.

    4) GZip (uncompress mode) the data into a byte().  It may not start at the first location so I may have to locate the start of the data

    5) Convert the byte() into a string.


    jdweng

    Tuesday, December 11, 2012 11:47 AM
  • I got all the problem solved, but did have time to fully test changes.  Should be able to send updates later today.  I'm nut using a WebBrowser Control.  Instead I'm using the MSHTML.dll library.  The webbrowser Control has many of the DOM objects protected while the MSHTML doesn't block the DOM objects from being accessed.  I think this solution will also solve some of my other Web Projects that I haven't been able to complete.

    jdweng

    Wednesday, December 12, 2012 10:16 AM
  • Hi Joel Engineer,

    any update ? share to me please !

    also you do know how to set independent session on webBrowser control.....i have alot of web browser control to login multiple user .....so now all webBrowser Control sharing session so i can't login multiple user in the same website !

    Thanks in advanced !




    Wednesday, December 12, 2012 3:22 PM
  • I should have it done by the end of the day.

    jdweng

    Wednesday, December 12, 2012 5:07 PM
  • Sorry I didn't finish sooner.   I've work 50 hours this weeek at my regular job and plan to work an additional 10 hour today.

    I'm not using webbrowser in this code.  I created an new class HTTP to login.  The code below actually logs in while the IE explorer failed.  The code handles the cookies perfextly.

    Here is the form class.

    Imports Microsoft.Win32
    Imports System.Windows
    Public Class Form1
        Dim BR As Browser
        Dim Web As HTTP
        Private Sub Open1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles Open1.LinkClicked
            BR.GetCookie(Cookies1.Text, "http://www.ssr138.com/number/front/Home.cfm")
        End Sub
        Private Sub Open2_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles Open2.LinkClicked
            BR.GetCookie(Cookies2.Text, "http://www.ssr138.com/number/front/Home.cfm")
            'Process.Start("SessionMerging1\DDM01")
        End Sub
        Private Sub Open3_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles Open3.LinkClicked
            BR.GetCookie(Cookies3.Text, "http://www.ssr138.com/number/front/Home.cfm")
        End Sub
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            BR = New Browser()
            BR.Show()
            Web = New HTTP()
            'SessionMergingDisable()
        End Sub
        Private Sub SessionMergingDisable()
            Dim RegistryPath As String = "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main"
            Dim ValueName = "SessionMerging"
            If My.Computer.Registry.GetValue(RegistryPath, ValueName, Nothing) Is Nothing Then
                ' Set webbrowser isolated session
                Process.Start("SessionMerging0\SessionMerging.reg")
            Else
                Dim SessionMergingCurrent As Int16 = Registry.GetValue(RegistryPath, ValueName, 0)
                If SessionMergingCurrent = 1 Then
                    ' Set webbrowser isolated session
                    Process.Start("SessionMerging0\SessionMerging.reg")
                End If
            End If
        End Sub
        Private Sub Cookies1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cookies1.TextChanged
        End Sub
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim CFID As String = 682314
            Dim CFTOKEN As String = 18466397
            Web.Navigate("http://www.ssr138.com/login_ssr.cfm", CFID, CFTOKEN)
            Web.Login("UserId", "test")
        End Sub
    End Class

    Here is my new HTTP class

    Imports System.Threading
    'add reference on COM tab "Microsoft HTML Object Library"
    Imports mshtml
    Imports System.Net
    Imports System.IO
    Imports System.IO.Compression
    Imports System.Collections.Specialized
    Imports System.Text
    Public Class HTTP
        Private Shared DocumentDone As ManualResetEvent = New ManualResetEvent(False)
        Private Shared NavigatedDone As ManualResetEvent = New ManualResetEvent(False)
        Private request As HttpWebRequest
        Private response As HttpWebResponse
        Dim doc As mshtml.HTMLDocument
        Sub New()
        End Sub
        Public Sub Navigate(ByVal URL As String, ByVal CFID As String, ByVal CFTOKEN As String)
            DocumentDone.Reset()
            'WebBrowser1.ScriptErrorsSuppressed = True
            request = WebRequest.Create(New Uri(URL, UriKind.Absolute))
            Call ConfigureRequest()
            Dim Cookie As String = String.Format("CFID={0}; CFTOKEN={1}", CFID, CFTOKEN)
            request.Headers.Add(HttpRequestHeader.Cookie, Cookie)
            request.Method = "GET"
            request.Method = "GET"
            response = CType(request.GetResponse(), HttpWebResponse)
            'get chunked data
            Dim responseStream As Stream = response.GetResponseStream()
            If response.ContentEncoding.ToLower().Contains("gzip") Then
                responseStream = New GZipStream(responseStream, CompressionMode.Decompress)
            Else
                If response.ContentEncoding.ToLower().Contains("deflate") Then
                    responseStream = New DeflateStream(responseStream, CompressionMode.Decompress)
                End If
            End If
            Dim Reader As StreamReader = New StreamReader(responseStream, Encoding.Default)
            Dim HtmlText As String = Reader.ReadToEnd()
            response.Close()
            responseStream.Close()
        End Sub
        Public Sub Login(ByVal UserID As String, ByVal Password As String)
            Dim PostData As String = String.Format("UserId={0}&Password={1}&lang=EN", _
               UserID, Password)
            Dim headers As WebHeaderCollection = response.Headers
            ' Get redirected uri
            Dim uri As String = response.ResponseUri.AbsoluteUri
            request = WebRequest.Create(New Uri(uri, UriKind.Absolute))
            ConfigureRequest()
            'Check for any cookies
            Dim Cookie As String = ""
            If headers("Set-Cookie") <> Nothing Then
                Cookie = headers("Set-Cookie")
            End If
            Dim collHeader As NameValueCollection = New NameValueCollection()
            If (Cookie.Length > 0) Then
                request.Headers.Add(HttpRequestHeader.Cookie, Cookie)
            End If
            request.Method = "POST"
            Dim lbPostBuffer() As Byte = Encoding.Default.GetBytes(PostData)
            request.ContentLength = lbPostBuffer.Length
            request.ContentType = "application/x-www-form-urlencoded"
            Dim PostStream As Stream = request.GetRequestStream()
            PostStream.Write(lbPostBuffer, 0, lbPostBuffer.Length)
            response = CType(request.GetResponse(), HttpWebResponse)
            PostStream.Close()
        End Sub
        Sub ConfigureRequest()
            request.Accept = "*/*"
            request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us")
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;" & _
                                ".NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; InfoPath.2;" & _
                                ".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)"
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate")
            request.UseDefaultCredentials = True
            request.PreAuthenticate = True
            request.AllowAutoRedirect = True
        End Sub
     
    End Class


    jdweng

    Friday, December 14, 2012 9:45 AM
  • Hi jdweng ! sorry now i don't how this code work....and i try to copy code to run but still not working,

    now all of my form .... i am using your code in first post .
    and also i added one TextBox to get Cookies from first login.....then when user click Openlink , it will WebBrowser with this cookies,

    But now the problem all webBrowser Control shared session/Cookies , so now i can't login or open WebBrowser with multiple user in the same website ,

    Can you help me to set Independence session on WebBrowser Control , i mean multiple user login on WebBrowser Control in the same website

    thanks in advanced


    • Edited by sokunthor Friday, December 14, 2012 4:56 PM
    Friday, December 14, 2012 4:53 PM
  • You missed this line in the Load function.

    Web = New HTTP()

    I have to find out if I can get into the Dom Class of a WebBrowser Control.  I think I have to develope my own webbrowser class that inherits the standard WebBrowser.  Not sure.  I wil think about it over the weekend.


    jdweng

    Friday, December 14, 2012 6:27 PM
  • You missed this line in the Load function.

    Web = New HTTP()

    I have to find out if I can get into the Dom Class of a WebBrowser Control.  I think I have to develope my own webbrowser class that inherits the standard WebBrowser.  Not sure.  I wil think about it over the weekend.


    jdweng

    Friday, December 14, 2012 6:28 PM
  • i am interesting with HTTP class, but i don't know how it work to solve my problem !

    can you help me ?
    Saturday, December 15, 2012 7:15 AM
  • I realized the HTTP Class doesn't solve your problem because you need a browser and there is no way of linking the HttpWebRequest that I know.  I've know have been trying to add a cookie to a webrowser.  It seems the whole world as "tried" to do this and none of the solutions I tried has worked.  I'm still trying.  I know if I go back to a old version of the webbrowser I can get it to work.


    jdweng

    Saturday, December 15, 2012 9:34 AM
  • Hmmmm really difficult :(
    Saturday, December 15, 2012 3:49 PM
  • I  shouldn't be difficult.  The same thing works in other libraries.  Just not the WebBrowser control.

    jdweng

    Saturday, December 15, 2012 5:28 PM
  • This code does what you specified.  Start a new WF app and replace the Form1 code with:

    Public Class Form1
      Dim BtnsText() As String = {"Login", "Browser"}
      Dim Btns(BtnsText.Length - 1) As Button
      Dim Frm2 As Form2
      Dim UserId As String = "UserId"
      Dim Password As String = "Password"
      Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Dim Pad As Integer = 15
        For I As Integer = 0 To Btns.Length - 1
          Btns(I) = New Button
          Btns(I).Text = BtnsText(I)
          Btns(I).Top = Pad
          Btns(I).Left = Pad + If(I > 0, Pad + Btns(I - 1).Width, 0)
          AddHandler Btns(I).Click, AddressOf Btn_Clicked
        Next
        Dim R As Rectangle = Btns(Btns.Length - 1).Bounds
        Me.ClientSize = New Size(R.Right + Pad, R.Bottom + Pad)
        Frm2 = New Form2
        AddHandler Frm2.WB.DocumentCompleted, AddressOf WB_Complete
        Frm2.WB.Navigate("www.ssr138.com")
      End Sub
      Sub Btn_Clicked(sender As Object, e As EventArgs)
        Select Case DirectCast(sender, Button).Text
          Case "Login"
            Dim Elements As HtmlElementCollection = Frm2.WB.Document.Body.GetElementsByTagName("Input")
            Dim UserIdFound, PasswordFround, LoginFound As Boolean
            For Each El As HtmlElement In Elements
              If El.Name = "UserId" Then
                El.InnerText = "UserId"
                UserIdFound = True
                Continue For
              End If
              If El.Name = "Password" Then
                El.InnerText = "Password"
                PasswordFround = True
                Continue For
              End If
              If El.OuterHtml.Contains("alt=Login") Then
                LoginFound = True
                El.InvokeMember("Click")
              End If
            Next
            If UserIdFound AndAlso PasswordFround AndAlso LoginFound Then
              Btns(0).Parent = Nothing
              Btns(1).Parent = Me
            End If
          Case "Browser"
            Me.Hide()
            Frm2.Bounds = New Rectangle(100, 100, 600, 800)
            Frm2.WB.Parent = Frm2
            Frm2.ShowDialog()
            Me.Close()
        End Select
      End Sub
      Sub WB_Complete(sender As Object, e As WebBrowserDocumentCompletedEventArgs)
        If Frm2.WB.Url = e.Url AndAlso Frm2.WB.ReadyState = WebBrowserReadyState.Complete Then
          Btns(0).Parent = Me
        End If
      End Sub
    End Class
    Class Form2
      Inherits Form
      Friend WithEvents WB As New WebBrowser
      Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)
        WB.Dock = DockStyle.Fill
        WB.Parent = Me
      End Sub
    End Class

    Sunday, December 16, 2012 5:44 AM
  • hi JohnWein

    Now i don't know where to replace your code , and also my problem is

    all webBrowser Control shared session/Cookies , so now i can't login or open WebBrowser with multiple user in the same website ,

    Can you help me to set Independence session on WebBrowser Control , i mean multiple user login on WebBrowser Control in the same website.

    Please kindly to find my project in this link and please help me to solve the problem download my project

    Sunday, December 16, 2012 8:25 AM
  • hi JohnWein

    Now i don't know where to replace your code , and also my problem is

    all webBrowser Control shared session/Cookies , so now i can't login or open WebBrowser with multiple user in the same website ,

    Can you help me to set Independence session on WebBrowser Control , i mean multiple user login on WebBrowser Control in the same website.

    Please kindly to find my project in this link and please help me to solve the problem download my project


    also in this project i don't show you for my account ( username & password ) hope you understand !
    Sunday, December 16, 2012 8:27 AM
  • "Now i don't know where to replace your code."

    Start a new WF app and replace the Form1 code

    When you start a new WF app, you should have a Form1.vb code file that looks like:

    Sunday, December 16, 2012 9:34 AM
  • After replacing the code on Form1.vb, Form1.vb should look like this:


    • Edited by JohnWein Sunday, December 16, 2012 9:44 AM
    Sunday, December 16, 2012 9:42 AM
  • Replace the values of the UserId and Password variables and run the program.
    Sunday, December 16, 2012 9:44 AM
  • Oh cool ! it working fine ! but if i have account more than one to login in the same website  and they can show browser !

    how can i edit this code ?

    i am trying to edit it but still not working for multiple user and browser !

    Please help me more !

    Thanks in advanced


    • Edited by sokunthor Sunday, December 16, 2012 11:04 AM
    Sunday, December 16, 2012 10:38 AM
  • John: You r code idd exactly what my code did except you put it in the form rather than a seperate class.  The real problem is getting the cookie to work.

    jdweng

    Sunday, December 16, 2012 10:47 AM
  • John: You r code idd exactly what my code did except you put it in the form rather than a seperate class.  The real problem is getting the cookie to work.

    jdweng

    My code is self contained code that does what the OP requested in his OP.  I can't  find a post of yours in this thread that does the same thing.  If the OP has a new problem, a new thread should be started.

    • Edited by JohnWein Sunday, December 16, 2012 12:50 PM
    Sunday, December 16, 2012 12:49 PM
  • I've been working on this thread for a week.  Read the title of the thread.  sokunthor wants one webbrowser control but allow multiple users to access the one webbrowser.  So he wants to assign a unique cookie to each user and then include the cookie with each Naviagate() method.  Navigate can have 4 parameters and the last can be a header, but it doesn't work with a coookie header.  Neither does Browser1.Document.Cookie.

    jdweng

    Sunday, December 16, 2012 1:04 PM
  • we can use multiple webbrowser control or one webbrowser control .....it no problem but problem all webbrowser control can't login multiple account.....because shared session/cookies !

    Multiple logins have nothing to do with the subject of this thread or your OP.

    Mark the posts that answer the question of this thread and continue on your next thread:  Un-Share Session Cookies of webbrowser control

    Sunday, December 16, 2012 3:43 PM
  • OK now i going tell you more with one picture inUn-Share Session Cookies of webbrowser control
    Sunday, December 16, 2012 4:53 PM
  • sokunthor: I totally disagree with John's assestment of the problem.  The problem is definely a issue with the cookies.  To be able to have multiple multiple connections with only one webbrowser application you need to be able to set the cookies.  I can set the cookies using an HttpWebRequest class.  I haven't been able to do the same with an IE browser.  I can set any header except the cookies.  I suspect that Mcirosoft has intentionally block the cookies so hackers can't can't do impersonations (not sure).  If I get a chance today I will try one more time to see if I can set the cookies using an IE application.

    jdweng

    Friday, December 28, 2012 11:50 AM