Tuesday, July 21, 2015

Debug Windows Service Application


  Windows service is a computer program that operates in the background. Programmers are widely using service like approach for the programs that needs to be run during the entire active time of computer but require a less user interaction.


   Visual studio provides a template for the developers to implement these kinds of applications.

According to myself, one of the main challenge of the windows service application is debugging. Of cause you cant run the service application as it is, without installing it as a windows service or change it to a console application. 

We have two approaches to debug windows services. As the first one to identify the problems in actual working environment we can create a log file foe the windows service. Personally i prefer separate log file like text file for the purpose.We can implement a simple method to the log every important steps of service in to this file. Sample class that i used to log activities can shown below 

Code:
public class ProgramLog
    {
        string fileName = "";//Global variable to store file name

        #region method to handle usual log records
        public void log(string text)//create normal Log text
        {
            fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory+fileName))
            {
                using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
                using (TextWriter tw = new StreamWriter(fs))
                {
                    tw.WriteLine(text);
                    tw.Flush();
                    tw.Close();
                    fs.Close();
                }
            }
            else
            {
                createFolder();
                log(text);
            }
        }
        #endregion

        #region log Error record 
        public void logError(string text, string className,int LineNumber, string Stacktrace)//create error text
        {
            fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + fileName))
            {
                using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
                using (TextWriter tw = new StreamWriter(fs))
                {
                    tw.WriteLine("**************************ERROR****************************");
                    tw.WriteLine(text);
                    tw.WriteLine("In Class :{0}", className);
                    tw.WriteLine("In Line :{0}", LineNumber);
                    tw.WriteLine("ERROR :{0}",Stacktrace);
                    tw.WriteLine("***********************************************************");
                }
            }
            else
            {
                createFolder();
                logError(text,className,LineNumber,Stacktrace);
            }
        }
        #endregion

        #region create folder to store log files
        public void createFolder()//create a folder for Log files
        {
            try
            {
                if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Log"))
                {
                    string folderName = "Log";
                    Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + folderName);
                    FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
                    StreamWriter sr = new StreamWriter(fs);
                    sr.Flush();
                    sr.Close();
                    fs.Close();
                }
                else
                {
                    FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
                    StreamWriter sr = new StreamWriter(fs);
                    sr.Flush();
                    sr.Close();
                    fs.Close(); 
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }
        #endregion



But if you need to write the logs to Application log or event log you can do it as follow which shows in  MSDN.

But this will cost you a lot on behalf of time, because its still hard to figure our where the exact error location is. So we need to find a way that we can debug the application line by line as i explain below as the second approach.

In this approach, first we need to convert our application into console application.For that we can simply right click on the project and go to the "properties window". At that window, under the "Application tab" we can select the Output type as "Console application".

Then you need to add a new method that initiate your program, in to the service. For that you need to select the [yourserviceName].cs file and go to the code view by double click it.

Generally we can see  two methods and one constructor in auto generated template of service.cs file. OnStart() method is the place that commits the service operations where OnStop() stops them. When we started the windows service, it triggers the OnStart() method and keeps it up and ruining until we call the OnStop() method. So that, in here, our idea is to call OnStart() but terminate it without hanging.

To do that we can add a new method like follow


Code:
        internal void TestStartupAndStop(string[] args)
        {
            this.OnStart(args);
            Console.ReadLine();
            this.OnStop();
        }

As you see here this method starts the operations and give you the desired output. After you click any key it triers the OnStop() methord to stop activities

Next thing you need to do is change the main method of the application. Normally main method of a windows service looks like follow



Code:
        static void Main(string []args)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new CPEService()
            };
            ServiceBase.Run(ServicesToRun);
        }

but here we need to change this method as follow.

Code:
static void Main(string[] args)
        {
            if (Environment.UserInteractive)
            {
                MyNewService service1 = new MyNewService(args);
                service1.TestStartupAndStop(args);
            }
            else
            {
                // Put the body of your old Main method here.
            }

Now you can run the service as a normal console application. But make sure that to replace main method before you deploy the application as service.

Tuesday, March 3, 2015

Few good clips for AI fans


Simulated Simulated Annealing


  

Genetic algorithm


Simple introduction to neural networks  


Perceptron Algorithm 

The neuron 


Saturday, January 3, 2015

Tips to debug two WTF errors in MVC (Asp.net MVC 4 - Oracle)

         Normally most of the existing programming languages has there own ways to prompt errors to the programmer. IDE makes them sharp by adding knacks that helps user to sort out the error. 

      But some times, there may be rare situations that was missed to address by the IDE or cant address by the IDE. Generally this can be seen when it comes to a new technology which don't have much developer crowd at the movement or when plunging a 3rd party technology to a existing technology. 

        Since i'm a newbie for MVC+Oracle, i had few general errors which are caused to stuck me for few hours , sometimes days.  I had database first approach and i didn't  use Razor but ASP.net. 

_________________________________________________________________________________

WTF ERROR ???

I use this term for the program errors that are not giving an enough details to debug it. 

Ex: "Invalid Operation"   

! No error code         
!! No line number
!!! No special module
!!!! No any hint 

____________________________________________________________________

  1. Cant see the changes on browser

 2.  "Operation invalid due to the current state of the object "
    • I got this error when try to save the changes by using "SaveChanges()" Method.
[Full Description]

    • There was no any hint where i need to correct to avoid the error. That made this error "WTF".
    • I found one common possibility that directs to this error.
    • but it was not the problem for me.Error continued and i decided to check the database for errors
    • when i tried to perform insertion on database it gave me an error with the message "Permission denied".
    • Finally i found that, i didn't  give the enough permission to  the oracle user to perform the operation on database