The problem is: When I remove the first message box line, my program doesn't run and throws "Exception has been thrown by the target of an invocation" on the if statement line. However, when I leave the messagebox there, it runs fine. Can someone explain to me why this is happening and what I can do to fix it? I'm fairly new to WPF by the way, any help would be appreciated.
public BrowserMode() {
InitializeComponent();
MessageBox.Show("Entering Browser Mode");
if (webBrowser1.Source.Scheme == "http")
{
//cancel navigation
//this.NavigationService.Navigating += new NavigatingCancelEventHandler(Cancel_Navigation);
qd = new QuestionData();
// code where stuff happens
var url = webBrowser1.Source;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// from h.RequestUri = "webcam://submit?question_id=45"
var parseUrl = request.RequestUri; //the uri that responded to the request.
MessageBox.Show("The requested URI is: " + parseUrl);
This sort of work is not suited for a constructor and should be moved out until after the WebBrowser is fully loaded. You have two options:
Hook Control.Loaded and perform this behavior there.
public BrowserMode()
{
InitializeComponent();
this.Loaded += BroswerMode_Loaded;
}
void BrowserMode_Loaded(object sender, EventArgs e)
{
if (webBrowser1.Source != null
&& webBrowser1.Source.Scheme == "http")
{
qd = new QuestionData();
// ...
}
}
Hook WebBrowser.Navigating and perform this behavior there.
public BrowserMode()
{
InitializeComponent();
this.webBrowser1.Navigating += WebBrowser_Navigating;
}
void WebBrowser_Navigating(object sender, NavigatingCancelEventArgs e)
{
if (e.Uri.Scheme == "http")
{
qd = new QuestionData();
// ...
}
}
Related
As the title says I need help writing a program that will connect to PVI and another program(I am not sure if it is possible to establish communication with a program like this that was written by the original machine manufacturer I will provide as much detail as i can if needed on this.) this will then exchange information from the PLC to the program running and allow freezing the frame of this program and taking screenshots of it as well as unfreezing it after.
I will include the code that i have so far which I wrote using a training manual provided from B&R this is just to establish connection to PVI and the automation studio program running on a PLC.
This is an outdated training manual but is the only source of information I have available for this problem. The program i wrote does compile and run it does seem to make something of a connection to a PLC that I have connected to my laptop as well as when running the simulation program without a PLC. However it does not read data from the program as the training manual explains it would read the values of some variables i have made in automation studio.
Also when attempting to click on any of the buttons i made and i will be honest i am not 100% sure what they are even supposed to do it will give me an error (System.NullReferenceException: 'Object reference not set to an instance of an object.' myStructPV was null.).
Which i assume is trying to tell me that the variable that is being used when the button is pushed is null however these variables are part of the PVI services namespace and i am not sure what value you would give them in initialization.
I do apologize if this does not make much sense as i mentioned i am quite new at developing and have not used Visual studio or C# since college way back.
Any advice or help will be appreciated very much thank you.
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 BR.AN.PviServices;
namespace PVITestApp
{
public partial class Form1 : Form
{
public Service myService;
public Cpu myCpu;
public BR.AN.PviServices.Task myTask;
public Variable myVariable;
public Module myModule;
public Variable myVariablePV1;
public Variable myStructPV;
public Form1()
{
InitializeComponent();
// txtStatus.Text = "text box is functioning!";
}
private void MyStructPV_Error(object sender, PviEventArgs e)
{
throw new NotImplementedException();
}
private void MyStructPV_ValueChanged(object sender, VariableEventArgs e)
{
throw new NotImplementedException();
}
private void Form1_Load(object sender, EventArgs e)
{
myService = new Service("service");
myService.Connected += MyService_Connected;
myService.IsStatic = true;
myService.Connect();
}
private void MyService_Connected(object sender, PviEventArgs e)
{
this.txtStatus.Text += "Service Connected\r\n";
if (myCpu == null)
{
myCpu = new Cpu(myService, "cpu");
//myCpu.Connection.DeviceType = BR.AN.PviServices.DeviceType.TcpIp;
myCpu.Connection.DeviceType = DeviceType.TcpIp;
myCpu.Connection.TcpIp.DestinationStation = 2;
myCpu.Connection.TcpIp.DestinationPort = 11160;
myCpu.Connection.TcpIp.DestinationIpAddress = "192.168.0.1";
//myCpu.Connection.TcpIp.DestinationIpAddress = "127.0.0.1";
myCpu.Connected += MyCpu_Connected;
myCpu.Error += MyCpu_Error;
myCpu.Connect(ConnectionType.CreateAndLink);
// maybe need to use this one - myCpu.Connect(ConnectionType.Create);
}
// throw new NotImplementedException();
}
private void MyCpu_Error(object sender, PviEventArgs e)
{
this.txtStatus.Text += e.Name + " Error:" + e.ErrorCode + "\r\n";
// throw new NotImplementedException(txtStatus.Text = "Error connecting.");
}
private void MyCpu_Connected(object sender, PviEventArgs e)
{
this.txtStatus.Text += "CPU Connected\r\n";
myTask = new BR.AN.PviServices.Task(myCpu, "pvitest");
myTask.Connected += MyTask_Connected;
myTask.Error += MyTask_Error;
myTask.Connect();
//throw new NotImplementedException();
}
private void MyTask_Error(object sender, PviEventArgs e)
{
this.txtStatus.Text += e.Name + " Error:" + e.ErrorCode + "\r\n";
//throw new NotImplementedException();
}
private void MyTask_Connected(object sender, PviEventArgs e)
{
this.txtStatus.Text += "Task " + e.Name + " Connected\r\n";
if (myVariable == null)
{
myVariable = new Variable(myTask, "Lifesign");
myVariable.Active = true;
myVariable.RefreshTime = 200;
myVariable.ValueChanged += MyVariable_ValueChanged;
myVariable.Error += MyVariable_Error;
myVariable.Connect();
}
if (myVariablePV1 == null)
{
myVariablePV1 = new Variable(myTask, "VarCreateOnly");
myVariablePV1.Address = "PV1";
myVariablePV1.Connect(ConnectionType.Create);
}
// throw new NotImplementedException();
}
private void MyVariable_Error(object sender, PviEventArgs e)
{
txtStatus.Text += e.Name + " E#" + e.ErrorCode.ToString();
//throw new NotImplementedException();
}
private void MyVariable_ValueChanged(object sender, VariableEventArgs e)
{
if (myStructPV == null) //PG35 stuff may need to move
{
myStructPV = new Variable(myTask, "Pv_Struct");
myStructPV.Active = true;
myStructPV.RefreshTime = 1000;
myStructPV.ValueChanged += MyStructPV_ValueChanged;
myStructPV.Error += MyStructPV_Error;
myStructPV.Connect();
}
// /\ above may need to be moved back.
if (e.Name == "Lifesign")
{
lblValLifesign.Text = ((Variable)sender).Value.ToString();
}
if (e.Name == "linkVarPV1")
{
lblPV1.Text = ((Variable)sender).Value.ToString();
}
Variable tmpVar = (Variable)sender; //PG 36 - 37
if(e.Name == "Pv_Struct")
{
if (tmpVar.Value.DataType == DataType.Structure)
{
foreach (Variable member in tmpVar.Members.Values)
{
txtStatus.Text += member.Value.ToString() + "\r\n";
}
}
}
foreach (String membername in e.ChangedMembers)
{
if (membername != null)
{
txtStatus.Text += tmpVar.Value[membername].ToString() + "\r\n";
}
}
//throw new NotImplementedException();
}
private void CmdConnectPV1_Click(object sender, EventArgs e)
{
Variable myLinkPV1 = new Variable(myVariable, "linkVarPV1");
myLinkPV1.LinkName = myVariablePV1.FullName;
myLinkPV1.Active = true;
myLinkPV1.ValueChanged += MyLinkPV1_ValueChanged;
myLinkPV1.Error += MyLinkPV1_Error;
myLinkPV1.Connect(ConnectionType.Link);
}
private void MyLinkPV1_Error(object sender, PviEventArgs e)
{
//throw new NotImplementedException();
}
private void MyLinkPV1_ValueChanged(object sender, VariableEventArgs e)
{
// throw new NotImplementedException();
}
private void CmdReadVar_Click(object sender, EventArgs e)
{
myVariable.ValueRead += MyVariable_ValueRead;
myVariable.ReadValue();
}
private void MyVariable_ValueRead(object sender, PviEventArgs e)
{
this.lblReadVar.Text = ((Variable)sender).Value.ToString();
//throw new NotImplementedException();
}
private void CmdReadTime_Click(object sender, EventArgs e)
{
myCpu.DateTimeRead += MyCpu_DateTimeRead;
myCpu.ReadDateTime();
}
private void MyCpu_DateTimeRead(object sender, CpuEventArgs e)
{
DateTime dt;
dt = e.DateTime;
this.Text = dt.ToString();
//throw new NotImplementedException();
}
private void CmdWriteVal_Click(object sender, EventArgs e)
{
myVariable.Value = 0;
myVariable.ValueWritten += MyVariable_ValueWritten;
}
private void MyVariable_ValueWritten(object sender, PviEventArgs e)
{
//throw new NotImplementedException();
}
private void CmdSetStruct_Click(object sender, EventArgs e)
{
myStructPV.WriteValueAutomatic = false;
myStructPV.Value["Member1"] = 10;
myStructPV.Value["Member2"] = 20;
myStructPV.Value["Member3"] = myVariable.Value;
myStructPV.WriteValue();
}
}
}
myStructPV is null because you're calling CmdSetStruct_Click() without having created myStructPV. You'd need MyVariable_ValueChanged() to run first or to at least put the code from it that creates myStructPV into CmdSetStruct_Click().
As long as you are getting to status "Task pvitest Connected" when running the init stuff, then all the PVI connection is working (if you don't have a task on you PLC named pvitest but still make it to CPU Connected then you're doing okay still). You just have to debug your connecting to actual tags.
As far as communicating with an existing Windows program written by the OEM, that's unlikely. You'd have to use some kind of debugger to get at its memory or hope they made some kind of API which is very unlikely.
I think Isaac is right to assume that you click on the button that executesCmdSetStruct_Click() before you actually initialize the myStruct Pv.
This could be because your connection to the PLC doesn't work up until to the point where you are able to get the valueChanged event from the Lifebit variable.
Could your Lifebit variable on the PLC be global? Would be nice to see the console output of the VS to be able to pinpoint the issue until it crashes.
Regarding running in the PVI trial mode you are right, it can create some problems for the initial connection but in that case, if you just stop the PVI manager and start it again, it should all be fine.
I'd anyway recommend you to have just one struct for handling the communication in an out of the PLC. For example:
gComm.ToPlc.Status.someVariable
gComm.FromPlc.Cmd.startDoingSth
With that, you would have to go through the PVI variable connection process twice only. Once to connect to the ToPlc struct and once to connect to the FromPlc struct. Your code will be a lot easier to manage that way.
And finally, you can use the onConnected events of the variables rather than the valueChanged. That way before you allow your app to move on, you can wait until you get a valid connection on the variables & catch the errors thrown from the variable connection and handle them gracefully. This would make it possible to prevent your app from crashing.
1: Can someone explain the last line of the first function to me?
2: The second function doesn't work. Please tell me why.The PHP script is fetching the data.
I edited the code to get this, but the app now crashes with a System nullreferenceexception.
Please help.
private void checkbutton_Click(object sender, RoutedEventArgs e)
{
statustext.Text = "Checking for new score";
var webclient = new WebClient();
webclient.OpenReadCompleted += new OpenReadCompletedEventHandler(getscores_OpenReadCompleted);
webclient.OpenReadAsync(new Uri("http://example.com/get.php?"+DateTime.Now));
}
void getscores_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
StreamReader s = null;
Stream reply=null;
try
{
reply = (Stream)e.Result;
s = new StreamReader(reply);
}
catch
{
statustext.Text = "ERROR IN FETCHING";
}
scorebox.Text = s.ReadToEnd();
statustext.Text = "DoNE";
}
The last line of the first method is attaching a handler to an event. It is saying that when the OpenReadCompleted event fires, that is to say when the read completes, the getscores_OpenReadCompleted method should be called.
The getscores_OpenReadCompleted doesn't work because it's trying to access a UI element from a non-UI thread.
You're also adding the handler after starting the asynchronous operation, so while it's unlikely, it's certainly possible that the operation completes very quickly and the event is fired before you add the handler. While this situation would be very unusual, it's fixed very quickly and easily by simply adding the handler before you start the asynchronous operation.
There are a couple of issues here:
Register the delegate before the call to OpenReadAsync
Read the stream from the event arguments and close the stream when you're done.
private void checkbutton_Click(object sender, RoutedEventArgs e)
{
statustext.Text = "Checking for new score";
var webclient = new WebClient();
webclient.OpenReadCompleted += new OpenReadCompletedEventHandler(getscores_OpenReadCompleted);
webclient.OpenReadAsync(new Uri("http://example.com/get.php?"+DateTime.Now));
}
void getscores_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
Stream reply = null;
StreamReader s = null;
string outputText = string.Empty;
try
{
reply = (Stream)e.Result;
s = new StreamReader(reply);
outputText = s.ReadToEnd();
}
finally
{
if (s != null)
{
s.Close();
}
if (reply != null)
{
reply.Close();
}
}
statustext.Text = outputText;
}
See the usage of the OpenReadAsync method here:
http://msdn.microsoft.com/en-us/library/system.net.openreadcompletedeventhandler(v=vs.110).aspx
and here
http://msdn.microsoft.com/en-us/library/ms144211(v=vs.110).aspx
I've got this code and I'm using it to show a button which allows the user to choose an image from his library and use it as a background for my app.
So I create a PhotoChooserTask, set it to show the camera and bind it to a method that has to be executed when the task is completed.
The button will start the task by showing the PhotoChooserTask.
The action to do on complete is quite easy, I've just got to set a boolean value and update an image source.
PhotoChooserTask pct_edit = new PhotoChooserTask();
pct_edit.ShowCamera = true;
pct_edit.Completed += pct_edit_Completed;
Button changeImageButton = new Button { Content = "Change Image" };
changeImageButton.Tap += (s, e) =>
{
pct_edit.Show();
};
void pct_edit_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
bi.SetSource(e.ChosenPhoto);
IsRebuildNeeded = true;
}
}
The problem is that it won't show the PhotoChooserTask but it will give me an exception, taking me to
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
in App.xaml.cs.
This looks weird as I've got another PhotoChooserTask in the same class and this one works fine.
What's wrong with it?
VisualStudio won't even tell me what's the exception and so there's no way to figure it out!
EDIT:
I just found out that the exception is thrown when I call
pct_edit.Show();
in the button's tap event.
You should be defining your chooser as a field in your class. It's a requirement that you have page scope for the PhotoChooser. You then subscribe to it in your constructor. This is stated on the MSDN here
class SomeClass
{
readonly PhotoChooserTask pct_edit = new PhotoChooserTask();
SomeClass()
{
pct_edit.ShowCamera = true;
pct_edit .Completed += new EventHandler<PhotoResult>(pct_edit_Completed);
}
}
You can use try to check what is the problem
changeImageButton.Tap += (s, e) =>
{
try
{
PhotoChooserTask pct_edit = new PhotoChooserTask();
pct_edit.ShowCamera = true;
pct_edit.Completed += (s,e) =>
{
if (e.TaskResult == TaskResult.OK)
{
var bi = new BitmapImage() // maybe you didn't initialize bi?
bi.SetSource(e.ChosenPhoto);
IsRebuildNeeded = true;
}
}
pct_edit.Show();
}
catch (Exception ex)
{
Message.Show(ex.Message);
}
};
Put brakepoint on Message, then you can check everything inside ex.
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void b1_Click(object sender, RoutedEventArgs e)
{
string url = trackingtb.Text;
LoadSiteContent("http://www.mywebsite.com");
}
public void LoadSiteContent(string url)
{
//create a new WebClient object
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback2);
client.DownloadStringAsync(new Uri(url));
}
private void DownloadStringCallback2(Object sender, DownloadStringCompletedEventArgs e)
{
// If the request was not canceled and did not throw
// an exception, display the resource.
if (!e.Cancelled && e.Error == null)
{
output.Text= (string)e.Result;
//If you get the cross-thread exception then use the following line instead of the above
//Dispatcher.BeginInvoke(new Action (() => textBlock1.Text = (string)e.Result));
}
}
I'm trying to download the html content of a website. For some reason this code is no working. I hope windows phone 7 and windows phone 8 uses the same stuff.
Thanks.
Your code works correctly for me. You are probably gettin an error. Why don't you check if you are receiving any errors?
private void DownloadStringCallback2(Object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
// Check the error here
}
// If the request was not canceled and did not throw
// an exception, display the resource.
else if (!e.Cancelled)
{
output.Text= (string)e.Result;
//If you get the cross-thread exception then use the following line instead of the above
//Dispatcher.BeginInvoke(new Action (() => textBlock1.Text = (string)e.Result));
}
}
I want to do web browser bot. It should click link and wait 25 seconds.
private void webBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) // This is only way It worked for me.
{
if (webBrowserMain.Url.AbsoluteUri == #"http://www.clix-cents.com/pages/clickads")
{
Regex regAddId = new Regex("onclick=\\'openad\\(\"([\\d\\w]+)\"\\);", RegexOptions.IgnoreCase); // Find link and click it.
if (regAddId.IsMatch(webBrowserMain.DocumentText))
{
string AddId = regAddId.Match(webBrowserMain.DocumentText).Groups[1].ToString();
webBrowserMain.Navigate(#"http://www.clix-cents.com/pages/clickads?h=" + AddId);
}
}
else if (webBrowserMain.Url.AbsoluteUri.Contains("http://www.clix-cents.com/pages/clickads?h=")) // up to there everything is ok. But problem starts here.
{
Thread.Sleep(25000); // It pouses whole thread and browser, so timer in browser is not counting down.
Regex regCaptchaCode = new Regex("src=\\'/pages/captcha\\?t=c&s=([\\d\\w\\W]+)\\'", RegexOptions.IgnoreCase);
if (regCaptchaCode.IsMatch(webBrowserMain.DocumentText))
{
pictureBox1.ImageLocation = #"http://www.clix-cents.com/pages/captcha?t=c&s=" + regCaptchaCode.Match(webBrowserMain.DocumentText).ToString();
}
}
}
How to write bot for something like that? I have no idea.
Don't reinvent the wheel - there's already solutions out there like WatiN which is mainly used for testing but is also suitable for automation.
Code example from the WatiN page:
[Test]
public void SearchForWatiNOnGoogle()
{
using (var browser = new IE("http://www.google.com"))
{
browser.TextField(Find.ByName("q")).TypeText("WatiN");
browser.Button(Find.ByName("btnG")).Click();
Assert.IsTrue(browser.ContainsText("WatiN"));
}
}
You could probably use a timer. Eg:
private Timer t = new Timer();
private string nextUrl = "";
private void buttonStart_Click(object sender, EventArgs e)
{
t.Interval = 2500;
t.Tick += new EventHandler(t_Tick);
}
void t_Tick(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(nextUrl))
webBrowser1.Navigate(nextUrl);
else
{
Regex regCaptchaCode = new Regex("src=\\'/pages/captcha\\?t=c&s=([\\d\\w\\W]+)\\'", RegexOptions.IgnoreCase);
if (regCaptchaCode.IsMatch(webBrowserMain.DocumentText))
{
pictureBox1.ImageLocation = #"http://www.clix-cents.com/pages/captcha?t=c&s=" + regCaptchaCode.Match(webBrowserMain.DocumentText).ToString();
}
}
}
private void webBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) // This is only way It worked for me.
{
if (webBrowserMain.Url.AbsoluteUri == #"http://www.clix-cents.com/pages/clickads")
{
Regex regAddId = new Regex("onclick=\\'openad\\(\"([\\d\\w]+)\"\\);", RegexOptions.IgnoreCase); // Find link and click it.
if (regAddId.IsMatch(webBrowserMain.DocumentText))
{
string AddId = regAddId.Match(webBrowserMain.DocumentText).Groups[1].ToString();
nextUrl = #"http://www.clix-cents.com/pages/clickads?h=" + AddId;
t.Start();
}
}
else if (webBrowserMain.Url.AbsoluteUri.Contains("http://www.clix-cents.com/pages/clickads?h=")) // up to there everything is ok. But problem starts here.
{
nextUrl = "";
t.Start();
}
}
The actual implementation will depend on the actual data on the site and how you want to use it. If all the links are on one page and you want to open each one, you could parse for all the links and store into a list. Then start the timer. At each Tick, you could open 1 item.