Windows service file listener only listens when debugging - c#

First the code:
public partial class Watcher : ServiceBase
{
private const string PathToFolder = #"D:\print\";
public Watcher()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
private void fileWatcher_Changed(object sender, FileSystemEventArgs e)
{
if (e.Name != "test.txt")
{
return;
}
using (var r = new StreamReader(e.FullPath))
{
var json = r.ReadToEnd();
dynamic tempTest = JsonConvert.DeserializeObject(json);
const string filename = PathToFolder + "textParsed.txt";
if (File.Exists(filename))
{
File.Delete(filename);
}
using (var file = File.CreateText(filename))
{
file.WriteLine(tempTest.Name.ToString());
}
}
}
}
If there are changes to the text.txt file I'm suppose to parse the content of that text file and create another file. If I attach VS to the service and debug the service, the event gets fired, but when running normally, nothing happens.
The installer has LocalSystem privileges and that's pretty much all the changes I've made... Should be pretty straight forward, but somehow isn't.

Related

Windows service keeps on failing

I have a windows service which is designed to continuously retrieve messages from Azure service bus queue and pass it to other queues.I have deployed this service to one of the server computer but unfortunately the service keeps failing at a random time interval.
My application handles the exceptions and writes them to a file.The main purpose of this application is to hook up to the queue and listen all the messages continuously and never move to the Application stop stage.I'm using a timer in this application and I don't think that is causing any problem.I'd like to know what would be the best approach to handle errors and make my application stable, below is the code. Thanks in advance.
public partial class Scheduler : ServiceBase
{
private Timer Scheduletimer = null;
private string servicenamespace;
private string issuesecretkey;
private string sourcequeue;
private string destinationqueue;
public Scheduler()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Scheduletimer = new Timer();
this.Scheduletimer.Interval = 1000;//1 sec
this.Scheduletimer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
Scheduletimer.Enabled = true;
WriteToFile("Application started : "+DateTime.Now.ToString());
}
protected void timer1_Tick(object sender, ElapsedEventArgs e)
{
Scheduletimer.Enabled = false;
WriteToFile("Business logic started : " + DateTime.Now.ToString());
//Business Logic code goes here
}
protected override void OnStop()
{
Scheduletimer.Enabled = false;
WriteToFile("Application stoped : "+DateTime.Now.ToString());
}
public void WriteToFile(string text)
{
string directory = AppDomain.CurrentDomain.BaseDirectory;
string logfilepath = directory + "LogFile.txt";
using (StreamWriter writer = new StreamWriter(logfilepath, true))
{
writer.WriteLine(text);
writer.Close();
}
}
public void WriteErrorsToFile(Exception ex)
{
string directory = AppDomain.CurrentDomain.BaseDirectory;
string Errorlogfilepath = directory + "ErrorLogFile.txt";
using (StreamWriter writer = new StreamWriter(Errorlogfilepath, true))
{
writer.WriteLine("Time Occured: " + DateTime.Now.ToString());
writer.WriteLine(ex.Message +" "+ DateTime.Now.ToString());
writer.Close();
}
}

Console C# check for internet availability and wait until it is not available

I have been searching for the code which will help me if the internet connection breaks in between.
I am having a console app which takes data from database and sends mail in bulk. Now while sending mails if internet connection fails than I want to wait until internet is available.
I got good ans here
public static void ConnectToPUServer()
{
var client = new WebClient();
while (i < 500 && networkIsAvailable)
{
string html = client.DownloadString(URI);
//some data processing
Console.WriteLine(i);
i++;
URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
}
Console.WriteLine("Complete.");
writer.Close();
}
static void NetworkChange_NetworkAvailabilityChanged(object sender,NetworkAvailabilityEventArgs e)
{
networkIsAvailable = e.IsAvailable;
if (!networkIsAvailable)
{
Console.WriteLine("Internet connection not available! We resume as soon as network is available...");
}
else
{
ConnectToPUServer();
}
}
This is not exactly what I want. But I want to apply something similar to this. Can anybody help me how to implement this? I mean what is ConnectToPUServer and when NetworkChange_NetworkAvailabilityChanged will be executed and what namespace to be used?
you can use the below mentioned code for it you have to use
using System.Net.NetworkInformation;
public partial class MainWindow : Window
{
public bool IsAvailable { get; set; }
public MainWindow()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
IsAvailable = e.IsAvailable;
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
if (IsAvailable)
{
WebBrowser1.Navigate(TextBox1.Text);
}
else
{
MessageBox.Show("Your Popup Message");
}
}
}

windows service file delete c#

windows service example code
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace file_delete
{
public partial class file_delete : ServiceBase
{
public file_delete()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
private void deleteFile(string folder)
{
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(folder);
System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");
foreach (System.IO.FileInfo fi in fileNames)
{
fi.Delete();
}
How can I call the deleteFile(string folder) from windows forms?
You can use the OnCustomCommand override, but this only takes an integer as an argument and does not support passing strings to the service.
The other options would be to create a WCF service or use Remoting to pass the information you need to the service and call the delete method.
EDIT: to respond to a question in the comments about how to use OnCustomCommand in a very strange way is as follows.
In the service you would need something like this.
private const int CMD_INIT_DELETE = 1;
private const int CMD_RUN_DELETE = 0;
private bool m_CommandInit = false;
private StringBuilder m_CommandArg = new StringBuilder();
protected override void OnCustomCommand(int command)
{
if (command == CMD_INIT_DELETE)
{
this.m_CommandArg.Clear();
this.m_CommandInit = true;
}
else if (this.m_CommandInit)
{
if (command == CMD_RUN_DELETE)
{
this.m_CommandInit = false;
this.deleteFile(this.m_CommandArg.ToString());
}
else
{
this.m_CommandArg.Append((char)command);
}
}
}
In the windows form application you would have something like this
private const int CMD_INIT_DELETE = 1;
private const int CMD_RUN_DELETE = 0;
private void RunServiceDeleteMethod(string delFolder)
{
serviceController1.ExecuteCommand(CMD_INIT_DELETE);
foreach (char ch in delFolder)
serviceController1.ExecuteCommand((int)ch);
serviceController1.ExecuteCommand(CMD_RUN_DELETE);
}
THIS IS NOT TESTED and only a proof of concept. Again, I DO NOT recommend doing it this way and the above example is only to show how NOT to do this type of communications between desktop applications and services.

Redirect console.writeline from windows application to a string

I have an external dll written in C# and I studied from the assemblies documentation that it writes its debug messages to the Console using Console.WriteLine.
this DLL writes to console during my interaction with the UI of the Application, so i don't make DLL calls directly, but i would capture all console output , so i think i got to intialize in form load , then get that captured text later.
I would like to redirect all the output to a string variable.
I tried Console.SetOut, but its use to redirect to string is not easy.
As it seems like you want to catch the Console output in realtime, I figured out that you might create your own TextWriter implementation that fires an event whenever a Write or WriteLine happens on the Console.
The writer looks like this:
public class ConsoleWriterEventArgs : EventArgs
{
public string Value { get; private set; }
public ConsoleWriterEventArgs(string value)
{
Value = value;
}
}
public class ConsoleWriter : TextWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
public override void Write(string value)
{
if (WriteEvent != null) WriteEvent(this, new ConsoleWriterEventArgs(value));
base.Write(value);
}
public override void WriteLine(string value)
{
if (WriteLineEvent != null) WriteLineEvent(this, new ConsoleWriterEventArgs(value));
base.WriteLine(value);
}
public event EventHandler<ConsoleWriterEventArgs> WriteEvent;
public event EventHandler<ConsoleWriterEventArgs> WriteLineEvent;
}
If it's a WinForm app, you can setup the writer and consume its events in the Program.cs like this:
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
using (var consoleWriter = new ConsoleWriter())
{
consoleWriter.WriteEvent += consoleWriter_WriteEvent;
consoleWriter.WriteLineEvent += consoleWriter_WriteLineEvent;
Console.SetOut(consoleWriter);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
static void consoleWriter_WriteLineEvent(object sender, Program.ConsoleWriterEventArgs e)
{
MessageBox.Show(e.Value, "WriteLine");
}
static void consoleWriter_WriteEvent(object sender, Program.ConsoleWriterEventArgs e)
{
MessageBox.Show(e.Value, "Write");
}
It basically amounts to the following:
var originalConsoleOut = Console.Out; // preserve the original stream
using(var writer = new StringWriter())
{
Console.SetOut(writer);
Console.WriteLine("some stuff"); // or make your DLL calls :)
writer.Flush(); // when you're done, make sure everything is written out
var myString = writer.GetStringBuilder().ToString();
}
Console.SetOut(originalConsoleOut); // restore Console.Out
So in your case you'd set this up before making calls to your third-party DLL.
You can also call SetOut with Console.OpenStandardOutput, this will restore the original output stream:
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
Or you can wrap it up in a helper method that takes some code as an argument run it and returns the string that was printed. Notice how we gracefully handle exceptions.
public string RunCodeReturnConsoleOut(Action code)
{
string result;
var originalConsoleOut = Console.Out;
try
{
using (var writer = new StringWriter())
{
Console.SetOut(writer);
code();
writer.Flush();
result = writer.GetStringBuilder().ToString();
}
return result;
}
finally
{
Console.SetOut(originalConsoleOut);
}
}
Using solutions proposed by #Adam Lear and #Carlo V. Dango I created a helper class:
public sealed class RedirectConsole : IDisposable
{
private readonly Action<string> logFunction;
private readonly TextWriter oldOut = Console.Out;
private readonly StringWriter sw = new StringWriter();
public RedirectConsole(Action<string> logFunction)
{
this.logFunction = logFunction;
Console.SetOut(sw);
}
public void Dispose()
{
Console.SetOut(oldOut);
sw.Flush();
logFunction(sw.ToString());
sw.Dispose();
}
}
which can be used in the following way:
public static void MyWrite(string str)
{
// print console output to Log/Socket/File
}
public static void Main()
{
using(var r = new RedirectConsole(MyWrite)) {
Console.WriteLine("Message 1");
Console.WriteLine("Message 2");
}
// After the using section is finished,
// MyWrite will be called once with a string containing all messages,
// which has been written during the using section,
// separated by new line characters
}

Getting media player state in windows phone 7

I have amended my code in App.xaml.cs
But i have an error at "this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));" (Placed at end of my App.xaml.cs)
The error is
"System.TimeSpan.FromMilliseconds(double) is a method but is used like a type"
System.Windows.Application.ApplicationLifetimeObjects is a property but is used like a type
Identifier expected
Invalid token '(' in a class, struct or interface member declaration
Method must have a return type
Below is the whole piece of my App.xaml.cs
namespace Alarm_Clock
{
public class GlobalData
{
public BitmapImage bitmapImage;
}
public partial class App : Application
{
public static GlobalData globalData;
public class XNAAsyncDispatcher : IApplicationService
{
private readonly DispatcherTimer _frameworkDispatcherTimer;
public XNAAsyncDispatcher(TimeSpan dispatchInterval)
{
_frameworkDispatcherTimer = new DispatcherTimer();
_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
_frameworkDispatcherTimer.Interval = dispatchInterval;
}
void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}
public static string imagePath
{
//get { return "PhotoNote_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg"; }
get;
set;
}
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
//Global variables for the WriteableBitmap objects used throughout the application.
public static WriteableBitmap CapturedImage;
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
globalData = new GlobalData();
globalData.bitmapImage = new BitmapImage();
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}
}
The pause just dont work in my code below.
This is my whole piece of code:
namespace Alarm_Clock
{
public partial class AlarmRing : PhoneApplicationPage
{
int songSelectedIndex;
public AlarmRing()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait;
//Get the DateTime.Now and place it into "timeTxtBlock" text block
timeTxtBlock.Text = DateTime.Now.ToShortTimeString();
//Read from Isolated storage queSetting.txt for the number of question to answer by the user
//Read from Isolated storage music.txt for the selected music to play when the alarm ring
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
try
{
StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\music.txt", FileMode.Open, myStore));
songSelectedIndex = Convert.ToInt16(readFile.ReadLine());
readFile.Close();
}
catch (Exception)
{
//If the user did not select the music to be played when the alarm ring it will play the first music by default
songSelectedIndex = 0;
}
using (var ml = new MediaLibrary())
{
//Play the music using media player from the song collection
FrameworkDispatcher.Update();
MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
MediaPlayer.Play(ml.Songs[songSelectedIndex]);
MediaPlayer.IsRepeating = true;
MediaPlayer.IsMuted = false;
MediaPlayer.IsShuffled = false;
MediaPlayer.IsVisualizationEnabled = false;
}
//Load code
loadtime();
}
static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{
if (MediaPlayer.State == MediaState.Paused)
{
MediaPlayer.Resume();
}
}
void loadtime()
{
ringingAlarm.Begin();
//Get the DateTime.Now
String timeNow = DateTime.Now.ToShortTimeString();
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string labels in storage.GetFileNames("*"))
{
XElement _xml;
IsolatedStorageFileStream location = new IsolatedStorageFileStream(labels, System.IO.FileMode.Open, storage);
System.IO.StreamReader file = new System.IO.StreamReader(location);
_xml = XElement.Parse(file.ReadToEnd());
if (_xml.Name.LocalName != null)
{
XAttribute time = _xml.Attribute("time");
//Get the day of the week
String dayOfWeek = DateTime.Now.DayOfWeek.ToString("F");
if (timeNow == time.Value.ToString())
{
//"textBlock2" text block will display the label of the alarm
textBlock2.Text = labels;
}
}
file.Dispose();
location.Dispose();
}
}
}
string settingQues;
string settingQuesPassToGame;
string format;
string format1;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
//Try get the value of number of question to be answered by the user that is pass over from setClockPage.xaml
if (NavigationContext.QueryString.TryGetValue("settingQues", out settingQues))
settingQuesPassToGame = settingQues;
//Try get the format that is passed over
if (NavigationContext.QueryString.TryGetValue("format", out format))
format1 = format;
}
//Display a pop up message box with instruction
//And navigate to "Start.xaml"
private void gameBtn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("To dismiss alarm" + System.Environment.NewLine + "- Answer selected IQ question" + System.Environment.NewLine + "- With all correct answer");
NavigationService.Navigate(new Uri("/Start.xaml?ringingAlarmTitle=" + textBlock2.Text + "&ringingAlarmTime=" + timeTxtBlock.Text + "&format1=" + format1, UriKind.Relative));
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
public Visibility visible { get; set; }
}
}
When I place MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged); at the constructor there is an error.
The error is MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged) is a method but is use like a type.
I have changed my code but it still dosent work
static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{
if (MediaPlayer.State == MediaState.Paused)
{
MediaPlayer.Resume();
}
}
You have to dispatch XNA Events manual in Windows Phone 7 Apps:
public class XNAAsyncDispatcher : IApplicationService
{
private readonly DispatcherTimer _frameworkDispatcherTimer;
public XNAAsyncDispatcher(TimeSpan dispatchInterval)
{
_frameworkDispatcherTimer = new DispatcherTimer();
_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
_frameworkDispatcherTimer.Interval = dispatchInterval;
}
void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}
Add this to the end of your public App()
public App()
{
// Other stuff
// End
this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}
Complete Guide: http://msdn.microsoft.com/library/ff842408.aspx

Categories