YoutubeSearch Nuget in a bgworker and progressbar not working - c#

Here is a question very close to mine (I think): Running a method in BackGroundWorker and Showing ProgressBar
Here is my code, it's not freezing my Main form anymore but the function doesn't do its job.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using YoutubeSearch;
namespace searchyoutubeTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myBGWorker.WorkerReportsProgress = true;
}
void myBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
myProgressBar.Value = e.ProgressPercentage;
}
void myBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnSearch.Enabled = true;
MessageBox.Show("Done");
}
private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
VideoSearch items = new VideoSearch();
List<Video> list = new List<Video>();
foreach (var item in items.SearchQuery(txtSearch.Text, 1))
{
Video video = new Video();
video.Title = item.Title;
video.Author = item.Author;
video.Url = item.Url;
byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
video.Thumbnail = Image.FromStream(ms);
}
list.Add(video);
}
e.Result = list;
}
private void btnSearch_Click(object sender, EventArgs e)
{
btnSearch.Enabled = false;
myBGWorker.RunWorkerAsync();
//VideoSearch items = new VideoSearch();
//List<Video> list = new List<Video>();
//foreach (var item in items.SearchQuery(txtSearch.Text, 1))
//{
// Video video = new Video();
// video.Title = item.Title;
// video.Author = item.Author;
// video.Url = item.Url;
// byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
// using (MemoryStream ms = new MemoryStream(imageBytes))
// {
// video.Thumbnail = Image.FromStream(ms);
// }
// list.Add(video);
//}
//videoBindingSource.DataSource = list;
}
private void txtSearch_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnSearch_Click(this, new EventArgs());
}
}
}
}
But if I do only the function, it works:
//VideoSearch items = new VideoSearch();
//List<Video> list = new List<Video>();
//foreach (var item in items.SearchQuery(txtSearch.Text, 1))
//{
// Video video = new Video();
// video.Title = item.Title;
// video.Author = item.Author;
// video.Url = item.Url;
// byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
// using (MemoryStream ms = new MemoryStream(imageBytes))
// {
// video.Thumbnail = Image.FromStream(ms);
// }
// list.Add(video);
//}
//videoBindingSource.DataSource = list;
Any idea what I am doing wrong?

I assume you correctly added the events for the button and onload of the form.
You didnt attach the events for the BackgroundWorker. When you click on the searchbutton, the workers starts and the DoWork method is invoked on a seperate thread.
public Form1()
{
InitializeComponent();
myBGWorker.WorkerReportsProgress = true;
myBGWorker.DoWork += myBGWorker_DoWork;
myBGWorker.ProgressChanged += myBGWorker_ProgressChanged;
myBGWorker.RunWorkerCompleted += myBGWorker_RunWorkerCompleted;
}

Related

How to display the route using GMap in C#?

My main problem is that it doesn't display the line between the 2 markers when I click on the display button.It should draw my route between the first pin and the second pin, but it doesn't show me anything at all. I've been trying for some time to figure out what's wrong.
This is the code. I also uploaded images, maybe it will help.
Can anyone help me with this? Thanks!
code
interface
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GMap.NET.MapProviders;
using GMap.NET;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
namespace Licenta
{
public partial class Map : Form
{
List<PointLatLng> _points;
public Map()
{
InitializeComponent();
_points = new List<PointLatLng>();
}
private void Map_Load(object sender, EventArgs e)
{
GMapProviders.GoogleMap.ApiKey = "#AIzaSyBreQ8N4txQ74BwKwigtnmkSW8Vhisyles";
gMapControl1.ShowCenter = false;
}
private void btnAdauga_Click(object sender, EventArgs e)
{
_points.Add(new PointLatLng(Convert.ToDouble(txtLat.Text), Convert.ToDouble(txtLong.Text)));
}
private void btnSterge_Click(object sender, EventArgs e)
{
if (gMapControl1.Overlays.Count > 0)
{
gMapControl1.Overlays.RemoveAt(0);
gMapControl1.Refresh();
}
}
private void btnAfiseaza_Click(object sender, EventArgs e)
{
var route = GoogleMapProvider.Instance.GetRoute(_points[0], _points[1], false, false, 14);
var r = new GMapRoute(route.Points, "My Route")
{
Stroke = new Pen(Color.Red, 5)
};
var routes = new GMapOverlay("routes");
routes.Routes.Add(r);
gMapControl1.Overlays.Add(routes);
lblDist.Text = route.Distance + " km";
}
GMapOverlay markers = new GMapOverlay("markers");
private void btnIncarca_Click(object sender, EventArgs e)
{
gMapControl1.DragButton = MouseButtons.Left;
gMapControl1.MapProvider = GMapProviders.GoogleMap;
double lat = Convert.ToDouble(txtLat.Text);
double longt = Convert.ToDouble(txtLong.Text);
gMapControl1.Position = new PointLatLng(lat, longt);
gMapControl1.MinZoom = 2;
gMapControl1.MaxZoom = 100;
gMapControl1.Zoom = 7;
PointLatLng point = new PointLatLng(lat, longt);
GMapMarker marker = new GMarkerGoogle(point, GMarkerGoogleType.red_pushpin);
markers.Markers.Add(marker);
gMapControl1.Overlays.Add(markers);
}
private void gMapControl1_Load(object sender, EventArgs e)
{
gMapControl1.SetPositionByKeywords("Timisoara, Romania");
}
private void button5_Click(object sender, EventArgs e)
{
_points.Clear();
}
}
}

How to take file from button

I made a application with iTextSharp to put numbers on a PDF file.
As you will see in the following code, my application just can do this, only if the file is in a specific directory.
So I made an "Other" button where the user can select a file.
What I want to do now is, that the chosen file will download the converted PDF.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace NummerierePDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] bytes = File.ReadAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF.pdf");
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF1.pdf", bytes);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
}
}
}
}
So File.WriteAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF1.pdf", bytes);
can stay because it doesn't matter where the file will be downloaded after it's converted.
But File.ReadAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF.pdf");
shouldn't be a specific directory, it should get the chosen file from button3.
As you probably noticed I'm new into programming so I thought maybe I could do this: File.ReadAllBytes(fileToOpen);
to get the string. Though that doesn't do his job.
Thanks for your time.
If you want to use a variable between methods of the same class then you need to declare a private and non-static class level variable (called also Instance Field). This is visible to every method of the class.
public partial class Form1 : Form
{
// Here declare a variable visible to all methods inside the class but
// not outside the class. Init it with an empty string
private string theFile = "";
private void button1_Click(object sender, EventArgs e)
{
// When you click the button1 check if the variable
// has been set to something in the button3 click event handler
if(string.IsNullOrEmpty(theFile) || !File.Exists(theFile))
return;
// Now you can use it to load the file and continue with the code
// you have already written
byte[] bytes = File.ReadAllBytes(theFile);
......
......
}
private void button3_Click(object sender, EventArgs e)
{
// The only job of button3 is to select the file to work on
// as you can see we can use the variable also here
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
theFile = FD.FileName;
}
}
But do you really need a separate button for this? I mean you could put the three lines of code in the button3 directly in at the start of the code in button1 and remove the superfluos (at this point) button3
I suggest you to read some docs on variable's Scope and Lifetime
Try this
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace NummerierePDF
{
public partial class Form1 : Form
{
string fileToOpen = string.Empty;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrWhiteSpace(fileToOpen)) return;
byte[] bytes = File.ReadAllBytes(fileToOpen);
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF1.pdf", bytes);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
}
}
}
}
I have put your variable to class scope and now you can access it from anywhere inside your class

simple image uploader

I wrote a simple image uploader in C#. Here's my code:
using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace Snappx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GlobalHook.HookManager.KeyUp += new KeyEventHandler(MyKeyUp);
CheckForIllegalCrossThreadCalls = false;
new Task(this.Hide).Start();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(-1);
}
string ORIGINIM;
async void MyKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.PrintScreen)
{
await GetImage();
e.Handled = true;
}
else e.Handled = false;
}
String img = #"temp";
async Task GetImage()
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save(img, ImageFormat.Png);
}
using (var w = new WebClient())
{
var values = new NameValueCollection { { "key", "85684005b7d4faa4c33ee480010d4982" }, { "image", Convert.ToBase64String(File.ReadAllBytes(img)) } };
notifyIcon1.ShowBalloonTip(3, "Uploading", "Uploading image to Imgur", ToolTipIcon.Info);
w.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
Task<byte[]> x = w.UploadValuesTaskAsync(new Uri("http://imgur.com/api/upload.xml"), values);
byte[] response = await x;
while (w.IsBusy) System.Threading.Thread.Sleep(500);
File.Delete(img);
ORIGINIM = Convert.ToString(XDocument.Load(new MemoryStream(response)));
ORIGINIM = ORIGINIM.Substring(ORIGINIM.LastIndexOf("<original_image>")).Replace("<original_image>", "");
ORIGINIM = ORIGINIM.Substring(0, ORIGINIM.LastIndexOf("</original_image>")).Replace("</original_image>", "");
Clipboard.SetText(ORIGINIM);
if (!File.Exists(#"Uploads.txt")) File.Create(#"Uploads.txt");
new StreamWriter(#"Uploads.txt").WriteLine(ORIGINIM);
notifyIcon1.ShowBalloonTip(3, "Done", "URL copied to clipboard.", ToolTipIcon.Info);
}
}
private void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
int percentage = e.ProgressPercentage * 2;
notifyIcon1.ShowBalloonTip(3, "Uploading", (percentage).ToString() + "%", ToolTipIcon.Info);
}
}
}
First of all, when there is no Uploads.txt file, it returns an Exception handler. Then second time I run it, it creates it. Is there any simpler way to store it?
Second question:
Am I able to add two different options, one for capture full screen and one for select screen region.
How could I integrate it with my code? Could you post it?
Instead of (!File.Exists(#"Uploads.txt")) File.Create(#"Uploads.txt") try this
using (StreamWriter sw = new StreamWriter(File.Open(#"Uploads.txt", FileMode.OpenOrCreate)))
{
sw.WriteLine(ORIGINIM);
}
The reason why it worked on the second try is because you didn't create a lock on the file with File.Create - the existing logic opens the file, which creates a FileStream, then you attempt to open StreamWriter on the same file. You should instead create the StreamWriter by passing the FileStream into its constructor, as shown in the above example.

C# Antivirus-Program using MD5 - BackgroundWorker/FileNotFoundException - Incorrect Path?

I'm trying to create an antivirus program that takes a group of 5 MD 5 hashes from a text file and after the user select a folder using browse and clicks scan the program should iterate through all the files run the hash for each one in a background worker and compare, if the result is a virus detected, the result is then fed to a list box.
Currently the code is catching (FileNotFoundException) and the msgbox displaying FilePath is producing "Path1" "Path2" "Path3", could anyone explain how i can correct the code so that the paths are being correctly fed? I don't really understand where the "Path1" "Path2" "Path3" ect is coming from?
Code Below :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace TestAntivirus
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int noofvirus = 0;
List<string> completehashes = new List<string>();
private void Browse_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
label1.Text = folderBrowserDialog1.SelectedPath;
noofvirus = 0;
label2.Text = "Viruses:" + noofvirus.ToString();
progressBar1.Value = 0;
listBox1.Items.Clear();
}
private void BDone_Click(object sender, EventArgs e)
{
this.Close();
}
private void BScan_Click(object sender, EventArgs e)
{
string[] scanned = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
int numofscanned = scanned.Count();
progressBar1.Maximum = scanned.Length;
foreach (string item in scanned)
{
for (int i = 0; i < (numofscanned); i++)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler (backgroundWorker1_DoWork);
worker.RunWorkerAsync(i);
}
}
foreach (string hashes in completehashes)
{
try
{
StreamReader stream = new StreamReader(hashes);
string read = stream.ReadToEnd();
var lineCount = File.ReadLines(#"C:\Users\Neil Bagley\Desktop\ProjectWork\VirusHashes\Test5.txt").Count();
var virus = File.ReadAllLines(#"C:\Users\Neil Bagley\Desktop\ProjectWork\VirusHashes\Test5.txt");
foreach (string st in virus)
{
if (Regex.IsMatch(read, st))
{
MessageBox.Show("Virus Detected");
noofvirus += 1;
label2.Text = "Viruses: " + noofvirus.ToString();
listBox1.Items.Add(hashes);
}
progressBar1.Increment(1);
}
}
catch
{
string read = hashes;
var virus = File.ReadAllLines(#"C:\Users\Neil Bagley\Desktop\ProjectWork\VirusHashes\Test5.txt");
foreach (string st in virus)
{
if (Regex.IsMatch(read, st))
{
MessageBox.Show("Virus Detected");
noofvirus += 1;
label2.Text = "Viruses:" + noofvirus.ToString();
listBox1.Items.Add(hashes);
}
}
}
}
}
private static String MakeHashString(byte[] hashbytes)
{
StringBuilder hash = new StringBuilder(32);
foreach (byte b in hashbytes)
{
hash.Append(b.ToString("X2").ToLower());
}
return hash.ToString();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string filePath = e.Argument.ToString();
byte[] buffer;
int bytesRead;
long size;
long totalBytesRead = 0;
try
{
using (Stream file = File.OpenRead(filePath))
{
size = file.Length;
using (HashAlgorithm hasher = MD5.Create())
{
do
{
buffer = new byte[4096];
bytesRead = file.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
hasher.TransformBlock(buffer, 0, bytesRead, null, 0);
backgroundWorker1.ReportProgress((int)((double)totalBytesRead / size * 100));
} while (bytesRead != 0);
hasher.TransformFinalBlock(buffer, 0, 0);
e.Result = MakeHashString(hasher.Hash);
}
}
}
catch (FileNotFoundException)
{
MessageBox.Show("File not found in the specified path" + filePath);
}
catch (IOException)
{
MessageBox.Show("IOException");
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
completehashes.Add(e.Result.ToString());
progressBar1.Value = 0;
}
}
}
After the advice previously given i have tried to start remaking the project, but im now unsure why this only adds one hash to the listbox rather all as i expected with "foreach (string scan in scanned)" can anyone explain?
New Attempt:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace AntiVirus
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int noofvirus = 0;
private string[] scanned;
private void BBrowse_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
label1.Text = folderBrowserDialog1.SelectedPath;
noofvirus = 0;
label2.Text = "Viruses:" + noofvirus.ToString();
progressBar1.Value = 0;
listBox1.Items.Clear();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
scanned = Directory.GetFiles(e.Argument.ToString(), "*.*", SearchOption.AllDirectories);
foreach (string scan in scanned)
{
byte[] buffer;
int bytesRead;
long size;
long totalBytesRead = 0;
using (Stream file = File.OpenRead(scan))
{
size = file.Length;
using (HashAlgorithm hasher = MD5.Create())
{
do
{
buffer = new byte[4096];
bytesRead = file.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
hasher.TransformBlock(buffer, 0, bytesRead, null, 0);
backgroundWorker1.ReportProgress((int)((double)totalBytesRead / size * 100));
} while (bytesRead != 0);
hasher.TransformFinalBlock(buffer, 0, 0);
e.Result = MakeHashString(hasher.Hash);
}
}
}
}
private static String MakeHashString(byte[] hashbytes)
{
StringBuilder hash = new StringBuilder(32);
foreach (byte b in hashbytes)
{
hash.Append(b.ToString("X2").ToLower());
}
return hash.ToString();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
listBox1.Items.Add(e.Result.ToString());
progressBar1.Value = 0;
}
private void BScan_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(folderBrowserDialog1.SelectedPath);
}
private void BDone_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
You set e.Result for each hash, but only when the RunWorkerCompleted event is fired does it get added to the listbox.
(that event only fires once when the DoWork Event has completed, so only the last hash gets added)
I would recommand using backgroundWorker1.ReportProgress 2nd parameter userState when you've got the file hash like so:
(note, code is untested/psuedocode but it hopefully gets you on the right track)
//CalculateTotalProgress() is a fictional function returning total progress percentage
backgroundWorker1.ReportProgress(CalculateTotalProgress(currentFile,totalFiles), MakeHashString(hasher.Hash));
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
listBox1.Items.Add(e.UserState.ToString);
progressBar1.Value = e.ProgressPercentage;
}

XMLParseException occurs

The invocation of the constructor on type 'WpfApplication1.MainWindow'
that matches the specified binding constraints threw an exception.'
Line number '4' and line position '9'.
That was the error I'm facing while changing my target platform from 'x86' to 'Any CPU' in order to run my executable to run in x86 and x64 bit windows operating systems.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WebKit;
using WebKit.Interop;
using Twitterizer;
using Facebook;
using TwitterConnect;
using facebook;
namespace WpfApplication3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
WebKitBrowser wb = new WebKitBrowser();
TwitterConnect.TwitterStuff ts = new TwitterStuff();
Browser b = new Browser();
OpenWebkitBrowser.facebook fb_1 = new OpenWebkitBrowser.facebook();
private void Possibillion_Loaded(object sender, RoutedEventArgs e)
{
System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();
host.Child = wb;
this.Grid2.Children.Add(host);
wb.DocumentCompleted += wb_DocumentCompleted;
}
void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
textBox1.Text = wb.Url.ToString();
TabItem1.Header = wb.DocumentTitle;
}
private void btnMinimize_Click(object sender, RoutedEventArgs e)
{
Possibillion.WindowState = WindowState.Minimized;
}
private void btnMaximize_Click(object sender, RoutedEventArgs e)
{
if (Possibillion.WindowState == WindowState.Maximized)
Possibillion.WindowState = WindowState.Normal;
else
Possibillion.WindowState = WindowState.Maximized;
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
Possibillion.Close();
}
private void btnGo_Click(object sender, RoutedEventArgs e)
{
wb.Navigate("http://" + textBox1.Text);
}
private void btnTwitter_Click(object sender, RoutedEventArgs e)
{
bool loggedIn = b.AlreadyLoggedIn();
if (!loggedIn)
{
//this.Hide();
b.Show();
}
//else
//{
// MainWindow mw = new MainWindow();
// mw.Show();
// this.Close();
//}
else if (textBox1.Text != "")
{
ts.tweetIt(wb.DocumentTitle);
//textBox1.Clear();
}
}
private void btnfacebook_Click_1(object sender, RoutedEventArgs e)
{
if (val.login == true)
{
//fb_1.Show();
if (string.IsNullOrEmpty(textBox1.Text))
{
Dispatcher.Invoke(new Action(() => { System.Windows.MessageBox.Show("Enter message."); }));
return;
}
var fb = new FacebookClient(val.token);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
Dispatcher.Invoke(new Action(() => { System.Windows.MessageBox.Show(args.Error.Message); }));
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
//_lastMessageId = (string)result["id"];
Dispatcher.Invoke(new Action(() =>
{
System.Windows.MessageBox.Show("Message Posted successfully");
textBox1.Text = string.Empty;
// pho.IsEnabled = true;
}));
};
var fbimg = new Facebook.FacebookMediaObject
{
FileName = Guid.NewGuid() + ".jpg",
ContentType = "image/png"
};
// FileStream fs = new FileStream("Rose.png", FileMode.Open, FileAccess.Read);
// BinaryReader br = new BinaryReader(fs);
// byte[] res = br.ReadBytes((int)fs.Length);
// br.Close();
// fs.Close();
//fbimg.SetValue(res);
// Uri uri = new Uri("/Background.png",UriKind.Relative);
var parameters = new Dictionary<string, object>();
//parameters.Add("picture", fbimg);
//parameters.Add("message", "hi");
// parameters["picture"] ="https://twimg0-a.akamaihd.net/profile_images/2263781693/SAchin_reasonably_small.png";
parameters["message"] = textBox1.Text;
// parameters["picture"] =fbimg;
//fb.PostAsync(#"/photos", parameters);
fb.PostAsync("me/feed", parameters);
}
else
{
Dispatcher.Invoke(new Action(() => { fb_1.ShowDialog(); }));
//System.Windows.MessageBox.Show("message not sent");
}
}
private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
wb.Navigate("http://" + textBox1.Text);
}
}
}
Make sure your target platform matches your build settings.
If you have changed your configuration manager to any CPU, then in the project properties under build you will need to do the same.
Edit - Ah seems like your trying to run a toolkit that is build for x86 in a x64 world.

Categories