C# Winform application couldn't run when Window startup - c#

everyone
I have a problem with my application. I make an event that when I tick to a checkbox it will run when Window startup and I save this setting in a XML file. But it doesn't work and Window show me a message error "Stop working". Does anyone know what did I do wrong? I try to resolve it but it still. Thanks a lot. Here is my code:
private RegistryKey registrykeyApp = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Run", true);
private void checkBoxKhoidongcungwin_CheckedChanged(object sender, EventArgs e)
{
if (this.checkBoxKhoidongcungwin.Checked)
{
if(this.registrykeyApp.GetValue("ViKey") == null)
this.registrykeyApp.SetValue("ViKey", Application.ExecutablePath.ToString(),RegistryValueKind.ExpandString);
}
else
{
this.registrykeyApp.DeleteValue("ViKey", false);
}
}

That registry key cannot be accessed from an application that is not running with elevated privileges since viruses, etc could use it to hijack computers. Unfortunately when access is denied you often get generic errors that aren't obvious.
Right click on your exe and run it as administrator and it should work. If so you can add an application manifest to your project to always request the elevated privileges automatically, without manually right clicking.
http://www.samlogic.net/articles/manifest.htm

Related

Error while starting a WPF-Application on System-Startup

I have a WPF-Application that I would like to start automatically if I start my Computer.
I have a window where a user can configure some settings for the application, one of the possible configuration options is a checkbox, that allows the user to dis- or enable the application to automatically start on the System-Startup.
This is how I set or delete the value in the Registry, depending on the users choice in the Checkbox:
try
{
var currentAssembly = Assembly.GetExecutingAssembly();
var rkApp = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (settingsViewModel.AutostartEnabled)
{
rkApp.SetValue(currentAssembly.GetName().Name, currentAssembly.Location);
}
else
{
rkApp.DeleteValue(currentAssembly.GetName().Name, false);
}
}
catch (Exception exception)
{
}
My Problem is, that even though the Application gets registered and can also be seen in the Autostart-Section within the Task-Manager, that I get the following error every time I restart my computer to check if the Appliction is started:
"You are attempting to open a file of type Application extension (.dll)"
So what am I doing wrong? Is there any way to avoid this error or to fix it? I already tried adding an application manifest file to my project to always start my Application as an Administrator. But that didn't seem to work either.
I'd appreciate any help.
Try to use System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName instead of currentAssembly.Location.
This should give you the path of the running executable. Assembly.GetEntryAssembly does not.

Clicking a button on a windows from from a webform

I have created a windows form program that does some Business Intelligence but have subsequently needed to access this via a webform. I am fairly new to programming so I don't know what can be achieved here. But essentially I am wanting someone to go on to the net and when the user presses a button it sends a message to the windows form executable in a file and tells it to run and then press a button on the form, which runs a method to generate images of graphs. Is this possible?
Here is the relevant code.
In the webform I have this button.
protected void rolloutSmartSheets(object sender, EventArgs e)
{
string message = string.Format("Starting processes");
ltMessage.Text = message;
Process process = new Process();
process.StartInfo.FileName = #"P:\Visual Studio 2013\Projects\Smartsheet\SmartsheetAPI\obj\Debug\SmartSheetAPI.exe";
process.Start();
message = string.Format("Ended all processes");
ltMessage.Text = message;
}
That runs the executable but it opens the windows form and I imagine if the executable is sitting on another computer wouldn't that open on that computer? In which case i want it to tell it to press this button on the windows form which runs the method I need and then the user doesn't need to worry about it.
public void commitToDatabase_Click(object sender, EventArgs e)
{
commitToDataBase();
}
If you are able to have the clients install something in advance, you can provide this functionality using a custom protocol handler.
Example protocol handler from MSDN Article
HKEY_CLASSES_ROOT
alert
(Default) = "URL:Alert Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "alert.exe,1"
shell
open
command
(Default) = "C:\Program Files\Alert\alert.exe" "%1"
Then add a link onto your webform like this
href="alert://test"
As long as the client has the handler installed, both in the registry and the executable file, it will run C:\Program Files\Alert\alert.exe, passing "test" to it as the first paramater.
You can easily change this to provide the ability to run the local graph generator, and pass any parameters from the webform you might need.

getting the full filenames from all top directory files in a specific directory and suppressing the occuring error

I met a not expected problem with getting just the top directory full filenames from a specific directory. C# throws an error and doesn't list anything in the specific directory.
But MS DOS has not a problem with my command: *"dir C:\windows\prefetch\*.pf"
Visual Basics 6 old "Dir Function" also does it without complaining.
The "Windows Explorer" opens it up and doesn't ask anything from me. Also "Nirsofts Tool Suit" lists it instantly without any problem. No one of this tools needs to run with special permissions, just a double click on the application icon and ready is the task.
I looked around and found nothing here, what would answer this weird problem. My user can access the directory, if I go with any other application into it, now there is the question why C# throws
an "Unauthorized Access Exception" which is totally weird, since I have access in this folder.
I don't want to elevate my application with admin permissions for it nor create extra a xml for it to run it with highest privileges. The not trustful yellow elevation box must be avoided.
Now my question: How it comes that I can not list the filenames in this folder when all other
applications can do that.
What code do I need if "Directory.GetFiles()" fails?
Is there any flag or property in the framework directory class which allows my application access to the files, whatever.
Here my code which fails (using System.IO):
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Substring(0, 0); //clear the textBox1
//Unauthorized access exception and yellow bar in this line
foreach(string FileX in Directory.GetFiles(Path.Combine(Environment.GetEnvironmentVariable("windir"), "prefetch"), "*.pf"))
{
textBox1.Text += FileX;
}
}
Did I understand correctly that you only need the File-names with directory-names.
This code works for me, no elevations needed.
private void button1_Click(object sender, EventArgs e)
{
string folder = #"C:\windows\prefetch";
string filemask = #"*.pf";
string[] filelist = Directory.GetFiles(folder, (filemask));
//now use filelist[i] for any operations.
}

Launching JAR with Process.Start: javaw.exe runs but "nothing happens"?

Given the code. when the button is clicked nothing happens , i get no debug message etc in visual studio. However if i were to double click the .jar file in its folder i am able to run it. Anyone have any idea why?
Looking at Task manager when the button is clicked. javaw.exe is created but nothing happens.
private void btnKinderPuzzle_Click(object sender, RoutedEventArgs e)
{
// Check if this program is opened
if (IsProcessOpen("MTPuzzle"))
{
MessageBox.Show("KinderPuzzle is already running", "Kinder Package", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
Process.Start(Directory.GetCurrentDirectory() + "\\Puzzle\\PuzzleGame\\MTPuzzle.jar");
}
}
Process.Start("java.exe",
Path.Combine("-jar " + Directory.GetCurrentDirectory(),
"Puzzle\\PuzzleGame\\MTPuzzle.jar"));
The path may be not correct. You might use instead
Process.Start(Path.Combine(Directory.GetCurrentDirectory(), "Puzzle\\PuzzleGame\\MTPuzzle.jar"));
If stills, then I think the problem in the setting of Java. To solve this potential problem, create a file run.cmd near your jar file and write this code into:
java -jar "MTPuzzle.jar"
Then, use Process.Start to start the file run.cmd

C#, working with files, "Unauthorized Access"?

I'm learning about opening and saving files with C# and it seems that vista won't let my program save to a file on the root of C:\ , unless I run it in administrator mode.
Any ideas how to allow my program to play around with whatever files it wants?
Thanks!
private string name;
private void open_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
name = openFileDialog1.FileName;
textBox1.Clear();
textBox1.Text = File.ReadAllText(name);
textBox2.Text = name;
}
}
private void save_Click(object sender, EventArgs e)
{
File.WriteAllText(name, textBox1.Text);
}
To make your program start with administrator rights, you have to change the manifest. This can be done by Add New Item -> General -> Application Manifest File. Open the manifest and set "requestedExecutionLevel" to "requireAdministrator". When this is done, open the project settings and on the 'Application' tab choose your new manifest.
The program will run with your credentials, by default.
So, these do not have the right permissions to write to the root folder.
If you want it to run with other credentials you can us the runas command line to execute the application with other credentials.
Alternatively, grant more permissions to the account the application runs as.
There are several reasons for the UnauthorizedAccess Exception. Check one of those:
path specified a file that is read-only.
This operation is not supported on the current platform.
path specified a directory.
I accidently hit the third problem today ;-)

Categories