Unable to use NDde.dll in windows service - c#

C# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using NDde.Client;
namespace Test
{
public partial class Service1 : ServiceBase
{
System.Timers.Timer timeDelay;
int count;
public Service1()
{
InitializeComponent();
timeDelay = new System.Timers.Timer();
timeDelay.Elapsed += new System.Timers.ElapsedEventHandler(WorkProcess);
}
public void WorkProcess(object sender, System.Timers.ElapsedEventArgs e)
{
string process = "Timer Tick " + count;
LogService(process);
count++;
}
protected override void OnStart(string[] args)
{
LogService("Service is Started");
timeDelay.Enabled = true;
}
protected override void OnStop()
{
LogService("Service Stoped");
timeDelay.Enabled = false;
}
private void LogService(string content)
{
FileStream fs = new FileStream(#"C:\TestServiceLog.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(content+this.GetFirefoxUrl());
sw.Flush();
sw.Close();
}
public string GetFirefoxUrl()
{
DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo");
dde.Connect();
string url = dde.Request("URL", int.MaxValue);
dde.Disconnect();
return url;
}
}
}
Hi, I have written the above code but I am unable to perform the task GetFirefoxUrl(). Its giving me the following error. How can I resolve this?
Service cannot be started. NDde.DdeException: The client failed to connect to "Firefox|WWW_GetWindowInfo". Make sure the server application is running and that it supports the specified service name and topic name pair. ---> NDde.Foundation.DdemlException: The client failed to connect to "Firefox|WWW_GetWindowInfo". Make sure the server application is running and that it supports the specified service name and topic name pair.
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at NDde.Advanced.DdeContext.DdeThread.Invoke(Delegate method, Object[] args)
at NDde.Client.DdeClient.Connect()
--- End of inner exception stack trace ---
at NDde.Client.DdeClient.Connect()
at Test.Service1.GetFirefoxUrl()
at Test.Service1.LogService(String content)
at Test.Service1.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
I have checked the other threads related to this none of them gave me a solution. I hope some one guide me to achieve this.

Related

CanStop = false, but I can't start the service

I am making a service to put on my kid's computer, to make sure that they can't stop Qustodio, and they are quite tech-savvy. They know how to stop a service by going to Run >> services.msc, and I need to make the service NOT_STOPPABLE, like Kaspersky. But when I add the line: CanStop = false;, I can't start the service and it gives me an error. This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace MyFirstService
{
public partial class Service1 : ServiceBase
{
Timer timer = new Timer();
ServiceController qengine = new ServiceController("qengine");
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 5000; //number in milisecinds
timer.Enabled = true;
CanStop = false;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
qengine.Start();
WriteToFile("qengine attemped start at: " + DateTime.Now);
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}

Database insert on FileSystemEventHandler with Windows Service

I have managed to get the Service working, along with the FileSystemEventHandler inserting into a text file, but this now needs to be changed to insert into a database and a text file.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace WindowsServiceTest
{
public partial class Service1 : ServiceBase
{
Timer timer = new Timer(); // name space(using System.Timers;)
public static string path = ConfigurationManager.AppSettings["findpath"];
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 10000; //number in milisecinds
timer.Enabled = true;
FileSystemWatcher watcher = new FileSystemWatcher
{
Path = path,
NotifyFilter = NotifyFilters.LastWrite,
};
watcher.Created += new FileSystemEventHandler(FileSystemWatcher_Changed);
watcher.Renamed += new RenamedEventHandler(FileSystemWatcher_Renamed);
watcher.Changed += new FileSystemEventHandler(FileSystemWatcher_Changed);
watcher.EnableRaisingEvents = true;
}
public static void FileSystemWatcher_Changed(object source, FileSystemEventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Database=ServiceTest;Integrated Security=True;"))
{
try
{
con.Open();
var command = new SqlCommand("Insert into test(URL, Location) values(#URL, #agendaname);", con);
command.Parameters.Add("#URL", System.Data.SqlDbType.VarChar, 100).Value = e.Name;
command.Parameters.Add("#agendaname", System.Data.SqlDbType.VarChar, 100).Value = "Case History";
command.ExecuteNonQuery();
}
catch
{
WriteToFile($"Failed to insert: {e.Name} into the database");
}
}
}
public static void FileSystemWatcher_Renamed(object source, RenamedEventArgs e)
{
WriteToFile($"File Renamed: {e.OldFullPath} renamed to {e.FullPath}");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
WriteToFile("Service is recalled at " + DateTime.Now);
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
public static void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}
I think that I've done the database insert wrong because the catch block is being inserted into the text file. However, I've run the code by itself in a separate project and was inserting into the database in a Console Application.
Any help is appreciated, kind regards.
Windows services run under a different security context than console apps. As the comments have disclosed, the exception is related to your connection string.
If we analyze the connectiong string we can see that you are authenticating with IntegratedSecurity="True". Because your windows service is running under
a service account authentication is failing. I've specified 2 options for resolving this.
Option 1: Have Service run as windows account (Not recommended but will work for testing)
Open run box (Win Flag + R)
Type Services.MSC
Locate your service and right click properties
Choose the logon tab
Enter your windows auth username and password for service to run as
Option 2: Create SQL Server account
Create username and password in SQL for database
Update connection string to specify new username and password created

Send Print job from PuTTY to Zebra ZXP 3 SDK (non.zpl printer)

What I have is a medical record database that is accessed via PuTTY (SSH client). The cards themselves will only have Client name, record number in a barcode format (still determining the barcode type to be used), and client registration date.
1) We can get the data output as .zpl for Zebra Barcode label printers or formats compatible with laser printers like HP or Brother in a RAW format.
2) What output WILL the ZXP 3 SDK accept?
3) Can the SDK be set up to wait for and accept data coming at it using a command line from something like RedMon?
The cards themselves will only have the printed data, no mag stripe, smart chips, laminates or anything like that.
Mahalo in advance.
I would not recommend using either RedMon nor the SDK, as neither are required for what you are trying to do, and they both are time-vampires. Instead, I would write a small Windows Forms application which listens on a TCP port to receive the print job and send it to the standard printer which uses the Zebra driver.
Have the MUMPS application send an XML document via the Remote Print support in VT100. The example I have been using is below:
^[[5i
<patient>
<name first="John" last="Smith" />
<mrn>A04390503</mrn>
<dob>1991-03-12</dob>
</patient>
^[[4i
Configure a printer on the windows client to redirect to TCP/IP:
Add Printer
Local printer
Create a new port
Standard TCP/IP Port
Hostname: 127.0.0.1
Port name: CardFormatter
Uncheck "Query the printer and automatically select the driver to use"
Device type: Custom
Protocol: Raw
Port: 9101
Driver: Generic / Text Only
Start the application at logon, and print from the server. The MUMPS application will send back the XML, which Putty prints to the Text printer, which gets sent to the C# application on localhost. The C# application interprets the XML and prints to the actual printer via the Zebra driver or SDK.
Note: This only assumes one interactive session per workstation. If you are using fast-user-switching or terminal services, further care must be taken to ensure things work properly.
Example App:
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PassThroughPrinterTest
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TrayApplicationContext());
}
}
}
TrayApplicationContext.cs
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PassThroughPrinterTest
{
class TrayApplicationContext : ApplicationContext
{
private NotifyIcon trayIcon;
private PrintListener listener;
private PrintHandler handler;
public TrayApplicationContext()
{
this.trayIcon = new NotifyIcon()
{
Text = "Card Formatter",
Icon = Properties.Resources.AppIcon,
ContextMenu = new ContextMenu()
{
MenuItems =
{
new MenuItem("Print Options...", miPrintOptions_Click),
new MenuItem("Exit", miExit_Click)
}
},
Visible = true
};
this.handler = new PrintHandler();
this.listener = new PrintListener(9101);
this.listener.PrintDataReceived += this.handler.HandlePrintData;
}
private void miPrintOptions_Click(object sender, EventArgs args)
{
// TODO: add configuration and options to avoid having to hard code
// the printer name in PrintHandler.cs
MessageBox.Show("Options");
}
private void miExit_Click(object sender, EventArgs args)
{
Application.Exit();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
trayIcon.Dispose();
}
}
}
}
PrintHandler.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
namespace PassThroughPrinterTest
{
partial class PrintHandler : Form
{
public PrintHandler()
{
InitializeComponent();
}
public void HandlePrintData(object sender, PrintDataReceivedEventArgs args)
{
if (this.InvokeRequired)
{
this.Invoke(new EventHandler<PrintDataReceivedEventArgs>(HandlePrintData), sender, args);
return;
}
this.Show();
var sXml = Encoding.UTF8.GetString(args.PrintData);
this.PrintCard(XDocument.Parse(sXml));
this.Hide();
}
private void PrintCard(XDocument xDocument)
{
var nameElement = xDocument.Root.Element("name");
var lastName = nameElement.Attribute("last").Value;
var firstName = nameElement.Attribute("first").Value;
var mrn = xDocument.Root.Element("mrn").Value;
var printDoc = new PrintDocument()
{
PrinterSettings = new PrinterSettings()
{
PrinterName = "Adobe PDF"
},
DocumentName = "Patient ID Card"
};
var cardPaperSize = new PaperSize("Card", 337, 213) { RawKind = (int)PaperKind.Custom };
printDoc.DefaultPageSettings.PaperSize = cardPaperSize;
printDoc.PrinterSettings.DefaultPageSettings.PaperSize = cardPaperSize;
printDoc.PrintPage += (s, e) =>
{
var gfx = e.Graphics;
// print the text information
var fArial12 = new Font("Arial", 12);
gfx.DrawString(lastName, fArial12, Brushes.Black, new RectangleF(25, 25, 200, 75));
gfx.DrawString(firstName, fArial12, Brushes.Black, new RectangleF(25, 100, 200, 75));
// add a code39 barcode using a barcode font
// http://www.idautomation.com/free-barcode-products/code39-font/
// var fCode39 = new Font("IDAutomationHC39M", 12);
// gfx.DrawString("(" + mrn + ")", fArial12, Brushes.Black, new RectangleF(25, 200, 200, 75));
// or by using a barcode library
// https://barcoderender.codeplex.com/
// var barcode = BarcodeDrawFactory.Code128WithChecksum.Draw(mrn, 20, 2);
// gfx.DrawImage(barcode, 50, 200);
e.HasMorePages = false;
};
printDoc.Print();
}
}
}
PrintListener.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace PassThroughPrinterTest
{
sealed class PrintListener : IDisposable
{
private TcpListener listener;
public event EventHandler<PrintDataReceivedEventArgs> PrintDataReceived;
public PrintListener(int port)
{
this.listener = new TcpListener(IPAddress.Loopback, port);
this.listener.Start();
this.listener.BeginAcceptTcpClient(listener_AcceptClient, null);
}
public void Dispose()
{
this.listener.Stop();
}
private void listener_AcceptClient(IAsyncResult iar)
{
TcpClient client = null;
bool isStopped = false;
try
{
client = this.listener.EndAcceptTcpClient(iar);
}
catch (ObjectDisposedException)
{
// this will occur in graceful shutdown
isStopped = true;
return;
}
finally
{
if (!isStopped)
{
this.listener.BeginAcceptTcpClient(listener_AcceptClient, null);
}
}
Debug.Assert(client != null);
try
{
byte[] printData;
using (var clientStream = client.GetStream())
using (var buffer = new MemoryStream())
{
clientStream.CopyTo(buffer);
printData = buffer.ToArray();
}
OnPrintDataReceived(printData);
}
catch
{
// TODO: add logging and error handling for network issues or processing issues
throw;
}
finally
{
client.Close();
}
}
private void OnPrintDataReceived(byte[] printData)
{
var handler = PrintDataReceived;
if (handler != null)
{
handler(this, new PrintDataReceivedEventArgs(printData));
}
}
}
}
TrayApplicationContext.cs
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PassThroughPrinterTest
{
class TrayApplicationContext : ApplicationContext
{
private NotifyIcon trayIcon;
private PrintListener listener;
private PrintHandler handler;
public TrayApplicationContext()
{
this.trayIcon = new NotifyIcon()
{
Text = "Card Formatter",
Icon = Properties.Resources.AppIcon,
ContextMenu = new ContextMenu()
{
MenuItems =
{
new MenuItem("Print Options...", miPrintOptions_Click),
new MenuItem("Exit", miExit_Click)
}
},
Visible = true
};
this.handler = new PrintHandler();
this.listener = new PrintListener(9101);
this.listener.PrintDataReceived += this.handler.HandlePrintData;
}
private void miPrintOptions_Click(object sender, EventArgs args)
{
// TODO: add configuration and options to avoid having to hard code
// the printer name in PrintHandler.cs
MessageBox.Show("Options");
}
private void miExit_Click(object sender, EventArgs args)
{
Application.Exit();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
listener.Dispose();
trayIcon.Dispose();
}
}
}
}
PrintDataReceivedEventArgs.cs
using System;
namespace PassThroughPrinterTest
{
class PrintDataReceivedEventArgs : EventArgs
{
public byte[] PrintData { get; set; }
public PrintDataReceivedEventArgs(byte[] data)
{
if (data == null)
throw new ArgumentNullException("data");
this.PrintData = data;
}
}
}

Get all IP adresses on LAN

I have a program that ping and take all the ip address that are active in a LAN i code it with csharp console mode the problem is that when I put it in mode form an error appear in Spinwatch and a error message box appear
Here is the code and error below
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.Net.NetworkInformation;
using System.Threading;
namespace pingagediffusiontest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{ }
private static List<Ping> pingers = new List<Ping>();
private static int instances = 0;
private static object #lock = new object();
private static int result = 0;
private static int timeOut = 250;
private static int ttl = 5;
static void Mains()
{
string baseIP = "192.168.1.";
Console.WriteLine("Pinging 255 destinations of D-class in {0}*", baseIP);
CreatePingers(255);
PingOptions po = new PingOptions(ttl, true);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] data= enc.GetBytes("abababababababababababababababab");
SpinWait wait = new SpinWait();
int cnt = 1;
Stopwatch watch = Stopwatch.StartNew();
foreach (Ping p in pingers) {
lock (#lock) {
instances += 1;
}
p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeOut, data, po);
cnt += 1;
}
while (instances > 0) {
wait.SpinOnce();
}
watch.Stop();
DestroyPingers();
Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result);
Console.ReadKey();
}
public static void Ping_completed(object s, PingCompletedEventArgs e)
{
lock (#lock) {
instances -= 1;
}
if (e.Reply.Status == IPStatus.Success) {
Console.WriteLine(string.Concat("Active IP: ", e.Reply.Address.ToString()));
result += 1;
} else {
Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString()))
}
}
private static void CreatePingers(int cnt)
{
for (int i = 1; i <= cnt; i++) {
Ping p = new Ping();
p.PingCompleted += Ping_completed;
pingers.Add(p);
}
}
private static void DestroyPingers()
{
foreach (Ping p in pingers) {
p.PingCompleted -= Ping_completed;
p.Dispose();
}
pingers.Clear();
}
}
}
Error 1 The type or namespace name 'SpinWait' could not be found
Error 3 The type or namespace name 'Stopwatch' could not be found
Error 4 The name 'Stopwatch' does not exist in the current context
Just add the
using System.Diagnostics;
At the top of your file.
Error 3 The type or namespace name 'Stopwatch' could not be found
You need to import following namespace to use StopWatch in your program:
using System.Diagnostics;
as suggested by #CodeCaster in comments - you are missing semicolon to terminate the Console.WriteLine() statement :
Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString())) //missing semicolon
Suggestion : as you have stated you converted code from Console Application to Windows Forms Application it would be nice if you can change/replace all Console.WriteLine() Statements with MessageBox.Show() as shown below:
MessageBox.Show(String.Concat("Non-active IP: ", e.Reply.Address.ToString()));

Need to zip text files from a predefined location & save the zipped files in another location of hard disk using windows services

Need to zip text files from a predefined location & save the zipped files in another location of hard disk using windows services & delete the old text file (a scheduled service)
I tried the following code in which i used 'icsharpcode' for zipping the files. But after installing the service.. i am getting a message that "this services has started & then stopped..." without showing any required output.
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Design;
using System.Diagnostics.Eventing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
using ICSharpCode.SharpZipLib.Zip;
namespace createzip
{
public partial class createzip : ServiceBase
{
Timer timer1 = new Timer();
public createzip()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1.Elapsed += new ElapsedEventHandler(onelapsedtime);
timer1.Enabled = true;
timer1.Interval = 60000;
}
protected override void OnStop()
{
timer1.Enabled = false;
}
private void onelapsedtime(object source, ElapsedEventArgs e)
{
string folder = "#E:\\zipped files";
Directory.SetCurrentDirectory(folder);
string output = "#E:\\output";
string outputfilename = Path.Combine(output, "this file is zipped");
using (var x = new ZipFile(output))
{
foreach (var f in Directory.GetFiles(folder))
x.Add(f);
}
string[] filenames = Directory.GetFiles(folder);
using ( ZipOutputStream s = new
ZipOutputStream(File.Create(output))) //(args[1])))
{
s.SetLevel(9);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry(Path.GetDirectoryName(file));
//entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourcebytes;
do
{
sourcebytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourcebytes);
}
while (sourcebytes > 0);
}
}
s.Finish();
s.Close();
return;
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
namespace trail2zip
{
public partial class trail2zip : ServiceBase
{
Timer timer;
string path1 = #"E:\zipped files\New Text Document.txt";
string path2 = #"E:\output\filezipname.zip";
string path3 = #"E:\zipped files\R_23122015.txt";
int timerInterval = 60000;
public trail2zip()
{
InitializeComponent();
timer = new Timer();
timer.Elapsed+=new ElapsedEventHandler(this.timer_Elapsed);
timer.Interval = timerInterval;
timer.Enabled = true;
}
protected override void OnStart(string[] args)
{
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
timer.SynchronizingObject = null;
timer.Elapsed -= new ElapsedEventHandler(this.timer_Elapsed);
timer.Dispose();
timer = null;
}
public void timer_Elapsed(object sender, ElapsedEventArgs e)
{
ZipFile z = ZipFile.Create(path2); //(filezipname);
z.BeginUpdate();
z.Add(path1);
z.Add(path3);
z.CommitUpdate();
z.Close();
}
}
}

Categories

Resources