473,786 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Debugging ScreenScrape Code

Hi All,
I have a very small screen scrape application, that has a small
problem. when I run the app and I have fiddler(an http tool to view
what is being sent by the requests/responses,
http://www.fiddlertool.com) the app works, and I am able to login to
the (intranet)websi te. If do not run the app while fiddler is running,
it does not work(the app returns html of the login page, instead of the
target page).

Here is the code, thanks in advance

Note it maybe easier to copy and paste this code into notepad to
view....

/*
* User: Mccollid
* Date: 10/3/2005
* Time: 11:25 AM
*
*/
using System;
using System.Drawing;
using System.Windows. Forms;
using System.Net;
using System.IO;
using System.Text;
using System.Web;

namespace ScreenScraper
{
/// <summary>
/// Description of MainForm.
/// </summary>
public class MainForm : System.Windows. Forms.Form
{
private System.Windows. Forms.Button button1;
private System.Windows. Forms.TextBox textBox1;
private string LOGIN_URL;
private string USERNAME;
private string PASSWORD;
private string SECRET_PAGE_URL ;
private string COOKIEHOLDER;

public MainForm()
{
//
// The InitializeCompo nent() call is required for Windows Forms
designer support.
//

InitializeCompo nent();

//
// TODO: Add constructor code after the InitializeCompo nent() call.
//
}

[STAThread]
public static void Main(string[] args)
{
Application.Run (new MainForm());
}
void Button1Click(ob ject sender, System.EventArg s e)
{
this.textBox1.T ext="Connecting ...";
this.LOGIN_URL= "http://loginpage"; this.SECRET_PAG E_URL
="http://targetpage";
this.USERNAME ="UserName";
this.PASSWORD ="Password";

HttpWebRequest webrequest=WebR equest.Create(L OGIN_URL) as
HttpWebRequest;
StreamReader responseReader= new
StreamReader(we brequest.GetRes ponse().GetResp onseStream());

string responseData = responseReader. ReadToEnd();
//this.textBox1.T ext=responseDat a;

//extract PathInfo value and build our post data
string pathInfo=Extrac tPathInfo(respo nseData);
MessageBox.Show (pathInfo,pathI nfo);
//string
postData=String .Format("pathIn fo={0}&username ={1}&password={ 2}&Login=Login" ,
pathInfo, USERNAME, PASSWORD);
string
postData=String .Format("userna me={1}&password ={2}&pathInfo={ 0}",
pathInfo, USERNAME, PASSWORD);

this.textBox1.T ext=postData;

//have a cookie container ready to receive the forms auth cookie
CookieContainer cookies=new CookieContainer ();

//now post to the login form
webrequest=WebR equest.Create(L OGIN_URL) as HttpWebRequest;
webrequest.Meth od="Post";
webrequest.Cred entials = CredentialCache .DefaultCredent ials;
webrequest.User Agent="User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 1.0.3705)";
webrequest.Acce pt="Accept: image/gif, image/x-xbitmap, image/jpeg,
image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel,
application/vnd.ms-powerpoint, application/msword, */*";
webrequest.Cont entType="applic ation/x-www-form-urlencoded";

webrequest.Allo wAutoRedirect=t rue;
webrequest.Cook ieContainer=coo kies;

webrequest.Refe rer="http://unatime.merck.c om/unatime/action/home";


//write the form values into the request message
StreamWriter requestWriter = new
StreamWriter(we brequest.GetReq uestStream());
requestWriter.W rite(postData);
requestWriter.C lose();
//we don't need the contents of the response, just the cookie

try
{
webrequest.GetR esponse().Close ();
}
catch (WebException ee)
{
// MessageBox.Show (ee.Message);
// this.textBox1.T ext=ee.Message;
}

//webrequest.GetR esponse().Close ();

//now we can send out cookie along with a request for the protected
page
webrequest = WebRequest.Crea te(SECRET_PAGE_ URL) as HttpWebRequest;
webrequest.Meth od="Post";
webrequest.Cred entials = CredentialCache .DefaultCredent ials;
webrequest.User Agent="User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 1.0.3705)";
webrequest.Acce pt="Accept: image/gif, image/x-xbitmap, image/jpeg,
image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel,
application/vnd.ms-powerpoint, application/msword, */*";
webrequest.Cont entType="applic ation/x-www-form-urlencoded";
webrequest.Allo wAutoRedirect=t rue;
webrequest.Cook ieContainer=coo kies;
webrequest.Refe rer="http://unatime.merck.c om/unatime/action/home";
responseReader= new
StreamReader(we brequest.GetRes ponse().GetResp onseStream());

//StreamReader readStream = new StreamReader
(webrequest.Get Response().GetR esponseStream() , Encoding.UTF8);

//and read the response
responseData = responseReader. ReadToEnd();
responseReader. Close();

//Response.Write( responseData);
this.textBox1.T ext=responseDat a;

}
private string ExtractPathInfo (string s)
{
string viewStateNameDe limiter="pathIn fo";
string valueDelimiter= "value=\"";

int viewStateNamePo sition=s.IndexO f(viewStateName Delimiter);
int viewStateValueP osition=s.Index Of(valueDelimit er,
viewStateNamePo sition);

int viewStateStartP osition=viewSta teValuePosition +
valueDelimiter. Length;
//int viewStateEndPos ition=s.IndexOf ("\"", viewStateStartP osition);
int viewStateEndPos ition=s.IndexOf ("\"", viewStateStartP osition);
return
HttpUtility.Url EncodeUnicode(s .Substring(view StateStartPosit ion,
viewStateEndPos ition-viewStateStartP osition));

}

}
}

Nov 17 '05 #1
6 1821
You are creating cookie container, which creates an empty cookie container.
You are assigning it to each web request. However, when you get your web
response, you aren't saving the cookies into the cookie container.
Therefore, on every call, you are failing to catch the cookies. It works
with the utility because that utility is catching the cookies for you.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"Dan McCollick" <mc*********@ho tmail.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
Hi All,
I have a very small screen scrape application, that has a small
problem. when I run the app and I have fiddler(an http tool to view
what is being sent by the requests/responses,
http://www.fiddlertool.com) the app works, and I am able to login to
the (intranet)websi te. If do not run the app while fiddler is running,
it does not work(the app returns html of the login page, instead of the
target page).

Here is the code, thanks in advance

Note it maybe easier to copy and paste this code into notepad to
view....

/*
* User: Mccollid
* Date: 10/3/2005
* Time: 11:25 AM
*
*/
using System;
using System.Drawing;
using System.Windows. Forms;
using System.Net;
using System.IO;
using System.Text;
using System.Web;

namespace ScreenScraper
{
/// <summary>
/// Description of MainForm.
/// </summary>
public class MainForm : System.Windows. Forms.Form
{
private System.Windows. Forms.Button button1;
private System.Windows. Forms.TextBox textBox1;
private string LOGIN_URL;
private string USERNAME;
private string PASSWORD;
private string SECRET_PAGE_URL ;
private string COOKIEHOLDER;

public MainForm()
{
//
// The InitializeCompo nent() call is required for Windows Forms
designer support.
//

InitializeCompo nent();

//
// TODO: Add constructor code after the InitializeCompo nent() call.
//
}

[STAThread]
public static void Main(string[] args)
{
Application.Run (new MainForm());
}
void Button1Click(ob ject sender, System.EventArg s e)
{
this.textBox1.T ext="Connecting ...";
this.LOGIN_URL= "http://loginpage"; this.SECRET_PAG E_URL
="http://targetpage";
this.USERNAME ="UserName";
this.PASSWORD ="Password";

HttpWebRequest webrequest=WebR equest.Create(L OGIN_URL) as
HttpWebRequest;
StreamReader responseReader= new
StreamReader(we brequest.GetRes ponse().GetResp onseStream());

string responseData = responseReader. ReadToEnd();
//this.textBox1.T ext=responseDat a;

//extract PathInfo value and build our post data
string pathInfo=Extrac tPathInfo(respo nseData);
MessageBox.Show (pathInfo,pathI nfo);
//string
postData=String .Format("pathIn fo={0}&username ={1}&password={ 2}&Login=Login" ,
pathInfo, USERNAME, PASSWORD);
string
postData=String .Format("userna me={1}&password ={2}&pathInfo={ 0}",
pathInfo, USERNAME, PASSWORD);

this.textBox1.T ext=postData;

//have a cookie container ready to receive the forms auth cookie
CookieContainer cookies=new CookieContainer ();

//now post to the login form
webrequest=WebR equest.Create(L OGIN_URL) as HttpWebRequest;
webrequest.Meth od="Post";
webrequest.Cred entials = CredentialCache .DefaultCredent ials;
webrequest.User Agent="User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 1.0.3705)";
webrequest.Acce pt="Accept: image/gif, image/x-xbitmap, image/jpeg,
image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel,
application/vnd.ms-powerpoint, application/msword, */*";
webrequest.Cont entType="applic ation/x-www-form-urlencoded";

webrequest.Allo wAutoRedirect=t rue;
webrequest.Cook ieContainer=coo kies;

webrequest.Refe rer="http://unatime.merck.c om/unatime/action/home";


//write the form values into the request message
StreamWriter requestWriter = new
StreamWriter(we brequest.GetReq uestStream());
requestWriter.W rite(postData);
requestWriter.C lose();
//we don't need the contents of the response, just the cookie

try
{
webrequest.GetR esponse().Close ();
}
catch (WebException ee)
{
// MessageBox.Show (ee.Message);
// this.textBox1.T ext=ee.Message;
}

//webrequest.GetR esponse().Close ();

//now we can send out cookie along with a request for the protected
page
webrequest = WebRequest.Crea te(SECRET_PAGE_ URL) as HttpWebRequest;
webrequest.Meth od="Post";
webrequest.Cred entials = CredentialCache .DefaultCredent ials;
webrequest.User Agent="User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 1.0.3705)";
webrequest.Acce pt="Accept: image/gif, image/x-xbitmap, image/jpeg,
image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel,
application/vnd.ms-powerpoint, application/msword, */*";
webrequest.Cont entType="applic ation/x-www-form-urlencoded";
webrequest.Allo wAutoRedirect=t rue;
webrequest.Cook ieContainer=coo kies;
webrequest.Refe rer="http://unatime.merck.c om/unatime/action/home";
responseReader= new
StreamReader(we brequest.GetRes ponse().GetResp onseStream());

//StreamReader readStream = new StreamReader
(webrequest.Get Response().GetR esponseStream() , Encoding.UTF8);

//and read the response
responseData = responseReader. ReadToEnd();
responseReader. Close();

//Response.Write( responseData);
this.textBox1.T ext=responseDat a;

}
private string ExtractPathInfo (string s)
{
string viewStateNameDe limiter="pathIn fo";
string valueDelimiter= "value=\"";

int viewStateNamePo sition=s.IndexO f(viewStateName Delimiter);
int viewStateValueP osition=s.Index Of(valueDelimit er,
viewStateNamePo sition);

int viewStateStartP osition=viewSta teValuePosition +
valueDelimiter. Length;
//int viewStateEndPos ition=s.IndexOf ("\"", viewStateStartP osition);
int viewStateEndPos ition=s.IndexOf ("\"", viewStateStartP osition);
return
HttpUtility.Url EncodeUnicode(s .Substring(view StateStartPosit ion,
viewStateEndPos ition-viewStateStartP osition));

}

}
}

Nov 17 '05 #2
When I try to add cookies my request times out?? I have indicated
where I think the problem lies(about half way down)...but I truely do
not understand.

HttpWebRequest wrequest= (HttpWebRequest ) WebRequest.Crea te(LOGIN_URL)
as HttpWebRequest;

StreamReader responseReader = new
StreamReader(wr equest.GetRespo nse().GetRespon seStream());

string responseData =responseReader .ReadToEnd().To String();
responseReader. Close();

string pathInfo = ExtractPathInfo (responseData);
string postData=String .Format("userna me={1}&password ={2}&pathInfo={ 0}",
pathInfo, USERNAME, PASSWORD);

wrequest=(HttpW ebRequest) WebRequest.Crea te(LOGIN_URL) as
HttpWebRequest;
wrequest.Method ="Post";
wrequest.Conten tType = "applicatio n/x-www-form-urlencoded";
wrequest.Cookie Container= new CookieContainer ();

MessageBox.Show ("Cookie Section");
//cookies collected
//WHEN EXECUTING THIS CODE APP TIMES OUT
HttpWebResponse wresponse = (HttpWebRespons e) wrequest.GetRes ponse();
wresponse.Cooki es =
wrequest.Cookie Container.GetCo okies(wrequest. RequestUri);
this.textBox1.T ext+=wresponse. StatusDescripti on;

StreamWriter rwriter= new StreamWriter(wr equest.GetReque stStream());
rwriter.Write(p ostData);
rwriter.Close() ;
MessageBox.Show ("Target");
wrequest = (HttpWebRequest ) WebRequest.Crea te(SECRET_PAGE_ URL) as
HttpWebRequest;

//wrequest.Cookie Container= new CookieContainer ();
responseReader = new
StreamReader(wr equest.GetRespo nse().GetRespon seStream());

responseData=re sponseReader.Re adToEnd();
responseReader. Close();

this.textBox1.T ext +=responseData. ToString();

this.textBox1.T ext+="Done";

Nov 17 '05 #3
I am having trouble getting the HttpWebRequest. method ="Post"; When I
have this in the code, and run the app through fiddler, it is still
showing that a get was sent? am I calling this wrong?(it is
wrequest.method ="post"; in my code).

Thanks
Dan

Nov 17 '05 #4
Also, when I check fiddler, it is saying that there are three cookies
being returned. Yet if i do a
MessageBox.Show (wresponse.getc ookies(wrequest .request.uri).c ount.toString() );
i only return 2? I can't figure out why this code works
sometimes...and then doesn't work, then works...then doesn't work...

Nov 17 '05 #5
Hi Dan,

First suggestion: use a different variable for the first request from the
second one.

Second suggestion: create the cookie container into a seperate variable
(like you were doing in the first snippet you posted)

Third suggestion: copy the cookies OUT of the first response into the cookie
container. Then assign these cookies IN to the second request.

You are discarding the cookies every time. The only reason it works at all
is by accident, because you've been using the same variable. However,
memory cookies won't transfer, only persistent cookies will, and your site
expects the memory cookie to hold the login token (pretty normal behavior).

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"Dan McCollick" <mc*********@ho tmail.com> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
When I try to add cookies my request times out?? I have indicated
where I think the problem lies(about half way down)...but I truely do
not understand.

HttpWebRequest wrequest= (HttpWebRequest ) WebRequest.Crea te(LOGIN_URL)
as HttpWebRequest;

StreamReader responseReader = new
StreamReader(wr equest.GetRespo nse().GetRespon seStream());

string responseData =responseReader .ReadToEnd().To String();
responseReader. Close();

string pathInfo = ExtractPathInfo (responseData);
string postData=String .Format("userna me={1}&password ={2}&pathInfo={ 0}",
pathInfo, USERNAME, PASSWORD);

wrequest=(HttpW ebRequest) WebRequest.Crea te(LOGIN_URL) as
HttpWebRequest;
wrequest.Method ="Post";
wrequest.Conten tType = "applicatio n/x-www-form-urlencoded";
wrequest.Cookie Container= new CookieContainer ();

MessageBox.Show ("Cookie Section");
//cookies collected
//WHEN EXECUTING THIS CODE APP TIMES OUT
HttpWebResponse wresponse = (HttpWebRespons e) wrequest.GetRes ponse();
wresponse.Cooki es =
wrequest.Cookie Container.GetCo okies(wrequest. RequestUri);
this.textBox1.T ext+=wresponse. StatusDescripti on;

StreamWriter rwriter= new StreamWriter(wr equest.GetReque stStream());
rwriter.Write(p ostData);
rwriter.Close() ;
MessageBox.Show ("Target");
wrequest = (HttpWebRequest ) WebRequest.Crea te(SECRET_PAGE_ URL) as
HttpWebRequest;

//wrequest.Cookie Container= new CookieContainer ();
responseReader = new
StreamReader(wr equest.GetRespo nse().GetRespon seStream());

responseData=re sponseReader.Re adToEnd();
responseReader. Close();

this.textBox1.T ext +=responseData. ToString();

this.textBox1.T ext+="Done";

Nov 17 '05 #6
Thank you so much. Works great now.

Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3644
by: R Millman | last post by:
under ASP.NET, single stepping in debug mode appears not to stop within event procedures. i.e. 1) Create web page with submit button and event procedure for the click event in the code behind page, 2) Breakpoint in the Page_Load, 3) debug the web page and click the submit button, 4) "step into" under debug several times, 5) The debugger does not stop at any of the statements in the click event handler. A breakpoint is needed in each...
0
3228
by: ZMan | last post by:
Scenario: This is about debugging server side scripts that make calls to middle-tier business DLLs. The server side scripts are legacy ASP 3.0 pages, and the DLLs are managed DLLs converted/developed with VB.NET. What I want from debugging is to be able to step into the methods in the DLLs called from ASP scripts using Visual Studio .NET. Background: For typical script debugging issues, you can read and follow the two documents on...
5
2958
by: Velvet | last post by:
Can someone tell me to what process I need to attach to be able to step through my classic ASP code in VS.net 2003. I'm working on an XP box with IIS installed. I also have VS.net 2005 (The final, never installed beta) installed on this box if it makes a difference (I did not install VS Development Web Server as I'm already using the XP web server). I've seen that I need to attach to the native IIS engine, but I don't know what it's...
5
3647
by: snicks | last post by:
I'm trying to exec a program external to my ASP.NET app using the following code. The external app is a VB.NET application. Dim sPPTOut As String sPPTOut = MDEPDirStr + sID + ".ppt" Dim p As New System.Diagnostics.Process 'p.Start(MDEPDirStr & "macrun.exe", sPPTOut) p.Start("C:\WINDOWS\SYSTEM32\CALC.EXE") 'p.Start("C:\WINDOWS\SYSTEM32\macrun.exe", sPPTOut)
8
2216
by: razael1 | last post by:
I am putting debugging messages into my program by putting blocks that look like this: #ifdef DEBUG errlog << "Here is some information"; #endif All these #ifdef blocks make the code bulky and harder to read, so I'd like to do something where I put: errMsg("Here is some information");
5
7802
by: phnimx | last post by:
Hi , We have developed a number of plug-in .NET Library Components that we typically deploy with our various applications by installing them into the GAC. Each of the applications contains an app.config file referencing arbitrary versions of the plug-in components they wish to consume. Here's the problem: Assuming I have installed any one of our application software,
5
2814
by: rn5a | last post by:
Can someone please suggest me a text editor especially for DEBUGGING ASP scripts apart from Microsoft Visual Interdev? I tried using Visual Interdev & created a project but Interdev generates some error related to FrontPage extensions. I couldn't exactly understand the error. I tried to create the project in C: \Inetpub\wwwroot. If I just open a ASP file (by navigating to the File-->Open File... menu), then Interdev doesn't give the...
0
7335
jwwicks
by: jwwicks | last post by:
Introduction This tutorial describes how to use Visual Studio to create a new C++ program, compile/run a program, resume work on an existing program and debug a program. It is aimed at the beginning CIS student who is struggling to get their programs working. I work in the computer lab at the college I'm attending and I see many students who don't know how to use the IDE for best results. Visual Studio automatically creates a number of...
2
20851
jwwicks
by: jwwicks | last post by:
C/C++ Programs and Debugging in Linux This tutorial will give you a basic idea how to debug a program in Linux using GDB. As you are aware Visual Studio doesn’t run on Linux so you have to use some of the tools provided on the command-line. If you hate the command line tools, get over it since you’re bound to be using them at some point in your career. All commands in Linux ARE case sensitive so capital letters are different from lowercase...
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9496
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9961
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8989
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5397
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4066
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3669
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.