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;
}
}
}
}
Related
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;
}
}
}
}
}
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);
I want to develop a client-server application. I started the project but I encountered the some problems. When I want to connect to server with one client, everything is done. Program is working. But when I want to connect with two or three etc. PC to server, clients of them is working but others is not working. How can I fix this problem?
Here is the 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;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Timers;
using ClientServer;
namespace ClientServer
{
public partial class Form1 : Form
{
private TcpClient Client;
private StreamReader STR;
public StreamWriter STW;
public string receive;
public string text_to_send;
//int zaman;
public Form1()
{
InitializeComponent();
- Client = new TcpClient();
Control.CheckForIllegalCrossThreadCalls = false; //cross threading problem
IPAddress[] LocalIP = Dns.GetHostAddresses(Dns.GetHostName()); // my IP Adress
foreach (IPAddress adress in LocalIP)
{
if(adress.AddressFamily== AddressFamily.InterNetwork)
{
textBox3.Text = adress.ToString();
}
}
}
private void button2_Click(object sender, EventArgs e) //Start server
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
listener.Start();
Client = listener.AcceptTcpClient();
STR = new StreamReader(Client.GetStream());
STW = new StreamWriter(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //receive data background
backgroundWorker2.WorkerSupportsCancellation = true; //ability cancel this thread
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receive data
{
while(Client.Connected)
{
try
{
receive = STR.ReadLine();
if(receive=="soru1")
{
label7.Text = "Merhaba bu bir denemedir :)";
//zaman = 45;
timer1.Enabled = true;
}
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Sen:" + receive + "\n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //veri gönder
{
if(Client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ben:" + text_to_send + "\n"); }));
}
else
{
MessageBox.Show("Gönderim başarısız!");
}
backgroundWorker2.CancelAsync();
}
private void button3_Click(object sender, EventArgs e) //Connect Server
{
Client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));
try
{
Client.Connect(IP_End);
if(Client.Connected)
{
textBox2.AppendText("Server'a bağlantı sağlandı" + "\n");
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //receive data in background
backgroundWorker2.WorkerSupportsCancellation = true; //
}
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
private void button1_Click(object sender, EventArgs e) //Send Button
{
if(textBox1.Text != "")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
//private void timer1_Tick(object sender, System.EventArgs e) //
//{
// zaman--; //timer her saniyede sayıyı 1 azaltacak
// label9.Text = zaman.ToString();
// if (zaman == 0)
// {
// timer1.Enabled = false;
// }
//}
}
}
Here a good links:
http://www.mikeadev.net/2012/07/multi-threaded-tcp-server-in-csharp/
https://www.codeproject.com/Articles/511814/Multi-client-per-one-server-socket-programming-in
tcpListener.Start();
Console.WriteLine("************This is Server program************");
Console.WriteLine("Hoe many clients are going to connect to this server?:");
int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());
for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}
The invocation of the constructor on type 'WpfApplication1.MainWindow'
that matches the specified binding constraints threw an exception.'
Line number '4' and line position '9'.
That was the error I'm facing while changing my target platform from 'x86' to 'Any CPU' in order to run my executable to run in x86 and x64 bit windows operating systems.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 WebKit;
using WebKit.Interop;
using Twitterizer;
using Facebook;
using TwitterConnect;
using facebook;
namespace WpfApplication3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
WebKitBrowser wb = new WebKitBrowser();
TwitterConnect.TwitterStuff ts = new TwitterStuff();
Browser b = new Browser();
OpenWebkitBrowser.facebook fb_1 = new OpenWebkitBrowser.facebook();
private void Possibillion_Loaded(object sender, RoutedEventArgs e)
{
System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();
host.Child = wb;
this.Grid2.Children.Add(host);
wb.DocumentCompleted += wb_DocumentCompleted;
}
void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
textBox1.Text = wb.Url.ToString();
TabItem1.Header = wb.DocumentTitle;
}
private void btnMinimize_Click(object sender, RoutedEventArgs e)
{
Possibillion.WindowState = WindowState.Minimized;
}
private void btnMaximize_Click(object sender, RoutedEventArgs e)
{
if (Possibillion.WindowState == WindowState.Maximized)
Possibillion.WindowState = WindowState.Normal;
else
Possibillion.WindowState = WindowState.Maximized;
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
Possibillion.Close();
}
private void btnGo_Click(object sender, RoutedEventArgs e)
{
wb.Navigate("http://" + textBox1.Text);
}
private void btnTwitter_Click(object sender, RoutedEventArgs e)
{
bool loggedIn = b.AlreadyLoggedIn();
if (!loggedIn)
{
//this.Hide();
b.Show();
}
//else
//{
// MainWindow mw = new MainWindow();
// mw.Show();
// this.Close();
//}
else if (textBox1.Text != "")
{
ts.tweetIt(wb.DocumentTitle);
//textBox1.Clear();
}
}
private void btnfacebook_Click_1(object sender, RoutedEventArgs e)
{
if (val.login == true)
{
//fb_1.Show();
if (string.IsNullOrEmpty(textBox1.Text))
{
Dispatcher.Invoke(new Action(() => { System.Windows.MessageBox.Show("Enter message."); }));
return;
}
var fb = new FacebookClient(val.token);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
Dispatcher.Invoke(new Action(() => { System.Windows.MessageBox.Show(args.Error.Message); }));
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
//_lastMessageId = (string)result["id"];
Dispatcher.Invoke(new Action(() =>
{
System.Windows.MessageBox.Show("Message Posted successfully");
textBox1.Text = string.Empty;
// pho.IsEnabled = true;
}));
};
var fbimg = new Facebook.FacebookMediaObject
{
FileName = Guid.NewGuid() + ".jpg",
ContentType = "image/png"
};
// FileStream fs = new FileStream("Rose.png", FileMode.Open, FileAccess.Read);
// BinaryReader br = new BinaryReader(fs);
// byte[] res = br.ReadBytes((int)fs.Length);
// br.Close();
// fs.Close();
//fbimg.SetValue(res);
// Uri uri = new Uri("/Background.png",UriKind.Relative);
var parameters = new Dictionary<string, object>();
//parameters.Add("picture", fbimg);
//parameters.Add("message", "hi");
// parameters["picture"] ="https://twimg0-a.akamaihd.net/profile_images/2263781693/SAchin_reasonably_small.png";
parameters["message"] = textBox1.Text;
// parameters["picture"] =fbimg;
//fb.PostAsync(#"/photos", parameters);
fb.PostAsync("me/feed", parameters);
}
else
{
Dispatcher.Invoke(new Action(() => { fb_1.ShowDialog(); }));
//System.Windows.MessageBox.Show("message not sent");
}
}
private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
wb.Navigate("http://" + textBox1.Text);
}
}
}
Make sure your target platform matches your build settings.
If you have changed your configuration manager to any CPU, then in the project properties under build you will need to do the same.
Edit - Ah seems like your trying to run a toolkit that is build for x86 in a x64 world.
I'm having some trouble, somehow I get a "not allowed exception" and I can't seem to figure out what is wrong I know the answer is simple but I really can't spot what's wrong with my code...
it happens when I try to write something to the newly created file and I could imagine that it also will when it tries to read the file... any information would be acknowledged...
thx in advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; // ny
using System.Net;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Shell;
using System.IO; // ny
using System.IO.IsolatedStorage; // ny
namespace SmartSence
{
public partial class MainPage : PhoneApplicationPage
{
private static UTF8Encoding enc = new UTF8Encoding();
// Constructor
public MainPage()
{
InitializeComponent();
if (CreateStore().FileExists("Userdata\\Userdata.txt"))
{
mail.Text = ReadFile(CreateStore());
}
}
private void minknap_Click(object sender, RoutedEventArgs e)
{
string newusername;
newusername = Username.Text;
mytext1.Text = newusername;
string igen;
igen = "&password=";
string newpassword;
newpassword = mypassword.Password;
mypasswordblock.Text = newpassword;
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://www.smartsence.dk/winindexcheck.php?id=" + mytext1.Text + igen + mypasswordblock.Text, UriKind.Absolute);
webBrowserTask.Show();
}
private void signin_Click(object sender, RoutedEventArgs e)
{
string signin;
signin = mail.Text;
signintext.Text = signin;
string igen;
igen = "&password=";
string newpassword;
newpassword = mail.Text;
signintext.Text = newpassword;
if (!CreateStore().DirectoryExists("Userdata"))
{
CreateStore().CreateDirectory("Userdata");
if (!CreateStore().FileExists("Userdata\\data.txt"))
{
CreateStore().CreateFile("Userdata\\data.txt");
}
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("Userdata\\Userdata.txt", FileMode.Create, CreateStore());
WriteToFile(CreateStore(), signin);
}
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://www.smartsence.dk/winindexcheck.php?id=" + signintext.Text + igen + signintext.Text, UriKind.Absolute);
webBrowserTask.Show();
}
private void minknap2_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Info.xaml", UriKind.Relative));
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
private void info_Click(object sender, EventArgs e)
{
MessageBox.Show("SmartSence App 4.0 - Is free to use, it´s has never been easier to navigate around the web. Buy the app and get free VIP status forever - Please support us :) ");
}
private void VIP_Click(object sender, EventArgs e)
{
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://www.smartsence.dk/winindexappvipcheck2.php", UriKind.Absolute);
webBrowserTask.Show();
}
private void image1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
}
#region NewMethods
private IsolatedStorageFile CreateStore()
{
IsolatedStorageFile lager = IsolatedStorageFile.GetUserStoreForApplication();
return lager;
}
private void WriteToFile(IsolatedStorageFile storeFile, string content)
{
IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Write); // Exception: not allowed on IsolatedStorageFile
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.WriteLine(content);
}
}
private string ReadFile(IsolatedStorageFile storeFile)
{
IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
return reader.ReadLine().Trim();
}
}
private void mail_Tap(object sender, GestureEventArgs e)
{
mail.Text = string.Empty;
}
#endregion
}
}
I think the issue is that you're not closing your IsolatedStorageFileStream, so the file is still open, and hence cannot be written, therefore throwing this exception. You should make sure to wrap your reads & writes in a using, or calling Dispose yourself.
public MainPage()
{
InitializeComponent();
if (CreateStore().FileExists("Userdata\\Userdata.txt"))
{
mail.Text = ReadFile(CreateStore()); //opens file and never closes it.
}
}
To fix this, you should use using statements.
private void WriteToFile(IsolatedStorageFile storeFile, string content)
{
using (IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Write){ // Exception: not allowed on IsolatedStorageFile
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.WriteLine(content);
}
}
}
private string ReadFile(IsolatedStorageFile storeFile)
{
using(IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Read){
using (StreamReader reader = new StreamReader(fileStream))
{
return reader.ReadLine().Trim();
}
}
}