Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created windows service by using following code. I am able to install and start process successfully. It also record event log record. which i can see from server explorer but it is not serving my intended task.

I guess i am wrong somewhere in connection string calling and declaring.I have stored my connection string in app.config file as below:

I want to run service after every 15 mins. But my code is not working properly.
When i start service Event log message-service started
After every 15 mins is shows - service running
When i stop service it shows -service stopped

when its shows running app it should execute following code to retrieve data from database , process on it and again store it kind of.....

My code is below. Please help me i am stuck in it. I try to debug it also but it is not giving any error. and my below code is working OK in asp.net web application.

Please help me in this regards. Thanks in advance.

XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="b1" connectionString="data source=server;Trusted_Connection=False;database= nilam ;User ID=e64;Password=35ixtyF0ur" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>



C#
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.Data.Sql;
using System.Data.SqlClient;
using System.Reflection;
using System.Configuration;
using DotNetHelpers.UltimateImageResizer;
using System.IO;
using System.Timers;
using System.Threading;

namespace ImageResizerService
{
    public partial class Service1 : ServiceBase
    {
        private DirectoryInfo imgDir;
        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["b1"].ConnectionString);
        string ImgName;
        byte[] rImg;
        private System.Timers.Timer scheduleTimer1 = null;
        public Service1()
        {
            InitializeComponent();
            if (!EventLog.SourceExists("IResizeSource"))
            {
                EventLog.CreateEventSource("IResizeSource", "IResizeLog");
            }
            eventLog1.Source = "IResizeSource";
            eventLog1.Log = "IResizeLog";
            scheduleTimer1 = new System.Timers.Timer();
        }
        protected override void OnStart(string[] args)
        {
            scheduleTimer1.Interval = 15 * 60 * 1000;
            scheduleTimer1.Enabled = true;
            scheduleTimer1.Start();
            scheduleTimer1.Elapsed += new ElapsedEventHandler(ResizeImages1);
            //Thread t = new Thread(new ThreadStart(this.ResizeImages1)); //(new Thread(() => DoLongRunningStartupWork()){IsBackground = true}) .Start();
           // t.Start();
            eventLog1.WriteEntry("Service Started");
        }
        protected override void OnStop()
        {
            scheduleTimer1.Stop();
            scheduleTimer1.Enabled = false;
            eventLog1.WriteEntry("Service Stopped");
        }
         
        //public void ResizeImages1()
        public void ResizeImages1(object sender, ElapsedEventArgs e)
        {
            eventLog1.WriteEntry("Running");
            cn.Open();
            string sPro = "select * from Properties";
            SqlDataAdapter adptPro = new SqlDataAdapter(sPro, cn);
            DataSet dsPro = new DataSet("Properties");
            adptPro.Fill(dsPro, "Properties");

            string sImg = "select img_no,img_name,create_date, modify_date,img,flag from propertyImages";
            SqlDataAdapter adptImg = new SqlDataAdapter(sImg, cn);
            DataSet dsImg = new DataSet("propertyImages");
            adptImg.Fill(dsImg, "propertyImages");

            int cntPro = dsPro.Tables[0].Rows.Count;
            int cntImg = dsImg.Tables[0].Rows.Count; //Response.Write(cnt);

            for (int iPro = 0; iPro < cntPro; iPro++)
            {
                DataRow drPro = dsPro.Tables[0].Rows[iPro]; 
                for (int jPro = 0; jPro < zPro; jPro++)
                {
                    mid = mid + "0";
                }

                int fileNo = 10;
                for (int i = 1; i <= fileNo; i++)
                {
                    if (i <= 9)
                    {
                        stamp = "p" + mid + drPro["propertyid"] + "_0" + i;  //Response.Write("<br/>" + drPro["propertyid"].ToString() + "  " + stamp);
                    }
                    else
                    {
                        stamp = "p" + mid + drPro["propertyid"] + "_" + i;
                    }
                    string ImgExist = Path.GetFullPath("~/Images/") + stamp + ".jpg";
                    if (File.Exists(ImgExist))
                    {
                        bool flag = false;
                        DateTime cdateData = new DateTime();
                        DateTime mdateData = new DateTime();
                        int ImgNo = 0;
                        for (int iImg = 0; iImg < cntImg; iImg++)
                        {
                            DataRow drImg = dsImg.Tables[0].Rows[iImg]; 
                            ImgNo = int.Parse(drImg["img_no"].ToString());
                            ImgName = drImg["img_name"].ToString();
                            cdateData = DateTime.Parse(drImg["create_date"].ToString());
                            mdateData = DateTime.Parse(drImg["modify_date"].ToString());

                            if (ImgName == stamp)
                            {
                                flag = true;
                            }
                            else
                            {
                                flag = false;
                            }
                            if (flag == true)
                                break;
                        }

                        if (flag == true)
                        {
                            DateTime cdateFile = File.GetCreationTime(Path.GetFullPath("~/Images/" + ImgName + ".jpg")); 
                            DateTime mdateFile = File.GetLastWriteTime(Path.GetFullPath("~/Images/" + ImgName + ".jpg"));
                            if (cdateFile1 != cdateData1 || mdateFile1 != mdataData1)
                            {
                                ResizeImagesToDB();
                                DateTime modify_date = mdateFile;
                                DateTime create_date = cdateFile;

                                UpdateToDB(create_date, modify_date, rImg, ImgNo);

                                string LImgName = "";
                                byte[] LImg = null;
                                SqlCommand cmd = new SqlCommand("Select img_name,img from propertyImages where img_name='" + ImgName + "'", cn);
                                SqlDataReader br = cmd.ExecuteReader();
                                while (br.Read())
                                {
                                    LImgName = br["img_name"].ToString();
                                    LImg = (byte[])br["img"];
                                }
                                br.Close();

                                FileStream fs = new FileStream(Path.GetFullPath("~/Large/") + LImgName + ".jpg", FileMode.Create, FileAccess.ReadWrite);
                                fs.Write(LImg, 0, LImg.Length);
                                fs.Flush();
                                fs.Close();

                                ResizeImageToDisk();
                            }
                        }
                        else
                        {
                            ResizeImagesToDB();
                            SqlCommand cmd = new SqlCommand("Select img_name,img from propertyImages where img_name='" + ImgName + "'", cn);
                            SqlDataReader br = cmd.ExecuteReader();
                            while (br.Read())
                            {
                                LImgName = br["img_name"].ToString();
                                LImg = (byte[])br["img"];
                            }
                            br.Close();
                        }
                    }
                }
            }
            cn.Close();
            cn.Dispose();
        }
    }
}
Posted
Updated 14-Mar-13 4:42am
v7
Comments
Richard C Bishop 14-Mar-13 10:14am    
That is too much code for just a database connection problem. Narrow it down to code that is relevant and also post the connection string from your config file.
Member 9884645 14-Mar-13 10:15am    
i have posted connection string in first part of code from app.config file
Richard C Bishop 14-Mar-13 10:19am    
Thank you. Your connection string is messed up. Database should be Data Source and data source should be Initial Catalog. Data Source is the name of the database you want and the Initial Catalog is the server.
Member 9884645 14-Mar-13 10:23am    
But the same connection string is working absolutely okay in web application then why not in windows service. still if you suggesting then i will try it by doing change. I am using MS SQL server
Richard C Bishop 14-Mar-13 10:27am    
You are correct, that connection string is fine for standard security. I was providing the connection string for a windows CE device.

try with the following code:
C#
string path = Assembly.GetExecutingAssembly().Location; 
string ImgExist = Path.Combine(path, "images/" + stamp + ".jpg");


The above code will work if images is a folder in the same directory where the executable resides, else you need to use relative path which starts from the application folder.

for example if the images folder is there in one-level up as the application folder then you need to write as follows:

C#
string ImgExist = Path.Combine(path, "../images/" + stamp + ".jpg"); 


And if it inside a sub-folder (example the folder name is : resources) of application directory then you need to write as follows:

C#
string ImgExist = Path.Combine(path, "resources/images/" + stamp + ".jpg"); 


Hope this helps. :)
 
Share this answer
 
Comments
Member 9884645 15-Mar-13 9:34am    
thanks a lot once again
As your code is too long it is not so easy to find the cause of your problem.

Just try logging messages in each major steps of the code, and check where it fails. Probably this is one of the way to find the root cause of your problem.
 
Share this answer
 
Comments
Member 9884645 14-Mar-13 11:50am    
hi my cn.open is working ok.. i trace it by using eventlog. .. I guess i am doing mistake

in string ImgExist = Path.GetFullPath("~/Images/") + stamp + ".jpg"; syntax as it fins windows path..... In web application i was using server.mappath but in windows i guess problem is there.... so if we want to retrive file from specific folder which is in webservice how to retrive it....

i am bit confused how to write that syntax to get path of image folder which is in same where my .exe lies.. say Imageresizer is my service name then image folder lies in Imageresizer/Imageresizer/Image...where my exe is in Imageresizer/Imageresizer/bin/Debug/Imageresizer.exe
Chinmaya C 14-Mar-13 12:27pm    
try with the following code:

string path = Assembly.GetExecutingAssembly().Location;
string ImgExist = Path.Combine(path, "images/" + stamp + ".jpg");

The above code will work if images is a folder in the same directory where the executable resides.
Member 9884645 14-Mar-13 12:45pm    
Thanks.. its is working ohk...

but still i want to ask you if image folder is not resided in same folder where .exe reside...then which syntax i should use?
Chinmaya C 14-Mar-13 13:03pm    
then you need to use relative path which starts from the application folder.
for example if the images folder is there in one-level up as the application folder then you need to write as follows:
string ImgExist = Path.Combine(path, "../images/" + stamp + ".jpg");

And if it inside a sub-folder (example the folder name is : resources) of application directory then you need to write as follows:
string ImgExist = Path.Combine(path, "resources/images/" + stamp + ".jpg");

Hope this helps. :)
Member 9884645 15-Mar-13 8:02am    
Thanks for your guidance.. now it is working ok.. please post your answer as a solution so i can mark it....

thanks once again.... :)
From services.msc, you need to set permissions to your service in order to let it access to database server
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900