I have an mobile application (.NET CF2 for Windows Mobile 6.1) that starts right after the system startup.
I want to force the form to load and them call a web service. there`s also a button that invokes the WS mannually.
I haven`t managed to first load the form so far. First it invokes the service and them it shows the form up.
Can you help me?
Bellow the code I`m using.
//MAIN FORM OF THE APP
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace AtualizaColetores
{
public partial class frmInicio : Form
{
public frmInicio()
{
InitializeComponent();
Program.ShowHide.ShowTopStatusbar(false);
ThreadPool.QueueUserWorkItem(delegate
{
Thread.Sleep(1000);
//incia animação para indicar processamento em segundo plano
Cursor.Current = Cursors.WaitCursor;
Cursor.Show();
Atualizador executar = new Atualizador();
executar.AtualizaColetor();
});
try
{
Process firstProc = new Process();
firstProc.StartInfo.FileName = #"\WOPT\RF_WOPT.exe";
firstProc.EnableRaisingEvents = true;
firstProc.Start();
firstProc.WaitForExit();
this.Activate();
Form destino = new frmControles();
destino.Show();
}
catch (Exception ex)
{
MessageBox.Show("Erro na incialização do programa: " + ex.Message);
return;
}
//Para a animação para indicar processamento em segundo plano
Cursor.Current = Cursors.Default;
Cursor.Show();
}
}
}
//Center code hereODE TO DOWNLOAD AND REPLACE THE CURRENT VERSION OF THE APP, IF NEEDED
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using Ionic.Zip;
namespace AtualizaColetores
{
class Atualizador
{
public void AtualizaColetor()
{
if (File.Exists(#"\WOPT\About.xml"))
{
string versaoAplicativo = "", LocalAplicativo = "", tipoColetor = "";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"\WOPT\About.xml");
XmlNodeList xnList = xmlDoc.GetElementsByTagName("VersaoRF");
foreach (XmlNode xn in xnList)
{
versaoAplicativo = xn["versaoAplicativo"].InnerText;
LocalAplicativo = xn["localAplicativo"].InnerText;
tipoColetor = xn["tipoColetor"].InnerText;
}
ConectorWOPT.WOPT executar = new ConectorWOPT.WOPT();
//inserir tratamento de erro aqui.
byte[] arquivo = executar.AtualizaColetores(LocalAplicativo, versaoAplicativo, tipoColetor);
string caminhoWOPT = #"\WOPT";
if (arquivo.Length > 0)
{
try
{
MemoryStream ms = new MemoryStream(arquivo);
FileStream fs = new FileStream(
#"\novaVersao.zip", FileMode.Create);
ms.WriteTo(fs);
ms.Close();
fs.Close();
fs = null;
ms = null;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
if (System.IO.Directory.Exists(caminhoWOPT))
{
try
{
System.IO.Directory.Delete(caminhoWOPT, true);
if (!System.IO.File.Exists(caminhoWOPT))
{
System.IO.Directory.CreateDirectory(caminhoWOPT);
}
}
catch (IOException e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
if (File.Exists(#"\novaVersao.zip"))
{
using (ZipFile zip = ZipFile.Read(#"\novaVersao.zip"))
{
foreach (ZipEntry e in zip)
{
e.Extract(#"\WOPT\", ExtractExistingFileAction.OverwriteSilently); // overwrite == true
}
}
System.IO.File.Delete(#"\novaVersao.zip");
System.Windows.Forms.MessageBox.Show("Coletor atualizado com sucesso");
}
else
{
System.Windows.Forms.MessageBox.Show("Falha na atualização");
}
}
}
else
{
System.Windows.Forms.MessageBox.Show("O aplicativo não está instalado neste coletor. Contate um supervisor.");
}
}
}
}
Just delay the processing with a timer or thread. Something along these lines:
public frmInicio()
{
InitializeComponent();
Program.ShowHide.ShowTopStatusbar(false);
ThreadPool.QueueUserWorkItem(delegate
{
Thread.Sleep(1000); // or however long you need
btnZip_Click(this, EventArgs.Empty);
});
}
Or put the call in OnActivate, checking for a first run.
EDIT 1
You have a lot (too much IMO) going on in your constructors. I'm betting the Form visibility issue has a lot to do with the fact that you are creating a Process in your Form constructor and then waiting for that process to complete before continuing. If that app is waiting on the output of your web service call, the thread creation was pointless because you've still made the constructor serially dependent on the call.
Related
I am a C # amateur I am not a professional developer and would like to ask my colleagues for help, I would like to make a C # program that connects to an SSH server. Then, depending on the selected value in combobox, the program downloads the appropriate string and I would like to send it to the ssh server to the specified path path and save the value from the string to the file;)
I tried to rewrite the code but something did not work out and I stopped in my place ;( Can anyone help me. Thanks in advance for your help.
this is my code
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 System.Threading;
using Renci.SshNet;
namespace FileGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SshClient sshClient = new SshClient("192.168.1.22", 22, "root", "pass");
sshClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(120);
sshClient.Connect();
ShellStream shellStreamSSH = sshClient.CreateShellStream("vt-100", 80, 60, 800, 600, 65536);
Thread thread = new Thread(() => recvSSHData(shellStreamSSH));
thread.Start();
//I don't know how to get the information if it is connected correctly and change e.g. btnConnect label to Connected.
}
public static void recvSSHData(ShellStream shellStreamSSH)
{
while (true)
{
try
{
if (shellStreamSSH != null && shellStreamSSH.DataAvailable)
{
string strData = shellStreamSSH.Read();
}
}
catch
{
}
System.Threading.Thread.Sleep(200);
}
}
string data1 = "data1";
string data2 = "data2";
string data3 = "data3";
string check;
string path = "/home/test01/desktop";
string filename = "test.txt";
private void btnSend_Click(object sender, EventArgs e)
{
if (cmbData.SelectedIndex == 0)
{
check = data1;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 1)
{
check = data2;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 2)
{
check = data3;
MessageBox.Show(check);
}
else
{
MessageBox.Show("Choose a value");
}
//And now there should be an instruction that sends a string check to the server to path to file replacing its contents
}
}
}
Ok, I coped with everything but I am on the last step, how to save the contents of string to a file using client scp ??
string text= "bal bla bla bla bla"
string path = "#/home/test01/desktop/";
string filename = "test1.txt"
...
try
{
MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(text));
scpClient.Upload(mStrm, path + filename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I have error:
Renci.SshNet.Common.ScpException: scp: error: unexpected filename:
w Renci.SshNet.ScpClient.CheckReturnCode(Stream input)
w Renci.SshNet.ScpClient.UploadFileModeAndName(IChannelSession channel, Stream input, Int64 fileSize, String serverFileName)
w Renci.SshNet.ScpClient.Upload(Stream source, String path)
w FileGenerator.Form1.btnSend_Click(Object sender, EventArgs e) w C:\Users\backu\source\repos\FileGenerator\FileGenerator\Form1.cs:wiersz 192
i am currently working on a Windows Forms App in c# which will allow the user to add or delete records. when i hit the button to display all the records written to the file the files appear, but when i try to delete by transact number i get an exception saying that "The process cannot access the the because it is being used somewhere else". i have tried putting it in a try-catch block to make sure the reader/writer will close and still not working code will be attached any help is greatly appreciated. p.s im not looking for code to finish this project just help getting by this exception and make it work like it is suppose.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MMFileIO
{
public partial class MMAssignment3 : Form
{
StreamWriter writer;
StreamReader reader;
string record = "";
public MMAssignment3()
{
InitializeComponent();
}
private void MMAssignment3_Load(object sender, EventArgs e)
{
txtFile.Text = #"c:\burnable\assignment3.txt";
if (!Directory.Exists(txtFile.Text.Substring
(0, txtFile.Text.LastIndexOf('\\'))))
MessageBox.Show("File path does not exist");
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (radNew.Checked)
writer = new StreamWriter(txtFile.Text, append: false);
else
writer = new StreamWriter(txtFile.Text, append: true);
}
catch(Exception ex)
{
if (writer != null)
writer.Close();
MessageBox.Show($"exception adding new record: {ex.Message}");
return;
}
record = $"{txtTransact.Text}::{txtDate.Text}::{txtSerial.Text}::" +
$"{txtToolPurchased.Text}::${txtPrice.Text}::{txtQty.Text}::" +
$"${txtAmount.Text}";
try
{
writer.WriteLine(record);
lblMessage.Text = ($"Record added");
txtTransact.Text = txtDate.Text = txtSerial.Text =
txtToolPurchased.Text = txtPrice.Text = txtQty.Text =
txtAmount.Text = "";
}
catch(Exception ex)
{
MessageBox.Show($"exception adding a new record: {ex.Message}");
}
finally
{
writer.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
List<string> records = new List<string>();
while (! reader.EndOfStream)
{
record = reader.ReadLine();
records.Add(record);
}
if (records.Count == 0)
MessageBox.Show("No records left in file");
reader.Close();
writer = new StreamWriter(txtFile.Text, append: false);
foreach (string item in records)
{
}
}
private void btnCloseFile_Click(object sender, EventArgs e)
{
txtDataDisplay.Text = "";
reader.Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
txtDataDisplay.Text = $"{"#".PadRight(10)}\t" +
$"{"Purchase-Date".PadRight(10)}\t{"Serial #".PadRight(10)}\t" +
$"{"Manufacturing Tools".PadRight(10)}\t{"Price".PadRight(10)}\t" +
$"{"Qty".PadRight(10)}\t{"Amount".PadRight(10)}\n{"".PadRight(50)}\n";
while (!reader.EndOfStream)
{
record = reader.ReadLine();
string[] fields = record.Split(new string[] { "::" }, StringSplitOptions.None);
txtDataDisplay.Text += $"{fields[0].PadRight(10)}\t" +
$"{fields[1].PadRight(10)}\t{fields[2].PadRight(10)}\t" +
$"{fields[3].PadRight(30)}\t{fields[4].PadRight(10)}\t" +
$"{fields[5].PadRight(10)}\t{fields[6].PadRight(10)}\n";
}
reader.Close();
}
I am trying to use the Ivi.Visa.Interop .dll to communicate to a Voltech PM1000+ power meter using USB. I'm relatively new to C# and do not know really where to start. I am using Visual Studio 2015 Community. I have already talked to a different instrument using GPIB and here is the code for that:
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 Ivi.Visa.Interop;
namespace commOverIP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void InitiateIOBtn_Click(object sender, EventArgs e)
{
///testing out excel
InitiateIOBtn.Text = "Initializing";
try
{
// resource manager and message-based session manager
Ivi.Visa.Interop.ResourceManager mngr = new Ivi.Visa.Interop.ResourceManager();
// GPIB address
string srcAddress = "GPIB::27::INSTR"; // GPIB address of data acquisition
//setting up communication
Ivi.Visa.Interop.FormattedIO488 instrument = new Ivi.Visa.Interop.FormattedIO488();
Ivi.Visa.Interop.IMessage Imsg = (mngr.Open(srcAddress, Ivi.Visa.Interop.AccessMode.NO_LOCK, 1000, "") as IMessage);
instrument.IO = Imsg;
instrument.IO.Clear();//clear io buffer
instrument.WriteString("*RST", true);//send RST? command to instrument
instrument.WriteString("*IDN?", true);//send IDN? command to instrument
returnOfCommand.Text = instrument.ReadString();//read IDN? result
//close communication
instrument.IO.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(instrument);
System.Runtime.InteropServices.Marshal.ReleaseComObject(mngr);
InitiateIOBtn.Text = "Initialize I/O";
//*/
}
catch(Exception exp)
{
MessageBox.Show(exp.Message);
}
InitiateIOBtn.Text = "Initialize I/O";
}
}
}
This works fine but USB seems to be a different beast. The only real lead I found was in the .dll with the:
IUsb.Init(string, Ivi.Visa.Interop.AccessMode, int, string)
I tried implementing this but I don't really know where to start.
If anyone could give me an example of how to query a "*IDN?" command that would be great. Or, even if there is a better way of doing this than through the Ivi.Visa.Interop dll.
Thanks in advance
Restart your device once. Clearing the IO also helps. Afterwards following code should work fine:
string resourceString= "USB0::xxx::xxx::xxx::0::INSTR";
ResourceManager manager = new ResourceManager();
FormattedIO488 connection = new FormattedIO488();
connection.IO = (IMessage)manager.Open(resourceString, AccessMode.NO_LOCK, 0, "");
connection.IO.Clear();
connection.WriteString("*IDN?", true);
string result = connection.ReadString();
I do what you are asking all of the time and I completely understand how frustrating it can be. I remember doing Google searches to come up with this code. The code actually came from some Keysight documentation when I bought the Agilent 82357B USB/GPIB Controller.
This can be adapted for any GPIB instrument, the only difference being the strings that you send to the instrument. These can be obtained by getting the programming manual for the instrument in which you're interested.
I installed the Keysight (formerly Agilent) I/O Library Suites that is used with the Agilent 82357B. One thing that is not obvious is that you should disable the 'Auto Discovery' option, as this feature will occasionally put your device in Local mode.
using System.Threading;
using System.Runtime.InteropServices;
// Add reference for VISA-COM 5.9 Type Library
using Ivi.Visa.Interop;
namespace USBCommunications
{
class Program
{
static void Main(string[] args)
{
Gpib.Write(address: 5, command: "*IDN?");
bool success = Gpib.Read(address: 5, valueRead: out string valueRead);
System.Console.WriteLine($"The ID is {valueRead}");
System.Console.ReadLine();
}
}
public class Gpib
{
static ResourceManager resourceManager;
static FormattedIO488 ioObject;
public static bool Write(byte address, string command)
{
resourceManager = new ResourceManager();
ioObject = new FormattedIO488();
string addr = $"GPIB::{address.ToString()}::INSTR";
try
{
ioObject.IO = (IMessage)resourceManager.Open(addr, AccessMode.NO_LOCK, 0, "");
Thread.Sleep(20);
ioObject.WriteString(data: command, flushAndEND: true);
return true;
}
catch
{
return false;
}
finally
{
try { ioObject.IO.Close(); }
catch { }
try { Marshal.ReleaseComObject(ioObject); }
catch { }
try { Marshal.ReleaseComObject(resourceManager); }
catch { }
}
}
public static bool Read(byte address, out string valueRead)
{
resourceManager = new ResourceManager();
ioObject = new FormattedIO488();
string addr = $"GPIB::{address.ToString()}::INSTR";
try
{
ioObject.IO = (IMessage)resourceManager.Open(addr, AccessMode.NO_LOCK, 0, "");
Thread.Sleep(20);
valueRead = ioObject.ReadString();
return true;
}
catch
{
valueRead = "";
return false;
}
finally
{
try { ioObject.IO.Close(); }
catch { }
try { Marshal.ReleaseComObject(ioObject); }
catch { }
try { Marshal.ReleaseComObject(resourceManager); }
catch { }
}
}
}
}
Happy programming!!
Ok so i wrote my own photo viewer to open jpg,gif,png files on my computer. However for some reason whenever i set the file association in windows, using the normal properties menu and then selecting my exe it fails to open the program when i click a picture.
I tried debugging by adding message boxes, but sofar it gives no output.
I see the current window loose focus, but nothing appears.
And task manager does not show my process ever opening.
I think windows might be preventing my application from running in some way, iv attempted to disable my antivirus and running it thinking it was that, but no dice.
Program.cs
namespace PictureViewer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args == null || args.Length == 0)
{
//Console.WriteLine("args is null"); // Check for null array
Application.Run(new Form1());
}
else
{
for (int i = 0; i < args.Length; i++) // Loop through array
{
string argument = args[i];
Application.Run(new Form1(argument));
}
}
}
}
}
Inside Form1 is 2 constructors, 1 with and one without a pram of string then i just do a
Picturebox1.Image = Image.fromFile(pram);
Im quite sure this issent a c# thing, its more of a windows being dumb thing.
Windows 8.1 for refrence.
edit: heres form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PictureViewer
{
public partial class Form1 : Form
{
string curentdirectory = "";
List<string> imageindir;
int curentindex;
public Form1()
{
InitializeComponent();
imageindir = new List<string>();
}
public Form1(string initfile)
{
InitializeComponent();
curentdirectory = initfile.Substring(0, initfile.LastIndexOf("/"));
imageindir = new List<string>();
try
{
this.Text = initfile;
img.Image = Image.FromFile(initfile);
}
catch(Exception ex)
{
MessageBox.Show("ERR");
}
}
private void btnleft_Click(object sender, EventArgs e)
{
try
{
if (--curentindex < 0)
{
curentindex = imageindir.Count - 1;
}
img.Image = Image.FromFile(imageindir[curentindex]);
}
catch (Exception ex)
{
MessageBox.Show("ERR");
}
}
private void btnright_Click(object sender, EventArgs e)
{
try
{
if (++curentindex > imageindir.Count - 1)
{
curentindex = 0;
}
img.Image = Image.FromFile(imageindir[curentindex]);
}
catch (Exception ex)
{
MessageBox.Show("ERR");
}
}
private void getDirFromFileName(string dir)
{
DirectoryInfo di;
di = new DirectoryInfo(curentdirectory);
var directories = di.GetFiles("*", SearchOption.TopDirectoryOnly);
foreach (FileInfo d in directories)
{
if(dir == d.Name)
{
curentindex = imageindir.Count;
}
if(validExtension(d.Name))
{
imageindir.Add(d.Name);
}
}
}
private bool validExtension(string val)
{
val = val.ToLower();
if (val.Contains(".jpg") || val.Contains(".jpeg") || val.Contains(".gif") || val.Contains(".png") || val.Contains(".bmp"))
return true;
return false;
}
}
}
There is an error in curentdirectory = initfile.Substring(0, initfile.LastIndexOf("/")); line. the / should be \\. May be the problem is here.
I have tested your code and it works fine. i have uploaded test project here
Editional Details:
Project has created in Visual Studio 2005.
I have created a C sharp project in which i have added a ShockwaveFlashObject to play my swf file.
The problem i am facing is when i create an installer for my project it works correctly on my machine on installation, but on my laptop the swf loads correctly but doesn't respond to the _FSCommand. I cannot use a try and catch block as it is not entering the FSCommand handle. Do i need to bundle something with my installation?
The laptop i am using is brand new and i wanted it that way so that i know what all stuff is needed for things to work correctly so that i can add prerequisites to my installer.
Also idk if this information is of any use but I am using advanced installer to build and exe for my project.
PS i have added things like the below code to know if FSCommand gets executed.
MessageBox.Show("step 1/2/3");
Here is the entire 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 MySql.Data.MySqlClient;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Globalization;
namespace WindowsFormsApplication1
{
public partial class frmFlashIntro : Form
{
public Form FormfrmMainRef { get; set; }
public frmFlashIntro()
{
InitializeComponent();
axShockwaveFlash1.Playing = true;
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
string currentPath = Directory.GetCurrentDirectory();
axShockwaveFlash1.Movie = "file://\\" + currentPath + "\\intro.swf";
}
private void axShockwaveFlash1_FSCommand(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent e)
{
MessageBox.Show("step 1");
string btn = e.command.ToString();
MessageBox.Show("step 2");
if (btn == "play")
{
MessageBox.Show("step 3");
try
{
MessageBox.Show("step 4");
var form2 = new frmMain();
MessageBox.Show("step 5");
this.Hide();
MessageBox.Show("step 6");
form2.Show();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
if (btn == "syllabus")
{
MySqlConnection con = new MySqlConnection(Properties.Settings.Default.conString);
con.Open();
Syllabus_usageInformation syl = new Syllabus_usageInformation(this);
MySqlCommand cmd = new MySqlCommand("SELECT ImageFiles FROM misc WHERE id=1", con);
byte[] img = (byte[])cmd.ExecuteScalar();
string strFn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(strFn, FileMode.CreateNew, FileAccess.Write);
fs.Write(img, 0, img.Length);
fs.Flush();
fs.Close();
con.Close();
syl.kpImageViewer1.OpenButton = false;
syl.kpImageViewer1.ImagePath = strFn;
syl.Show();
this.Hide();
}
if (btn == "usageInformation")
{ }
}
}
}
Is flash player ActiveX control installed on your laptop? You have to install it, otherwise there's nothing that can play your .swf file.