c# autologin website and view it - c#

Good morning everybody.
I simply want to automatical login to the website when I start the C# program.
So I started a new Webform project, simply added a button and a website frame.
Main:
namespace SG_Helper
{
static class Program
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
And the form with a function behind the button:
namespace SG_Helper
{
public partial class Form1 : Form
{
public string cookie = string.Empty;
public WebClient wc = new WebClient();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string loginData = "loginname=***&loginpwd=***&switch=login";
wc.BaseAddress = #"http://wbk2.schulterglatze.de/";
string cookie = string.Empty;
wc.Headers.Add("Content-Type: application/x-www-form-urlencoded");
wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
wc.Headers.Add("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
wc.Headers.Add("Accept-Encoding: identity");
wc.Headers.Add("Accept-Language: en-US,en;q=0.8");
wc.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3");
wc.Headers.Add("Cookie", cookie);
string response = wc.UploadString("http://wbk2.schulterglatze.de/?ref=0", "POST", loginData);
cookie = wc.ResponseHeaders["Set-Cookie"].ToString();
//System.Windows.Forms.MessageBox.Show(response);
webBrowser1.DocumentText = wc.DownloadString("http://wbk2.schulterglatze.de/masterfile/");
//webBrowser1.Navigate("http://wbk2.schulterglatze.de/masterfile");
}
}
}
I am unsure how to debug to find the correct way.
Can anyone tell me how to approach the problem?
Where do I need to debug to get the hint to the problem?
Thanks and greets
Daniel

Related

How to create Redirect URI OAuth2 in C# Console App with Dropbox API?

I've tried to create a Redirect URI, but seems that it is wrong. Actually, it's my first time trying to work with Dropbox API using .Net and I don't know many things.
As I said, I'm using Console Application in Visual Studio 2017. I wrote the code down below.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(Properties.Settings.Default.AccessToken))
{
this.GetAccessToken();
}
else
{
this.GetFiles();
}
}
private void GetAccessToken()
{
var login = new DropboxLogin("wbjcj6pa94berli", appKey, "https://www.dropbox.com/developers/apps/info/wbjcj6pa94berli", false, false);
login.Owner = this;
login.ShowDialog();
if (login.IsSuccessfully)
{
Properties.Settings.Default.AccessToken = login.AccessToken.Value;
Properties.Settings.Default.Save();
}
else
{
MessageBox.Show("Error...");
}
}
private void GetFiles()
{
}
}
I've created this Redirect URI in My App on Dropbox's site for Developers.
Redirect URI on Dropbox's WebPage:
[![enter image description here][1]][1]
I'm getting that MessageBox with "Error..." because, obviously, something is wrong.
Could any of you guys help me with this? Thanks a lot.

c# Using a Proxy in WebBrowser with login and password

I use Gecko browser (from Mozilla).
using System;
using System.Windows.Forms;
using Skybound.Gecko;
namespace shit_browser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Xpcom.Initialize(#"C:\XPCOM");
}
private void button1_Click(object sender, EventArgs e)
{
geckoWebBrowser1.Navigate("http://google.ru", 0, "", null, "");
}
}
}
You need to use a proxy. Log in via login, password and ip. How can this be realized?
You can use Selenium - Web Browser Automation.
ChromeDriver _driver;
WebDriverWait _wait;
_driver.Navigate().GoToUrl("......./homepage.htm");
_driver.Navigate().GoToUrl("...../index.htm");
_driver.Navigate().GoToUrl("....../login.jsp");
_wait.Until(ExpectedConditions.ElementExists(By.Id("kullaniciAdi")));
var userNameField = _driver.FindElementById("username");
var userPasswordField = _driver.FindElementById("password");
var loginButton =
_driver.FindElementByXPath("//input[#value='Login']");
userNameField.SendKeys("USERNAME");
userPasswordField.SendKeys("PASSWORD");
loginButton.Click();
Hmm sorry, i found like this maybe it'll work, didnt try.
public static void main(String[] args) {
// Create proxy class object
Proxy p=new Proxy();
// Set HTTP Port to 7777
p.setHttpProxy("localhost:7777");
// Create desired Capability object
DesiredCapabilities cap=new DesiredCapabilities();
// Pass proxy object p
cap.setCapability(CapabilityType.PROXY, p);
// Open firefox browser
WebDriver driver=new FirefoxDriver(cap);
// from here onwards code will be same as normal script
}
}

Launch winform with webrowser url from separate application

essentially what I want to do is I have one .exe .net program I made with a button in it. I want the click event in that button to launch my second .exe file, and change the WebBrowser URL in that second application. Is this possible?
The urls will be html pages on my computer.
So you need to share some data between 2 programs, one way to do it:
private void btnLaunchBrowser_Click(object sender, EventArgs e)
{
string yourExePath = "WhateverIsThePath.exe";
string url = "YourLocalUrlHere";
var browserWinformsApp = System.Diagnostics.Process.Start(yourExePath, url);
// Here you can control over the second Process, you can even
// Force it to Close by browserWinformsApp.Close();
}
In your Second App (Browser one), update Program.cs to accept parameters:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string passedUrl = args[0];
Application.Run(new Form1(passedUrl));
}
}
Finally, update your Form's constructor to accept a string url:
private string browserUrl;
public Form1(string url)
{
InitializeComponent();
browserUrl= url;
}

How to set a periodic task through my application?

I would like to implement a periodic file posting function to my application. For example, it uploads a certain text file in every 5 mins. So I am thinking some sort of manager that can handle time. I understand how to use Timer() method in c#, So how do I keep track on my timer through my application running? What will be the appropriate approach for such process?
Welcome to StackOverflow :D
I am assuming that you're using Windows Forms.
Here's an example on how to achieve this :
A periodic uploader for which you can set the interval, the upload handler and manage it (start/stop)
The upload handler will be a method on your side where you do the upload, this is great in the sense that this class does not need to know about it, it just calls it. In other terms separation of concerns.
internal class MyPeriodicUploader
{
private readonly Timer _timer;
private Action<string, string> _uploadHandler;
public MyPeriodicUploader(int miliseconds = 50000)
{
if (miliseconds <= 0) throw new ArgumentOutOfRangeException("miliseconds");
_timer = new Timer {Interval = miliseconds};
_timer.Tick += timer_Tick;
}
public string InputFile { get; set; }
public string TargetUrl { get; set; }
private void timer_Tick(object sender, EventArgs e)
{
if (_uploadHandler != null && InputFile != null && TargetUrl != null)
{
_uploadHandler(InputFile, TargetUrl);
}
}
public void SetUploadHandler(Action<string, string> uploadHandler)
{
if (uploadHandler == null) throw new ArgumentNullException("uploadHandler");
_uploadHandler = uploadHandler;
}
public void StartTimer()
{
_timer.Start();
}
public void StopTimer()
{
_timer.Stop();
}
public void SetUploadInterval(int minutes)
{
_timer.Interval = TimeSpan.FromMinutes(minutes).Milliseconds;
}
}
Now you want it available for your whole application, open Program.cs and create a property of it there :
internal static class Program
{
private static readonly MyPeriodicUploader _myPeriodicUploader = new MyPeriodicUploader();
public static MyPeriodicUploader MyPeriodicUploader
{
get { return _myPeriodicUploader; }
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
Then on your form use it like this :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Program.MyPeriodicUploader.SetUploadHandler(UploadHandler);
Program.MyPeriodicUploader.InputFile = "yourFileToUpload.txt";
Program.MyPeriodicUploader.TargetUrl = "http://youraddress.com";
Program.MyPeriodicUploader.StartTimer();
}
private void UploadHandler(string fileName, string targetUrl)
{
if (fileName == null) throw new ArgumentNullException("fileName");
// Upload your file
using (var webClient = new WebClient())
{
webClient.UploadFileAsync(new Uri(targetUrl), fileName);
}
}
}
UploadHandler is a callback if you're not familiar with the term I guess you'll quickly find it useful because you define the uploading, you won't depend of the implementation that MyPeriodicUploader would provide if it was the case; sometimes it would not fit your needs so defining it yourself is really useful.
I've put a really simple uploader in UploadHandler() as an example.
Note, I have used Action<string,string>, the first parameter is the file name, the second the target URL. The class will fail gracefully, if none of the file name and target url are defined, the operation will simply not happen.
Mark the answer if you like it, if there's something else update your question with more details so I can help.

C# can't see text when updating text box

I was wondering if someone could help me with a little issue I'm having. I'm trying to update a textbox from another class but the text is not showing up on in the textbox even though it is being sent as I have printed it to the screen.
The code I'm using is below:
Program.cs
namespace Search
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
try
{
Application.SetCompatibleTextRenderingDefault(false);
}
catch (InvalidOperationException e)
{
}
Application.Run(new Form1());
}
public static readonly Form1 MainLogWindow = new Form1();
}
}
HexToASCII:
public class HexToASCII
{
Output o = new Output();
public void hexToAscii(String hex, int textBox)
{
//Convert the string of HEX to ASCII
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hex.Length; i += 2)
{
string hs = hex.Substring(i, 2);
sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
}
//Pass the string to be output
string convertedHex = sb.ToString();
Program.MainLogWindow.UpdateTextBox(convertedHex);
}
}
Form1:
private delegate void NameCallBack(string varText);
public void UpdateTextBox(string input)
{
if (InvokeRequired)
{
textBox2.BeginInvoke(new NameCallBack(UpdateTextBox), new object[] { input });
}
else
{
textBox2.Text = textBox2.Text + Environment.NewLine + input;
}
}
I have tried to run it using a new thread ThreadStart ts = delegate()... but I'm unable to get the textbox to update. Sorry I'm very new to c#, could someone please explain the issue so I can understand it and learn for next time. Many thanks :)
This is the problem:
static void Main()
{
...
Application.Run(new Form1());
}
public static readonly Form1 MainLogWindow = new Form1();
You're creating two forms: one of them is being shown (with Application.Run) but you're changing the contents of the text box on the other one:
Program.MainLogWindow.UpdateTextBox(convertedHex);
You haven't shown how you're calling hexToAscii in the first place - personally I would try to avoid having static references to GUI elements like this, but you could get your code to work just by changing your Main method to use:
Application.Run(MainLogWindow);

Categories