|
I try to create a Windows Service which listens to UDP port 514, i install it using installutil.exe and i get the following error message:
---------------------------
Services
---------------------------
The SyslogService2005 service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.
---------------------------
OK
---------------------------
In practise it starts working till the progressbar in Properties Window ends!
my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Net.Sockets;
using System.Net;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Threading;
using System.IO;
namespace SyslogService2005
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
this.ServiceName = "SyslogServiceUDP514";
this.CanStop = true;
this.CanPauseAndContinue = true;
this.AutoLog = true;
}
private const int listenPort = 514;
class UdpState
{
public UdpClient u;
public IPEndPoint e;
}
public static bool messageReceived = false;
public static bool processWorking = false;
public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
Byte[] receiveBytes = u.EndReceive(ar, ref e);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
LogMessageToFile(receiveString);
messageReceived = true;
}
private static void StartListener()
{
IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
UdpClient u = new UdpClient(e);
UdpState s = new UdpState();
s.e = e;
s.u = u;
while (processWorking==true)
{
u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
while (!messageReceived)
{
Thread.Sleep(100);
}
}
}
static void LogMessageToFile(string msg)
{
System.IO.StreamWriter sw = System.IO.File.AppendText("C:\\Services\\LogFile.txt");
try
{
string logLine = System.String.Format("{0:G}: {1}.", System.DateTime.Now, msg);
sw.WriteLine("+----------------------------------------------------------------+");
sw.WriteLine(logLine);
}
finally
{
sw.Close();
}
}
protected override void OnStart(string[] args)
{
processWorking = true;
StartListener();
}
protected override void OnStop()
{
if ((Thread.CurrentThread != null) && (Thread.CurrentThread.IsAlive))
{
processWorking = false;
Thread.Sleep(5000);
Thread.CurrentThread.Abort();
LogMessageToFile("Service Stopped");
}
}
}
}
|
|
|
|
|
Have you tested your code in normal desktop process?
led mike
|
|
|
|
|
|
Dimitris Tselios wrote: No...
Bzzzz, wrong answer.
led mike
|
|
|
|
|
xacc.ide - now with TabsToSpaces support IronScheme - 1.0 beta 1 - coming soon ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))
|
|
|
|
|
I did a console app, it is working properly! Any ideas?
|
|
|
|
|
What about attaching the debugger and stepping through the startup code?
Mark Salsbery
Microsoft MVP - Visual C++
|
|
|
|
|
Hello folks!!!
I have a serious problem. I´making a "file explorer" in C# and it has to set a root node from an external HDD and show only files and folders hierarchically down it. This I´ve done and it´s working "fine"... with some problems but working!
The major problem is that I´ve to load a file by double clicking it on the list view (DWGs MUST open with AutoCAD, DOCs and Spreadsheets MUST open with MS Ofiice, Pictures must open with paint and whatever!) I know that I need to use ShellAPI BUT I´m having problems to use it properlly... I´ve been reading some HotTo´s, articles, walkthroughs (including C# does Shell) but none answer my question especifically.....
Can some one please help me? I´m desperate!!!!
thanks
PS. I´m using framework 1.1/2.0 with .NET 2003
|
|
|
|
|
Do you have to use the shell? if so, there's a cool article on here somewhere if you search.
Any reason why you can't just use System.Diagnosics.Process.Start(pathToFile); ?
[Edit]Check out the articles by arikp[^]
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
Dave,
I tried but the namespace doesn´t exists....
I´m using VisualStudio 2003!!!
I think I can´t avoid shell....
modified on Friday, October 10, 2008 11:13 AM
|
|
|
|
|
Yes, it does exists, and has since .NET 1.0.
What does your code look like??
|
|
|
|
|
I´ll try to explain my code while my poor English let :P!! It´s a file manager (a TreeView and a ListView). The Tree View shows only FOLDERS and List View only FILES. A file manager similar to Windows explorer but with a RootNode set to an especific folder on an external HD. Only the Root node and subnodes are visible. This I´ve done but not working properlly... just working...
The problem I´m having is to load the program by double-clicking on the file in the ListView.
The code is shown down
using System;
using System.Drawing;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Management;
using System.Globalization;
namespace Painel_de_Controle_ETECH
{
public class Workspace : System.Windows.Forms.Form
{
private System.Windows.Forms.TreeView tvFolders;
private System.Windows.Forms.ImageList m_imageListTreeView;
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.ListView lvFiles;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private System.ComponentModel.IContainer components;
public Workspace()
{
InitializeComponent();
PopulateDriveList();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Workspace));
this.tvFolders = new System.Windows.Forms.TreeView();
this.m_imageListTreeView = new System.Windows.Forms.ImageList(this.components);
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.splitter1 = new System.Windows.Forms.Splitter();
this.lvFiles = new System.Windows.Forms.ListView();
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.tvFolders.Dock = System.Windows.Forms.DockStyle.Left;
this.tvFolders.ImageList = this.m_imageListTreeView;
this.tvFolders.Location = new System.Drawing.Point(0, 32);
this.tvFolders.Name = "tvFolders";
this.tvFolders.Size = new System.Drawing.Size(168, 360);
this.tvFolders.TabIndex = 2;
this.tvFolders.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvFolders_AfterSelect);
this.m_imageListTreeView.ImageSize = new System.Drawing.Size(16, 16);
this.m_imageListTreeView.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("m_imageListTreeView.ImageStream")));
this.m_imageListTreeView.TransparentColor = System.Drawing.Color.Transparent;
this.toolBar1.AutoSize = false;
this.toolBar1.DropDownArrows = true;
this.toolBar1.Location = new System.Drawing.Point(0, 0);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(602, 32);
this.toolBar1.TabIndex = 0;
this.splitter1.Location = new System.Drawing.Point(168, 32);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(3, 360);
this.splitter1.TabIndex = 5;
this.splitter1.TabStop = false;
this.lvFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.lvFiles.Location = new System.Drawing.Point(171, 32);
this.lvFiles.Name = "lvFiles";
this.lvFiles.Size = new System.Drawing.Size(431, 360);
this.lvFiles.TabIndex = 0;
this.lvFiles.View = System.Windows.Forms.View.Details;
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBox1.Location = new System.Drawing.Point(312, 8);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(200, 20);
this.textBox1.TabIndex = 6;
this.textBox1.Text = "";
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.button1.Location = new System.Drawing.Point(520, 8);
this.button1.Name = "button1";
this.button1.TabIndex = 7;
this.button1.Text = "Refinar...";
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(602, 392);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.lvFiles);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.tvFolders);
this.Controls.Add(this.toolBar1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "Workspace";
this.ShowInTaskbar = false;
this.Text = "Workspace";
this.ResumeLayout(false);
}
#endregion
#region Pupulate
#region Criar DriveList
private void PopulateDriveList()
{
TreeNode nodeTreeNode;
int imageIndex = 0;
int selectIndex = 0;
const int LocalDisk = 3;
this.Cursor = Cursors.WaitCursor;
tvFolders.Nodes.Clear();
nodeTreeNode = new TreeNode("My Computer",0,0);
ManagementObjectCollection queryCollection = getDrives();
foreach ( ManagementObject mo in queryCollection)
{
switch (int.Parse( mo["DriveType"].ToString()))
{
case LocalDisk:
imageIndex = 6;
selectIndex = 6;
break;
default:
imageIndex = 2;
selectIndex = 3;
break;
}
if(int.Parse( mo["DriveType"].ToString()) == LocalDisk && mo["Name"].ToString() != "C:" )
{
nodeTreeNode = new TreeNode(mo["Name"].ToString() + "\\Painel de Controle ETECH\\Projetos ETECH",imageIndex,selectIndex);
tvFolders.Nodes.Add(nodeTreeNode);
TreeNodeCollection nodeCollection = nodeTreeNode.Nodes;
nodeTreeNode.Expand();
}
}
InitListView();
this.Cursor = Cursors.Default;
}
#endregion
#region Preencher tvFolder
private void tvFolders_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
this.Cursor = Cursors.WaitCursor;
TreeNode nodeCurrent = e.Node;
nodeCurrent.Nodes.Clear();
if (nodeCurrent.SelectedImageIndex == 0)
{
PopulateDriveList();
}
else
{
PopulateDirectory(nodeCurrent, nodeCurrent.Nodes);
}
this.Cursor = Cursors.Default;
}
#endregion
#region Iniciar lvFiles
protected void InitListView()
{
lvFiles.Clear();
lvFiles.Columns.Add("Name",150,System.Windows.Forms.HorizontalAlignment.Left);
lvFiles.Columns.Add("Size",75, System.Windows.Forms.HorizontalAlignment.Right);
lvFiles.Columns.Add("Created", 140, System.Windows.Forms.HorizontalAlignment.Left);
lvFiles.Columns.Add("Modified", 140, System.Windows.Forms.HorizontalAlignment.Left);
}
#endregion
#region Busacar Diretórios
protected void PopulateDirectory(TreeNode nodeCurrent, TreeNodeCollection nodeCurrentCollection)
{
TreeNode nodeDir;
int imageIndex = 2;
int selectIndex = 3;
if (nodeCurrent.SelectedImageIndex != 0)
{
try
{
if(Directory.Exists(getFullPath(nodeCurrent.FullPath)) == false)
{
MessageBox.Show("Directory or path " + nodeCurrent.ToString() + " does not exist.");
}
else
{
PopulateFiles(nodeCurrent);
string[] stringDirectories = Directory.GetDirectories(getFullPath(nodeCurrent.FullPath));
string stringFullPath = "";
string stringPathName = "";
foreach (string stringDir in stringDirectories)
{
stringFullPath = stringDir;
stringPathName = GetPathName(stringFullPath);
nodeDir = new TreeNode(stringPathName.ToString(),imageIndex,selectIndex);
nodeCurrentCollection.Add(nodeDir);
}
}
}
catch (IOException e)
{
MessageBox.Show("Error: Drive not ready or directory does not exist.");
}
catch (UnauthorizedAccessException e)
{
MessageBox.Show("Error: Drive or directory access denided.");
}
catch (Exception e)
{
MessageBox.Show("Error: " + e);
}
}
}
#endregion
#region Nome dos Diretórios
protected string GetPathName(string stringPath)
{
string[] stringSplit = stringPath.Split('\\');
int _maxIndex = stringSplit.Length;
return stringSplit[_maxIndex-1];
}
#endregion
#region Buscar Arquivos
protected void PopulateFiles(TreeNode nodeCurrent)
{
string[] lvData = new string[4];
InitListView();
if (nodeCurrent.SelectedImageIndex != 0)
{
if(Directory.Exists((string) getFullPath(nodeCurrent.FullPath)) == false)
{
MessageBox.Show("Directory or path " + nodeCurrent.ToString() + " does not exist.");
}
else
{
try
{
string[] stringFiles = Directory.GetFiles(getFullPath(nodeCurrent.FullPath));
string stringFileName = "";
DateTime dtCreateDate, dtModifyDate;
Int64 lFileSize = 0;
foreach (string stringFile in stringFiles)
{
stringFileName = stringFile;
FileInfo objFileSize = new FileInfo(stringFileName);
lFileSize = objFileSize.Length;
dtCreateDate = objFileSize.CreationTime;
dtModifyDate = objFileSize.LastWriteTime;
lvData[0] = GetPathName(stringFileName);
lvData[1] = formatSize(lFileSize);
if (TimeZone.CurrentTimeZone.IsDaylightSavingTime(dtCreateDate) == false)
{
lvData[2] = formatDate(dtCreateDate.AddHours(1));
}
else
{
lvData[2] = formatDate(dtCreateDate);
}
if (TimeZone.CurrentTimeZone.IsDaylightSavingTime(dtModifyDate) == false)
{
lvData[3] = formatDate(dtModifyDate.AddHours(1));
}
else
{
lvData[3] = formatDate(dtModifyDate);
}
ListViewItem lvItem = new ListViewItem(lvData,0);
lvFiles.Items.Add(lvItem);
}
}
catch (IOException e)
{
MessageBox.Show("Error: Drive not ready or directory does not exist.");
}
catch (UnauthorizedAccessException e)
{
MessageBox.Show("Error: Drive or directory access denided.");
}
catch (Exception e)
{
MessageBox.Show("Error: " + e);
}
}
}
}
#endregion
#region Pegar Caminho
protected string getFullPath(string stringPath)
{
string stringParse = "";
stringParse = stringPath.Replace("My Computer", "");
return stringParse;
}
#endregion
#region Buscar Lista de Drives
protected ManagementObjectCollection getDrives()
{
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
ManagementObjectCollection queryCollection = query.Get();
return queryCollection;
}
#endregion
#region Pegar Data
protected string formatDate(DateTime dtDate)
{
string stringDate = "";
stringDate = dtDate.ToShortDateString().ToString() + " " + dtDate.ToShortTimeString().ToString();
return stringDate;
}
#endregion
#region Converter tamanho para KB
protected string formatSize(Int64 lSize)
{
string stringSize = "";
NumberFormatInfo myNfi = new NumberFormatInfo();
Int64 lKBSize = 0;
if (lSize < 1024 )
{
if (lSize == 0)
{
stringSize = "0";
}
else
{
stringSize = "1";
}
}
else
{
lKBSize = lSize / 1024;
stringSize = lKBSize.ToString("n",myNfi);
stringSize = stringSize.Replace(".00", "");
}
return stringSize + " KB";
}
#endregion
#endregion
#region Eventos de Shell
#region Executar Arquivo
private void executeFile()
{
ShellLib.ShellExecute shellExecute = new ShellLib.ShellExecute();
shellExecute.Path = @"C:\Arquivos de programas\AutoCAD 2008\acad.exe";
shellExecute.Execute();
}
#endregion
#endregion
}
}
Just ignore the comments in portuguese!! I translated some important lines to english!!!
If anyone could helpme I will be VERY pleased!!! very very very pleased!!! I will thank my whole life!!!!
|
|
|
|
|
NOT THE WHILE BLOODY THING!! Just the part where you're having the problem launching files!
Thankfully, that part is at the end of the file. Noone is going to go looking through all that code for a small part...
Your executeFile method just needs to do something like:
Process.Start(filepath)
Because the Shell interpret spaces as a delimiter, it's a good idea to enclose filepaths in double quotes.
Process.Start(String.Format("\"{0}\"", filepath))
|
|
|
|
|
hahahahahaha sorry for that, my mistake !!!!
It was just if you wanted to to test it!!! So I showed the whole thing!!!!
Well, as you can see I´m bloody new on c# and .net!!! The other question is where I call the executeFile method???
but the complier is still yelling me that System.Diagnosics.Process namespace doesn´t exists!!!
There is something else I should do?
Thanks!!! I really appreciate the whole support you are giving me!!!
|
|
|
|
|
Oops - that might be because of a typo in my earlier post!
Diagnosics should be
Diagnostics (missed the 't')
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
hehehehehehehe no problem dude!!!!
just one last question... on the header of the code a put just
using System.Diagnostics; ??? because System.Diagnostic.Process is unrecognized too : /
Thank you dudes.. I really owe you one!!!!
|
|
|
|
|
In 'using's at the top of your file you can only put namespaces.
Process is a class within System.Diagnostics so it can't be put in the using (and of course Start is a method of that class).
For future reference, typos like that happen quite regularly. If something's not found there's several ways to find the error.
1. Type the line letter by letter until intellisense kicks in, and see if what you need is in the list (spelled correctly!).
2. Use the Object Browser and search for the class and/or method, or alternatively, browse from the base namespace. This can be good for finding out if there are any references you need to add to your project too.
3. Paste it into google, if there is a typo, at the top of the first page of search results there will normally be a suggested correct spelling.
The first two have the added benifit of showing you all the other stuff in that namespace/class that you wouldn't have known about otherwise. You can learn loads of new stuff by browsing around in there.
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
Then you just use Process, not System.Diagnostics.Process.
The using statement at the top frees you from haing to type the entire qualifier.
As for where you call the execute statement, that's up to your design! Though, having looked at the entire code you posted, you don't have any code doing anything with the files in the listview after the listview is populated. So, I have no idea what you expect the user to do to launch a file. What happens there is totally up to you.
|
|
|
|
|
Yeah! That´s where I´m placing the method executeFile. I´ll call by an event like listView_Click or eiter the listView_SelectedIndex
The code to populate I found here at CP and with a few changes I made it point to an expecific folder to be the root (just basic programming and basic O.O. concepts). My professors at college helped me a little because they are not quite familiar with .NET Framework. Even I got more familiarity with Assemble Languages and Structured C/Pascal... and few notions of O.O C++ and Objective C(Mac) (I HATE JAVA). I´m still junior in .NET but I´m trying!!!! I almost did it... just a few errors!!!
I appreciate all the help!!! I owe you guys a beer!!!!
Thanks
|
|
|
|
|
Having one on you right now
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
I have Visual Studio 2005 with Framework 2.0 installed in my machine. Can I use Framework 3.0 or 3.5 with Vistual Studio 2005. Or do you think that I need to have Visual Studio 2008 to work with 3.0 and 3.5. And also is Framework 3.5 is out or is that still in its Beta version.
Thanks
|
|
|
|
|
netJP12L wrote: Can I use Framework 3.0 or 3.5 with Vistual Studio 2005
Yes. A google search will lead you to the correct MS pages to download what you need.
netJP12L wrote: is Framework 3.5 is out
Yes, has been for some time.
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
thanks for answering. i am scared upgrading from 2.0 or 3.5 in my existing vs 2005 as it may corrupt something. do you think this possibility. Why microsoft is releasing their framwork so often. It's getting very tough to catch up and live up the with one framwork atleast for a while.
|
|
|
|
|
3.0 and 3.5 live in addition to 2.0 so you can still use 2.0 if you like. In fact, VS2008 gives you the option of which of these frameworks you'd like to use on the New Project screen.
If you go for it you'll be able to play with LINQ, extension methods, WPF etc... That's why they added the new frameworks - new stuff/toys to play with
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
netJP12L wrote: i am scared upgrading from 2.0 or 3.5 in my existing vs 2005 as it may corrupt something. do you think this possibility.
It is possible but unlikely. That's what backups are for.
2005 to 2008 upgrade is a lot easier than 2003 to 2005 especially as VS2008 supports multi-targetting. That means that in VS2008 you can specify what version of the .NET Framework you want to use in your project.
netJP12L wrote: Why microsoft is releasing their framwork so often.
Jeez, if you think that is bad you should have been around when MFC was at its height (late 90s). MS were releasing a new version of that every few months at one point.
.NET 3.0 and 3.5 are purely additive. In otherwords they don't make changes to bits released in previous versions. (Unlike 1.1 to 2.0)
That means that if you know .NET 2.0 then you are not required to learn anything new unless you want to.
netJP12L wrote: It's getting very tough to catch up and live up the with one framwork atleast for a while.
Then concentrate on the areas you will find useful. I try and take a high level view of everything so I know what is out there. Then I drill down into what I need when I need it. I find that I can ramp up to a new part of the framework fairly quickly because I already know what it is for and what it does, I just need to learn the detail.
|
|
|
|
|