I create a windows service and a setup project.
During the installation of the windows service, I add a windows form which allow the user to upload a file in the project folder but when I click on the button to upload the file my windows form is always on state not responding
ProjectInstaller of my windows service
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
Form1 validationForm = new Form1();
validationForm.ShowDialog();
}
Windows form
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
//fileDialog.Filter = "Dat files |*.dat";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
var path = fileDialog.FileName;
Process.Start(path);
}
}
catch (Exception)
{
MessageBox.Show("An error occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I think Process.Start(path); block UI thread.
Try to use Task.Run(() => Process.Start(a)); instead.
Your UI is locked up due to a long running process which is why you see "Not responding"
Mark your Click Async:
private async void button1_Click_1(object sender, EventArgs e)
and
await Task.Run(() =>
{
//Insert the long running stuff here
Process.Start(path);
});
Try this.
private void button1_Click(object sender, EventArgs e)
{
var task = new Thread(() => GetFile());
task.SetApartmentState(ApartmentState.STA);
task.Start();
task.Join();
}
private static void GetFile()
{
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
//fileDialog.Filter = "Dat files |*.dat";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
var path = fileDialog.FileName;
Process.Start(path);
}
}
catch (Exception)
{
MessageBox.Show("An error occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Related
I've created a .net application that needs to be able to be used without an internet connection. This application uses the CefSharp C# library to embed my rails app in a windows form. Below is my Main() function which sets up the cefsharp settings
static void Main()
{
//For Windows 7 and above, best to include relevant app.manifest entries as well
Cef.EnableHighDPISupport();
//We're going to manually call Cef.Shutdown below, this maybe required in some complex scenarios
CefSharpSettings.ShutdownOnExit = false;
var cachePath = "cache";
if (!Directory.Exists(cachePath)) Directory.CreateDirectory(cachePath);
var settings = new CefSettings();
settings.CachePath = cachePath;
settings.LogFile = "f7chromium.log";
settings.BrowserSubprocessPath = #"x86\CefSharp.BrowserSubprocess.exe";
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
Debug.WriteLine("Starting");
host = MyServer.Run();
//var browser = new BrowserForm();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Console.ReadLine();
}
Code to initialize form
public partial class Form1 : Form
{
public ChromiumWebBrowser chromeBrowser;
private static string baseUrl = "https://goo.com/";
public void InitializeChromium()
{
var url = baseUrl;
chromeBrowser = new ChromiumWebBrowser(url);
// Add it to the form and fill it to the form window.
this.Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
}
public Form1()
{
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
Bounds = Screen.PrimaryScreen.Bounds;
InitializeComponent();
InitializeChromium();
HotkeyManager.Current.AddOrReplace("Close", Keys.F10, OnClose);
HotkeyManager.Current.AddOrReplace("Reset", Keys.F8, OnReset);
HotkeyManager.Current.AddOrReplace("Refresh", Keys.F5, OnRefresh);
HotkeyManager.Current.AddOrReplace("DevTools", Keys.F3, DevTools);
}
private void DevTools(object sender, HotkeyEventArgs e)
{
chromeBrowser.ShowDevTools();
}
private void OnReset(object sender, HotkeyEventArgs e)
{
var result = MessageBox.Show("Confirm reset all station data", "Confirm Reset", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK) chromeBrowser.Load(baseUrl + "/reset");
}
private void OnRefresh(object sender, HotkeyEventArgs e)
{
chromeBrowser.Reload();
}
private void OnClose(object sender, HotkeyEventArgs e)
{
var result = MessageBox.Show("Close application?", "Confirm Exit", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
{
Process.Start(#"C:\");
Process.Start(#"powershell.exe");
Close();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
}
Is it possible to launch the application without an internet connection similarly to how you can load sites in chrome from cache by enabling the show-page-copy button?
I am having a problem with a with a code that I used for my C# application. When I click on the browse button and select the file dialogue box opens twice.
private void txt_location_TextChanged(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
folderPath = folderBrowserDialog1.SelectedPath;
}
}
private void Button21_Click(object sender, EventArgs e)
{
using(var fbd = new FolderBrowserDialog()) {
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) {
selectedPath = fbd.SelectedPath;
txt_location.Text = selectedPath;
}
}
}
private void bunifuThinButton21_Click_1(object sender, EventArgs e)
{
System.IO.StreamWriter file;
bool isvalid = ValidateInputs();
try {
file = new System.IO.StreamWriter(selectedPath + # "\dred.txt");
catch (Exception ex) {
MessageBox.Show("Please, Select valid Path..");
return;
}
try {
if (isvalid) {
WriteLines(file);
}
}
catch (Exception ex2) {
MessageBox.Show(ex2.Message);
}
finally {
file.Close();
}
}
}
Obviously, it is only meant to open once to enable me to read the selected file. This works, but only once I have selected the file twice.
Thanks in advance for your help.
You have FolderBrowserDialog being instantiated and shown on two different events:
txt_location_TextChanged
and
Button21_Click
You're having two popups because each one is firing once separately.
You should probably remove the event txt_location_TextChanged entirely unless you need it for another thing that isn't popping the FolderBrowserDialog again.
I created an app for my dad. It's just a simple dictation program. The thing is when he installed it on his computer it stalled and said the general access denied error.
The first time it gave the error I used SaveFileDialog sfd = new SaveFileDialog() then added the usually 'if statement" to make sure the dialog was ok. However the app had an access file denied.
I did the same thing with Environment.GetFolder and it installed on his computer to the location and ran fine. However, when I use the saveFileDialog1 and openFileDialog1 out of the tool box it does not save or open a txt document.
It works on my laptop and not his. Could this be due to an error in the code vs his computer. Also what is the correct way to use the Environement.GetFolder with the SaveFileDialog.
I can also post the full code to the program if needed.
private void lblOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Title = "Open File";
open.Filter = "Text Files (*txt) | *.txt";
if (open.ShowDialog() == DialogResult.OK)
{
StreamReader read = new StreamReader(File.OpenRead(open.FileName));
txtTextBox.Text = read.ReadToEnd();
read.Dispose();
}
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
This is the Enviroment i used on my screen recorder. i when i click save it brings up a dialog box i put in the file name press save and it does nothing. It saves the file but not as i specified. So i am trying to merge the above and below codes. The above code does not grant access however the below does
string OutputPath;
OutputPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + #"\\IvanSoft Desktop Recorder" + saveFileDialog1;
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string fileName = saveFileDialog1.FileName;
fileName = "Tutorial";
}
the whole code to the program
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading;
namespace AGM_Speech
{
public partial class Form1 : Form
{
public SpeechRecognitionEngine recognizer;
public Grammar grammar;
public Thread RecThread;
public Boolean RecognizerState = true;
public Form1()
{
InitializeComponent();
}
private void lblAbout_Click(object sender, EventArgs e)
{
this.Hide();
About about = new About();
about.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
GrammarBuilder builder = new GrammarBuilder();
builder.AppendDictation();
grammar = new Grammar(builder);
recognizer = new SpeechRecognitionEngine();
recognizer.LoadGrammarAsync(grammar);
recognizer.SetInputToDefaultAudioDevice();
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
RecognizerState = true;
RecThread = new Thread(new ThreadStart(RecThreadFunction));
RecThread.Start();
}
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (!RecognizerState)
return;
this.Invoke((MethodInvoker)delegate
{
txtTextBox.Text += (e.Result.Text.ToLower() + " ");
txtTextBox.SelectionStart = txtTextBox.Text.Length - 0;
txtTextBox.SelectionLength = 0;
});
}
public void RecThreadFunction()
{
while (true)
{
try
{
recognizer.RecognizeAsync();
}
catch
{
}
}
}
private void lblStartSpeech_Click(object sender, EventArgs e)
{
RecognizerState = true;
}
private void lblStopSpeech_Click(object sender, EventArgs e)
{
RecognizerState = false;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
RecThread.Abort();
RecThread = null;
grammar = null;
recognizer.UnloadAllGrammars();
recognizer.Dispose();
}
private void lblOpenFile_Click(object sender, EventArgs e)
{
string open = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StreamReader reader = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
private void txtSearch_Click(object sender, EventArgs e)
{
txtSearch.Clear();
lblGo_Click(null, null);
}
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)ConsoleKey.Enter)
{
lblGo_Click(null, null);
}
}
private void lblGo_Click(object sender, EventArgs e)
{
int index = 0;
String temp = txtTextBox.Text;
txtTextBox.Text = "";
txtTextBox.Text = temp;
while (index <= txtTextBox.Text.LastIndexOf(txtSearch.Text))
{
txtTextBox.Find(txtSearch.Text, index, txtTextBox.TextLength, RichTextBoxFinds.None);
txtTextBox.SelectionColor = Color.YellowGreen;
index = txtTextBox.Text.IndexOf(txtSearch.Text, index) + 1;
}
}
}
}
It's hard to say where you're failing, because there isn't much in the way of try/catch or logging.
Can you use this instead, and paste the stack trace that shows in the Message Box?
private string fileOutputLocation { get; set; }
private void lblSaveFile_Click(object sender, EventArgs e)
{
bool fileSelected = false;
Try(() =>
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
save.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), "IvanSoft Desktop Recorder");
if (save.ShowDialog() == DialogResult.OK)
{
fileOutputLocation = save.FileName;
fileSelected = true;
}
});
if (fileSelected)
{
bool fileSaved = SaveFile();
MessageBox.Show("File saved successfully: " + fileSaved.ToString());
}
}
private bool SaveFile()
{
TryDeleteFile();
bool fileSaved = false;
Try(()=>
{
File.WriteAllText(fileOutputLocation, txtTextBox.Text);
fileSaved = true;
});
return fileSaved;
}
private void TryDeleteFile()
{
Try(()=>
{
if (File.Exists(fileOutputLocation))
{
File.Delete(fileOutputLocation);
}
});
}
private void Try(Action action)
{
try
{
action();
}
catch (Exception e)
{
MessageBox.Show(string.Format("The following exception was thrown:\r\n{0}\r\n\r\nFile path: {1}", e.ToString(), fileOutputLocation));
}
}
With this, plus the events logged to the Windows Event Viewer (Start>Run>Eventvwr>Security), we should be able to tell you what the problem is.
Lastly, if you're just providing an executable to run, you should check the properties of the file to ensure it's not blocked in Windows.
I have tried to install an exe developed using Wix installer. After installation completed, tried to restart the system. Following sample logic I used.
Samples :
private void btn_RestartYes_Click(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(new ThreadStart(RestartThreadFunction));
thread.Start();
this.Close();
SyncBA.Model.Engine.Quit(0);
}
public void RestartThreadFunction()
{
try
{
Process.Start("shutdown", "/r");
}
catch (Exception ex)
{
SyncBA.Model.Engine.Log(LogLevel.Error, ex.Message);
}
}
private void btn_RestartLater_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
( OR )
private void btn_RestartYes_Click(object sender, RoutedEventArgs e)
{
RestartThreadFunction();
}
public void RestartThreadFunction()
{
try
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.WindowStyle = ProcessWindowStyle.Hidden;
proc.FileName = "cmd";
proc.Arguments = "/C shutdown -f -r";
Process.Start(proc);
SyncBA.Model.Engine.Quit(0);
this.Close();
}
catch (Exception ex)
{
SyncBA.Model.Engine.Log(LogLevel.Error, ex.Message);
}
}
private void btn_RestartLater_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
Above logic is successfully working fine. After restarted the system "exe" uninstall window appear.
How to resolve an uninstall window appear issue after restart the system?
Thanks in advance!!
I am using DropNet. I have problem with upload file into DropBox.
I am sure the connection with dropbox in fine. when I changed the method of upload to create file and delete file method that works fine.
I really can not see any problem that why is not uploading? I use exactly same API as DropNet.
protected void Btn_upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (Session["DropNetUserLogin"] != null)
{
try
{
_client.UseSandbox = true;
_client.UploadFile("/", FileUpload1.FileName, FileUpload1.FileBytes);
}
catch (Exception ex)
{
litOutput.Text = "Error in upload user login in session " + ex.Message;
}
}
else
{
litOutput.Text = "Session expired...";
}
}
else
{
litOutput.Text = "You did not specify a file to upload.";
}
}
}
Here is code which worked for me, hoping that this may help you:
private void button1_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
FileNameTextBox.Text = filename;
}
var x = #"/" + Path.GetFileName(FileNameTextBox.Text);
_client.UploadFile("/", Path.GetFileName(FileNameTextBox.Text), File.ReadAllBytes(#"" + FileNameTextBox.Text));
}