How to send custom commands to a service c# - c#

I'm using a windows service and a windows form. I have been trying to send custom commands to a service in order to create an isolated storage file. However when I click my "btnSubmit" no file is created. For some reason it doesn't seem to execute the command
Code in Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Project2Service;
namespace Project2
{
public partial class Form1 : Form
{
public Service1 s = new Service1();
public ServiceInstaller si = new ServiceInstaller();
public ProjectInstaller pi = new ProjectInstaller();
public ServiceController sc = new ServiceController("Project2Service");
private string[] isoType;
string machineName = System.Windows.Forms.SystemInformation.ComputerName;
public Form1()
{
InitializeComponent();
isoType = new string[] { "User", "Assembly And Domain"};
cboIsoType.Items.AddRange(isoType);
cboIsoType.SelectedIndex = 0;
btnContinue.Enabled = false;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
public void Labels()
{
lblMachine.Text = machineName;
lblSName.Text = s.ServiceName;
lblSType.Text = si.StartType.ToString();
lblSStatus.Text = sc.Status.ToString();
lblPause.Text = sc.CanPauseAndContinue.ToString();
lblShutdown.Text = sc.CanShutdown.ToString();
lblStop.Text = sc.CanStop.ToString();
}
private void btnStart_Click(object sender, EventArgs e)
{
//Controller.Refresh(); //Gets the current status of service
//if (Controller.Status == ServiceControllerStatus.Stopped)
//{
// Controller.Start();
//}
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
Labels();
btnStart.Enabled = false;
btnContinue.Enabled = false;
btnStop.Enabled = true;
btnPause.Enabled = true;
}
private void btnStop_Click(object sender, EventArgs e)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
Labels();
btnStart.Enabled = true;
btnContinue.Enabled = false;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
private void btnPause_Click(object sender, EventArgs e)
{
sc.Pause();
sc.WaitForStatus(ServiceControllerStatus.Paused);
Labels();
btnPause.Enabled = false;
btnContinue.Enabled = true;
btnStart.Enabled = false;
btnStop.Enabled = true;
}
private void btnContinue_Click(object sender, EventArgs e)
{
sc.Continue();
sc.WaitForStatus(ServiceControllerStatus.Running);
Labels();
btnStop.Enabled = true;
btnStart.Enabled = false;
btnPause.Enabled = true;
btnContinue.Enabled = false;
}
private void btnSubmit_Click(object sender, EventArgs e)
{
if (cboIsoType.SelectedItem.ToString() == "User")
{
sc.ExecuteCommand(128);
}
}
}
}
My Service Controller
public enum ServiceCustomCommands { Command1 = 128, Command2 = 129 };
//private IsolatedStorageScope iso;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Domain;
FileSystemWatcher Watcher = new FileSystemWatcher(#"C:\Users\Martin\Desktop\Project2\ServiceTest");
Watcher.EnableRaisingEvents = true;
Watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
Watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
WriteServiceInfo("Service Started!");
}
// This event is raised when a file is changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Changed!");
DirectoryInfo d = new DirectoryInfo(#"C:\Users\Martin\Desktop\Project2\ServiceTest");//Assuming Watch is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
str = str + ", " + file.LastWriteTime;
str = str + ", " + file.CreationTime;
str = str + ", " + file.Length;
WriteServiceInfo(file.Name);
WriteServiceInfo(file.LastWriteTime.ToString());
WriteServiceInfo(file.CreationTime.ToString());
WriteServiceInfo(file.Length.ToString());
}
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Created!");
}
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Deleted!");
}
private void Watcher_Renamed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Renamed!");
}
private void WriteServiceInfo(string info)
{
FileStream fs = new FileStream(#"C:\Users\Martin\Desktop\Project2\WindowsServiceLog.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(info + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnCustomCommand(int command)
{
switch ((ServiceCustomCommands)command)
{
case ServiceCustomCommands.Command1:
//Command1 Implementation
IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt", FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
//iso = IsolatedStorageScope.User;
break;
case ServiceCustomCommands.Command2:
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
break;
default:
break;
}
}

I think you need to add ServieControllerPermission:
ServiceController sc = new ServiceController("YOURServiceName", Environment.MachineName);
ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, Environment.MachineName, "YOURServiceName");//this will grant permission to access the Service
scp.Assert();
sc.Refresh();
sc.ExecuteCommand((int)YourMethods.methodX);

Related

Why when using filcesystemwatcher and dictionary with fileinfo it's throwing exceptions on wrong key and file not found?

Link for the repository on github :
https://github.com/chocolade1972/FileSystemWatcher
At the top i init with new instance both filelist and dic variables.
Then when starting watching i get all the files . and add them to the filelist and to the dic.
If for example the path is C:\ then filelist will contain 6 items :
filelist = Directory.GetFiles(textBox_path.Text, "*.*").ToList();
foreach (var item in filelist)
{
FileInfo info = new FileInfo(item);
dic.Add(item, info.Length);
}
Then in the event Watcher_Changes at this line :
var info = new FileInfo(e.FullPath);
There is exception the file not found and i see when using a breakpoint a long file temp type with tmp extension.
Then on other files it's throwing exceptions key was not present and then if i will start watching over again it will throw exceptions that the key is the same and already exist.
Other problem is now the button Button_doit in the event Button_doit_Click is not changing to stop and stay on start all the time.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
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 Microsoft.Win32;
namespace Watcher_WPF
{
/// <summary>
/// MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Watcher watcher;
private List<string> filelist = new List<string>();
private Dictionary<string, long> dic = new Dictionary<string, long>();
public MainWindow()
{
InitializeComponent();
CenterWindowOnScreen();
var nf = new NFilters()
{
Size = true,
FileName = true,
DirectoryName = true,
};
watcher = new Watcher(nf);
watcher.Created += Watcher_Changes;
watcher.Changed += Watcher_Changes;
watcher.Deleted += Watcher_Changes;
watcher.Renamed += Watcher_Renamed;
PrintMsg(Application.ResourceAssembly.ToString());
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (watcher.IsStarted)
{
e.Cancel = MessageBox.Show("Watcher is working, are you sure to close?", "Oh!",
MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No;
}
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
//Ctrl
if (e.KeyboardDevice.IsKeyDown(Key.LeftCtrl) || e.KeyboardDevice.IsKeyDown(Key.RightCtrl))
{
if (e.KeyboardDevice.IsKeyDown(Key.S))
{
//Ctrl+S
SaveLogs(null, null);
}
else if (e.KeyboardDevice.IsKeyDown(Key.D))
{
//Ctrl+D
ClearLogs(null, null);
}
}
}
private void Button_doit_Click(object sender, RoutedEventArgs e)
{
try
{
if (!watcher.IsStarted)
{
SetPath(textBox_path.Text.Trim());
}
watcher.IsStarted = !watcher.IsStarted;
if(button_doit.Content.ToString() == "Stop")
{
add_path.IsEnabled = true;
}
else
{
add_path.IsEnabled = false;
RandomFiles.GenerateFiles();
filelist = Directory.GetFiles(textBox_path.Text, "*.*").ToList();
foreach (var item in filelist)
{
FileInfo info = new FileInfo(item);
dic.Add(item, info.Length);
}
}
button_doit.Content = watcher.IsStarted ? "Stop" : "Start";
button_doit.Foreground = watcher.IsStarted ? Brushes.Red : Brushes.Black;
textBox_path.IsEnabled = !watcher.IsStarted;
PrintMsg(watcher.IsStarted ? "watcher started...At " + DateTime.Now.ToString() : "watcher stopped...At " + DateTime.Now.ToString());
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Button_options_Click(object sender, RoutedEventArgs e)
{
options.IsOpen = true;
}
private void OptionsMenu_Opened(object sender, RoutedEventArgs e)
{
allow_edit.IsChecked = !richTextBox_main.IsReadOnly;
topmost_switcher.IsChecked = Topmost;
filter_setter.IsEnabled = !watcher.IsStarted;
include_subdir.IsEnabled = !watcher.IsStarted;
include_subdir.IsChecked = watcher.IncludeSubdirectories;
}
private void AddPath(object sender, RoutedEventArgs e)
{
// Configure open file dialog box
var dialog = new Microsoft.Win32.OpenFileDialog();
dialog.FileName = "Document"; // Default file name
dialog.DefaultExt = ".*"; // Default file extension
dialog.Filter = "All files|*.*"; // Filter files by extension
// Show open file dialog box
bool? result = dialog.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
textBox_path.Text = dialog.FileName;
}
}
private void SaveLogs(object sender, RoutedEventArgs e)
{
try
{
SaveFileDialog sfd = new SaveFileDialog()
{
Filter = "TXT|*.txt",
FileName = $"watcher_{DateTime.Now:yyyyMMddHHmmss}"
};
if (sfd.ShowDialog() == true)
{
string path = sfd.FileName;
string content = new TextRange(
richTextBox_main.Document.ContentStart,
richTextBox_main.Document.ContentEnd).Text;
File.WriteAllText(path, content);
PrintMsg($"saved log to \"{path}\"");
}
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void ClearLogs(object sender, RoutedEventArgs e)
{
richTextBox_main.Document.Blocks.Clear();
}
private void Switch_Window_Topmost(object sender, RoutedEventArgs e)
{
Topmost = !Topmost;
}
private void Allow_edit_Click(object sender, RoutedEventArgs e)
{
richTextBox_main.IsReadOnly = !richTextBox_main.IsReadOnly;
}
private void Filter_setter_Click(object sender, RoutedEventArgs e)
{
var tmp = new FilterWindow(watcher.NFilters, watcher.Filter) { Owner = this }.ShowDialog();
if (tmp is Fdr fdr)
{
watcher.Filter = fdr.Filter;
watcher.NFilters = fdr.Nfilters;
PrintMsg($"set Filter: Size={watcher.NFilters.Size}, FileName={watcher.NFilters.FileName}, " +
$"DirectoryName={watcher.NFilters.DirectoryName}, Filter=\"{watcher.Filter}\"");
}
}
private void Include_subdir_Click(object sender, RoutedEventArgs e)
{
watcher.IncludeSubdirectories = !watcher.IncludeSubdirectories;
PrintMsg($"IncludeSubdirectories={watcher.IncludeSubdirectories}");
}
private void View_source_code_Click(object sender, RoutedEventArgs e)
{
Process.Start("https://github.com/Mzying2001/Watcher_WPF");
}
private void TextBox_path_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
Button_doit_Click(null, null);
}
private void RichTextBox_main_TextChanged(object sender, TextChangedEventArgs e)
{
if (richTextBox_main.IsReadOnly)
richTextBox_main.ScrollToEnd();
}
private void SetPath(string path)
{
watcher.Path = path;
PrintMsg($"set path: \"{watcher.Path}\"");
}
private void Watcher_Changes(object sender, FileSystemEventArgs e)
{
try
{
if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Deleted)
{
}
else
{
var info = new FileInfo(e.FullPath);
var newSize = info.Length;
var oldsize = dic[e.FullPath];
string FileN1 = "File Name : ";
string FileN2 = info.Name;
string FileN3 = " Size Has Changed : From ";
string FileN4 = oldsize.ToString();
string FileN5 = " To ";
string FileN6 = newSize.ToString();
if (newSize != oldsize)
{
//string output = $"[*] {e.ChangeType}: \"{e.FullPath}\"";
Println(FileN1 + FileN2 + FileN3 + FileN4 + FileN5 + FileN6);
}
if (dic.ContainsKey(e.FullPath))
{
dic[e.FullPath] = info.Length;
}
else
{
dic.Add(e.FullPath, info.Length);
}
}
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
try
{
Println($"[*] {e.ChangeType}: \"{e.OldFullPath}\" -> \"{e.FullPath}\"");
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Println(string text, SolidColorBrush brush) => Dispatcher.Invoke(() =>
{
richTextBox_main.Document.Blocks.Add(new Paragraph(new Run(text) { Foreground = brush }));
});
private void Println(string text)
{
Println("[+] " + text + " At : " + DateTime.Now.ToString(), Brushes.LawnGreen);
}
private void PrintMsg(string message)
{
Println($"[+] {message}", Brushes.Yellow);
}
private void PrintErr(Exception e)
{
Println($"[-] {e}", Brushes.Red);
}
private void CenterWindowOnScreen()
{
double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
double windowWidth = this.Width;
double windowHeight = this.Height;
this.Left = (screenWidth / 2) - (windowWidth / 2);
this.Top = (screenHeight / 2) - (windowHeight / 2);
}
private byte[] CheckSize(string filename)
{
using (MD5 md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
return md5.ComputeHash(stream);
}
}
}
private void textBox_path_TextChanged(object sender, TextChangedEventArgs e)
{
if (button_doit != null)
{
if (textBox_path.Text == "")
{
button_doit.IsEnabled = false;
}
else
{
button_doit.IsEnabled = true;
}
}
}
}
}

Save a copy of the file to specific folder, from a LinkLabel Hyperlink

I have a program that creates a list of hyperlinks to the files i search for. I can click the resulting hyperlink and the PDF opens. I would like to also have it make a copy of the pdf on my C: also without dialog. The source of the files is from the network. FileSearchButton_Click will search a directory for files with the content that match my search string.
aLinkLabel_LinkClicked is where I feel the copy action should be done
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FindFilesBasedOnText
{
public partial class FileSearcherBasedOnSpecificText : Form
{
SmartTextBox DirectoryTextBox = new SmartTextBox();
SmartTextBox SearchTextBox = new SmartTextBox();
SmartButton SearchButton = new SmartButton();
SmartButton FileSearchButton = new SmartButton();
public FileSearcherBasedOnSpecificText()
{
InitializeComponent();
DirectoryTextBox.Location = new Point(70, 12);
DirectoryTextBox.ForeColor = Color.Black;
DirectoryTextBox.ForeColor = Color.Black;
this.Controls.Add(DirectoryTextBox);
SearchTextBox.Location = new Point(70, 43);
//SearchTextBox.Size = new Size(478, 20);
this.Controls.Add(SearchTextBox);
SearchButton.Location = new Point(526, 12);
SearchButton.Size = new Size(160, 23);
SearchButton.Text = "Search Directory";
SearchButton.TabStop = false;
SearchButton.Click += SearchButton_Click;
this.Controls.Add(SearchButton);
FileSearchButton.Location = new Point(526, 43);
FileSearchButton.Size = new Size(160, 23);
FileSearchButton.Text = "Search file based-on text";
FileSearchButton.TabStop = false;
FileSearchButton.Click += FileSearchButton_Click;
this.Controls.Add(FileSearchButton);
listBox1.AllowDrop = true;
listBox1.DragDrop += listBox1_DragDrop;
listBox1.DragEnter += listBox1_DragEnter;
listBox1.Focus();
}
private void listBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
private void listBox1_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
listBox1.Items.AddRange(File.ReadAllLines(file));
}
private void SearchButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
DialogResult dialogReasult = folderBrowserDialog.ShowDialog();
if(!string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath))
{
DirectoryTextBox.Text = folderBrowserDialog.SelectedPath;
}
}
public void FileSearchButton_Click(object sender, EventArgs e)
{
FilesPanel.Controls.Clear();
int i = 0;
int y = 5;
string filesName = string.Empty;
string rootfolder = DirectoryTextBox.Text.Trim();
string[] files = Directory.GetFiles(rootfolder, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
try
{
string contents = File.ReadAllText(file);
if(contents.Contains(SearchTextBox.Text.Trim()))
{
i += 1;
LinkLabel aLinkLabel = new LinkLabel();
aLinkLabel.Text = file;
aLinkLabel.Location = new Point(5, y);
aLinkLabel.AutoSize = true;
aLinkLabel.BorderStyle = BorderStyle.None;
aLinkLabel.LinkBehavior = LinkBehavior.NeverUnderline;
aLinkLabel.ActiveLinkColor = Color.White;
aLinkLabel.LinkColor = Color.White;
aLinkLabel.BackColor = Color.Transparent;
aLinkLabel.VisitedLinkColor = Color.Red;
aLinkLabel.Links.Add(0, file.ToString().Length, file);
aLinkLabel.LinkClicked += aLinkLabel_LinkClicked;
FilesPanel.Controls.Add(aLinkLabel);
y += aLinkLabel.Height + 5;
}
else
{ // This shows DONE after each Search
LinkLabel aLinkLabel = new LinkLabel();
aLinkLabel.Font = new Font("", 12);
aLinkLabel.ActiveLinkColor = Color.White;
aLinkLabel.LinkColor = Color.White;
aLinkLabel.BackColor = Color.Transparent;
aLinkLabel.Text = "DONE";
FilesPanel.Controls.Add(aLinkLabel);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
void aLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
LinkLabel lnk = new LinkLabel();
lnk = (LinkLabel)sender;
lnk.Links[lnk.Links.IndexOf(e.Link)].Visited = true;
System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
//Create a directory if not exist for the file to be copied into
if (!System.IO.Directory.Exists(#"C:\Temp\RoHS_Docs"))
{
System.IO.Directory.CreateDirectory(#"C:\Temp\RoHS_Docs");
}
//Perform the file copy action on click
string CopyDestinationPath = #"C:\Temp\RoHS_Docs\";
System.IO.File.Copy(WHAT????, CopyDestinationPath, true);
}
private void FileSearcherBasedOnSpecificText_Load(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
FilesPanel.Controls.Clear();
}
private void label3_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SearchTextBox.Text = listBox1.SelectedItem.ToString();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
}
}

Multiple errors while trying to download with C#

Introduction:
Hello, I tried doing a program with a WinForms Application that downloads specific .zip files, but I get these errors:
UI look like
Errors what I get
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.IO;
using System.Collections;
using System.Net;
using System.Threading;
namespace Universal_Installer
{
public partial class Form1 : Form
{
WebClient wc;
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog def = new FolderBrowserDialog();
def.RootFolder = Environment.SpecialFolder.Desktop;
def.Description = "Select installation location...";
def.ShowNewFolderButton = true;
if (def.ShowDialog() == DialogResult.OK)
{
textBox1.Text = def.SelectedPath;
}
}
private void Button2_Click(object sender, EventArgs e)
{
if (!Directory.Exists(textBox1.Text))
{
MessageBox.Show("The selected path does not exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (Directory.Exists(textBox1.Text))
{
string inst_size = "n/a";
string name = "n/a";
bool able = false;
string downloadlink = "n/a";
string PeoplePlaygroundSize = "0.161";
string PrisonArchitectSize = "0.586";
string AnotherBrickInTheMallSize = "0.164";
if (PP.Checked == true)
{
inst_size = PeoplePlaygroundSize;
downloadlink = "(A download link)";
name = "People Playground.zip";
able = true;
}
else if (PA.Checked == true)
{
inst_size = PrisonArchitectSize;
downloadlink = "(A download link)";
name = "Prison Architect.zip";
able = true;
}
else if (ABITM.Checked == true)
{
inst_size = AnotherBrickInTheMallSize;
downloadlink = "(A download link)";
name = "Another Brick In The Mall.zip";
able = true;
}
if (able == false)
{
MessageBox.Show("No checkboxes are checked!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (MessageBox.Show("Are you sure you want to install a " + inst_size + " GB game?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
status.Text = "Status: DOWNLOADING (" + inst_size + " GB)";
//////
ABITM.Enabled = false;
PP.Enabled = false;
PA.Enabled = false;
textBox1.Enabled = false;
button1.Enabled = false;
button2.Enabled = false;
//////
Thread thread = new Thread(() =>
{
Uri uri = new Uri(downloadlink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
wc.DownloadFileAsync(uri, textBox1.Text + "/" + filename);
});
thread.Start();
}
}
}
private void FileDownloadComplete(object sender,AsyncCompletedEventArgs e)
{
status.Text = "Status: IDLE";
PBAR.Value = 0;
MessageBox.Show("Download Completed (PATH: "+textBox1.Text+")", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information);
ABITM.Enabled = true;
PP.Enabled = true;
PA.Enabled = true;
textBox1.Enabled = true;
button1.Enabled = true;
button2.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
wc = new WebClient();
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileCompleted += FileDownloadComplete;
}
private void wc_DownloadProgressChanged(object sender, AsyncCompletedEventArgs e)
{
Invoke(new MethodInvoker(delegate ()
{
PBAR.Minimum = 0;
double recive = double.Parse(e.BytesReceived.ToString());
double total = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = recive / total * 100;
PBAR.Value = int.Parse(Math.Truncate(percentage).ToString());
}));
}
}
}
Help:
Any help? By the way, if you see any text ending with .Text or .Value etc... these mean they are objects.
I really need your help by the way...
According the Official Documentation, the second argument for the DownloadProgressChanged must be DownloadProgressChangedEventArgs instead of AsyncCompletedEventArgs.
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Invoke(new MethodInvoker(delegate ()
{
PBAR.Minimum = 0;
double recive = double.Parse(e.BytesReceived.ToString());
double total = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = recive / total * 100;
PBAR.Value = int.Parse(Math.Truncate(percentage).ToString());
}));
}

How to move a function to a separate assembly from the interface [Error]

I am currently working on a file copying facility that allows me to select a source and a destination for the folders to be copied from and to. A progress bar is displayed after the user clicks on Copy.
The only issue is that All of my functions reside in one file which is form1.cs (as follows)
namespace CopyFacility
{
public partial class Form1 : Form
{
BackgroundWorker background = new BackgroundWorker();
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
OpenFileDialog openFile = new OpenFileDialog();
public Form1()
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
string inputFile = null;
string outputFile = null;
private void CopyFile(string source, string destination, DoWorkEventArgs e)
{
FileStream fsOut = new FileStream(destination, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] buffer = new byte[1048756];
int readBytes;
while((readBytes = fsIn.Read(buffer,0,buffer.Length)) > 0)
{
if(background.CancellationPending)
{
e.Cancel = true;
background.ReportProgress(0);
fsIn.Close();
fsOut.Close();
return;
}
else
{
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int) (fsIn.Position * 100 / fsIn.Length));
}
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int)(fsIn.Position * 100 / fsIn.Length));
}
fsIn.Close();
fsOut.Close();
}
private void Background_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
fileProgressBar.Value = e.ProgressPercentage;
}
private void Background_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been cancelled";
}
else
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been completed";
}
}
private void Background_DoWork(object sender, DoWorkEventArgs e)
{
CopyFile(inputFile, outputFile + #"\" + Path.GetFileName(inputFile),e);
}
private void btnCancel_Click(object sender, EventArgs e)
{
background.CancelAsync();
}
private void btnCopy_Click(object sender, EventArgs e)
{
if(background.IsBusy)
{
lblProgress.Visible = true;
}
else
{
fileProgressBar.Visible = true;
background.RunWorkerAsync();
}
}
private void btnSource_Click(object sender, EventArgs e)
{
if(openFile.ShowDialog() == DialogResult.OK )
{
inputFile = openFile.FileName;
btnSource.Text = inputFile;
}
}
private void btnDestination_Click(object sender, EventArgs e)
{
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
outputFile = folderBrowser.SelectedPath;
btnDestination.Text = outputFile + #"\" + Path.GetFileName(inputFile);
}
}
}
}
I was wondering how I could go about putting the function "CopyFile" into it's own class that can be called whenever the button is clicked?
When I try creating a new class method and inserting the functions related to the copying function into a new class "CopyFunction.cs" , I get a following error from the code "InitializingComponent();" as follows
public CopyPresenter(BackgroundWorker background, FolderBrowserDialog folderBrwoser, OpenFileDialog openFile)
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
The error says that the "InitializeComponent" doesn't exist in the current context.

Sending custom commands to a service using windows form

I am trying to send custom commands to a service using a windows form. The command I am trying to send is trying to place a file in Isolated Storage. Below is my source code.
Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Project2Service;
namespace Project2
{
public partial class Form1 : Form
{
public Service1 s = new Service1();
public ServiceInstaller si = new ServiceInstaller();
public ProjectInstaller pi = new ProjectInstaller();
public ServiceController sc = new ServiceController("Project2Service");
private string[] isoType;
string machineName = System.Windows.Forms.SystemInformation.ComputerName;
public Form1()
{
InitializeComponent();
isoType = new string[] { "User", "Assembly And Domain"};
cboIsoType.Items.AddRange(isoType);
cboIsoType.SelectedIndex = 0;
btnContinue.Enabled = false;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
public void Labels()
{
lblMachine.Text = machineName;
lblSName.Text = s.ServiceName;
lblSType.Text = si.StartType.ToString();
lblSStatus.Text = sc.Status.ToString();
lblPause.Text = sc.CanPauseAndContinue.ToString();
lblShutdown.Text = sc.CanShutdown.ToString();
lblStop.Text = sc.CanStop.ToString();
}
private void btnStart_Click(object sender, EventArgs e)
{
//Controller.Refresh(); //Gets the current status of service
//if (Controller.Status == ServiceControllerStatus.Stopped)
//{
// Controller.Start();
//}
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
Labels();
btnStart.Enabled = false;
btnContinue.Enabled = false;
btnStop.Enabled = true;
btnPause.Enabled = true;
}
private void btnStop_Click(object sender, EventArgs e)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
Labels();
btnStart.Enabled = true;
btnContinue.Enabled = false;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
private void btnPause_Click(object sender, EventArgs e)
{
sc.Pause();
sc.WaitForStatus(ServiceControllerStatus.Paused);
Labels();
btnPause.Enabled = false;
btnContinue.Enabled = true;
btnStart.Enabled = false;
btnStop.Enabled = true;
}
private void btnContinue_Click(object sender, EventArgs e)
{
sc.Continue();
sc.WaitForStatus(ServiceControllerStatus.Running);
Labels();
btnStop.Enabled = true;
btnStart.Enabled = false;
btnPause.Enabled = true;
btnContinue.Enabled = false;
}
private void btnSubmit_Click(object sender, EventArgs e)
{
if (cboIsoType.SelectedItem.ToString() == "User")
{
sc.ExecuteCommand(128);
}
}
}
}
Service
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Project2Service
{
public partial class Service1 : ServiceBase
{
public enum ServiceCustomCommands { Command1 = 128, Command2 = 129 };
//private IsolatedStorageScope iso;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Domain;
FileSystemWatcher Watcher = new FileSystemWatcher(#"C:\Users\Martin\Desktop\Project2\ServiceTest");
Watcher.EnableRaisingEvents = true;
Watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
Watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
WriteServiceInfo("Service Started!");
}
// This event is raised when a file is changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Changed!");
DirectoryInfo d = new DirectoryInfo(#"C:\Users\Martin\Desktop\Project2\ServiceTest");//Assuming Watch is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
str = str + ", " + file.LastWriteTime;
str = str + ", " + file.CreationTime;
str = str + ", " + file.Length;
WriteServiceInfo(file.Name);
WriteServiceInfo(file.LastWriteTime.ToString());
WriteServiceInfo(file.CreationTime.ToString());
WriteServiceInfo(file.Length.ToString());
}
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Created!");
}
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Deleted!");
}
private void Watcher_Renamed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Renamed!");
}
private void WriteServiceInfo(string info)
{
FileStream fs = new FileStream(#"C:\Users\Martin\Desktop\Project2\WindowsServiceLog.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(info + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{
WriteServiceInfo("Service Stopped!");
}
protected override void OnCustomCommand(int command)
{
switch ((ServiceCustomCommands)command)
{
case ServiceCustomCommands.Command1:
//Command1 Implementation
IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt", FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
//iso = IsolatedStorageScope.User;
break;
case ServiceCustomCommands.Command2:
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
break;
default:
break;
}
}
}
}
sc.ExecuteCommand(128); in the submit button method does not seem to fire.
This worked just fine for me so I surmise its your code not hitting the call to execute the command. I took your code, made it a bit easier.
For example - stripping out all the stuff above - this code below worked and the text file appeared with the "Command Received" in it.
In your case it could be that you aren't closing the file. Try this:
using (
IsolatedStorageFile isoFile =
IsolatedStorageFile.GetStore(
IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly,
null, null))
{
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt",
FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
WriteServiceInfo("data written to isolated storage");
isoFile.Close();
}
I changed the submit button to simply send the command, I'd suggest the same
private void btnSubmit_Click(object sender, EventArgs e)
{
sc.ExecuteCommand(128);
}
Service code is as follows
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Project2Service
{
public partial class Service1 : ServiceBase
{
public enum ServiceCustomCommands { Command1 = 128, Command2 = 129 };
//private IsolatedStorageScope iso;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WriteServiceInfo("Service Started!");
}
// This event is raised when a file is changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Changed!");
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Created!");
}
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Deleted!");
}
private void Watcher_Renamed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Renamed!");
}
private void WriteServiceInfo(string info)
{
FileStream fs = new FileStream(#"C:\Users\Adam\Desktop\WindowsServiceLog.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(info + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{
WriteServiceInfo("Service Stopped!");
}
protected override void OnCustomCommand(int command)
{
WriteServiceInfo("Command received");
switch ((ServiceCustomCommands)command)
{
case ServiceCustomCommands.Command1:
//Command1 Implementation
IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt", FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
//iso = IsolatedStorageScope.User;
break;
case ServiceCustomCommands.Command2:
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
break;
default:
break;
}
}
}
}

Categories