|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace WindowsFormsApplicationDW
{
public partial class Form1 : Form
{
string sWebPath = "http://www.miosito.it/"; //change this path with WebApplicationTest's virtual path
string sLocalPath = @"c:\"; //change this path, physical path of a file downloading (write permission)
string sMyName = "erika";
string sPageLogin = "login.aspx";
string sPageDw = "dw.aspx";
bool bFirstTime;
StreamWriter swWriterL;
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
const int INTERNET_COOKIE_HTTPONLY = 0x00002000;
private string GetGlobalCookies(string uri)
{
uint uiDataSize = 2048;
StringBuilder sbCookieData = new StringBuilder((int)uiDataSize);
if (InternetGetCookieEx(uri, null, sbCookieData, ref uiDataSize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero) && sbCookieData.Length > 0)
{
return sbCookieData.ToString().Replace(";", ",");
}
else
{
return null;
}
}
public Form1()
{
InitializeComponent();
bFirstTime = true;
timer1.Start(); // Then I start timer
swWriterL = new StreamWriter(System.AppDomain.CurrentDomain.BaseDirectory + "log.log", true); // Inizializate log
swWriterL.WriteLine("---------------------------------");
swWriterL.WriteLine("Start working session " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
webBrowser1.Navigate(sWebPath + sPageLogin);
}
private void timer1_Tick(object sender, EventArgs e)
{
swWriterL.WriteLine("Error timeout application");
swWriterL.Close();
timer1.Stop();
this.Close();
Application.Exit();
}
//extract __VIEWSTATE __EVENTVALIDATION from input type hidden
private string ExtractInputHidden(string str, string name)
{
string sRit = "";
string sPattern = "(?<=" + name + "\" value=\")(?<val>.*?)(?=\")";
Match match = Regex.Match(str, sPattern);
if (match.Success)
{
sRit = match.Groups["val"].Value;
sRit = HttpUtility.UrlEncodeUnicode(sRit);
}
return sRit;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//login page
if ((bFirstTime == true) && (e.Url.ToString().Contains(sPageLogin))) //only first time
{
bFirstTime = false;
HtmlElement heElement;
heElement = (HtmlElement)webBrowser1.Document.GetElementById("UserEmail");
heElement.InnerText = "name";
heElement = (HtmlElement)webBrowser1.Document.GetElementById("UserPass");
heElement.InnerText = "pass";
System.Threading.Thread.Sleep(2000);
heElement = (HtmlElement)webBrowser1.Document.GetElementById("Submit1");
heElement.InvokeMember("click");
System.Threading.Thread.Sleep(2000);
webBrowser1.Navigate(sWebPath + sPageDw);
}
else
if (e.Url.ToString().Contains(sPageDw) == true)
{
try
{
//first request to extract __VIEWSTATE and __EVENTVALIDATION and cookie use get
string sPageData;
string PathRemote = sWebPath + sPageDw;
string sTmpCookieString = GetGlobalCookies(webBrowser1.Url.AbsoluteUri);
HttpWebRequest fstRequest = (HttpWebRequest)WebRequest.Create(PathRemote);
fstRequest.Method = "GET";
fstRequest.CookieContainer = new System.Net.CookieContainer();
fstRequest.CookieContainer.SetCookies(webBrowser1.Document.Url, sTmpCookieString);
HttpWebResponse fstResponse = (HttpWebResponse)fstRequest.GetResponse();
StreamReader sr = new StreamReader(fstResponse.GetResponseStream());
sPageData = sr.ReadToEnd();
sr.Close();
string sViewState = ExtractInputHidden(sPageData, "__VIEWSTATE");
string sEventValidation = this.ExtractInputHidden(sPageData, "__EVENTVALIDATION");
//second request post all values and save generated file
string sUrl = sWebPath + sPageDw;
HttpWebRequest hwrRequest = (HttpWebRequest)WebRequest.Create(sUrl);
hwrRequest.Method = "POST";
hwrRequest.CookieContainer = new System.Net.CookieContainer();
string sPostData = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=" + sViewState + "&__EVENTVALIDATION=" + sEventValidation + "&Name=" + sMyName + "&Button1=Button";
byte[] bByteArray = Encoding.UTF8.GetBytes(sPostData);
hwrRequest.ContentType = "application/x-www-form-urlencoded";
hwrRequest.CookieContainer.SetCookies(webBrowser1.Document.Url, sTmpCookieString);
hwrRequest.ContentLength = bByteArray.Length;
Stream sDataStream = hwrRequest.GetRequestStream();
sDataStream.Write(bByteArray, 0, bByteArray.Length);
sDataStream.Close();
using (WebResponse response = hwrRequest.GetResponse())
{
using (sDataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(sDataStream);
{
//get original file name
string sHeader = response.Headers["Content-Disposition"];
int iFileNameStartIndex = sHeader.IndexOf("filename=") + "filename=".ToString().Length;
int iFileNameLength = sHeader.Length - iFileNameStartIndex;
string sFileName = sHeader.Substring(iFileNameStartIndex, iFileNameLength);
string sResponseFromServer = reader.ReadToEnd();
//save the file
FileStream fs = File.Open(sLocalPath + sFileName, FileMode.OpenOrCreate, FileAccess.Write);
Byte[] info = new System.Text.UTF8Encoding(true).GetBytes(sResponseFromServer);
fs.Write(info, 0, info.Length);
fs.Close();
swWriterL.WriteLine("saved");
reader.Close();
sDataStream.Close();
response.Close();
} //end StreamReader
} //end dataStream
}//end WebResponse
}//end try
catch (Exception eccezione)
{
swWriterL.WriteLine("Error: " + eccezione.Message);
swWriterL.Close();
}
swWriterL.Close();
this.Close(); //close form
Application.Exit(); //close app
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.