Windows服务未与SQL数据库连接且未给出任何错误 [英] Windows service not connecting with SQL database and not giving any error

查看:83
本文介绍了Windows服务未与SQL数据库连接且未给出任何错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码创建了Windows服务。我能够成功安装并开始处理。它还记录事件日志记录。我可以从服务器资源管理器中看到它,但它不能完成我的预期任务。



我想在连接字符串调用和声明的某处我错了。我已将我的连接字符串存储在app.config文件中,如下所示:



我想每隔15分钟就开始服务一次。但我的代码工作不正常。

当我开始服务时事件日志消息服务开始

每隔15分钟显示一次 - 服务运行

当我停止服务它显示 - 服务停止



当它显示正在运行应用时它应该执行以下代码从数据库中检索数据,处理它并再次存储它类型.....



我的代码如下。请帮助我,我被困在里面。我也尝试调试它,但它没有给出任何错误。我的下面的代码在asp.net web应用程序中运行正常。



请在这方面帮助我。在此先感谢。



 <?  xml     version   =   1.0    encoding   =  utf-8    >  
< < span class =code-leadattribute> configuration >
< connectionStrings >
< add 名称 = b1 connectionString = < span class =code-keyword> data source = server; Trusted_Connection = False; database = nilam; User ID = e64; Password = 35ixtyF0ur < span class =code-attribute> providerName = System.Data.SqlClient / >
< span class =code-keyword>< / connectionStrings >
< / configuration >







 使用系统; 
使用 System.Collections.Generic;
使用 System.ComponentModel;
使用 System.Data;
使用 System.Diagnostics;
使用 System.Linq;
使用 System.ServiceProcess;
使用 System.Text;
使用 System.Data.Sql;
使用 System.Data.SqlClient;
使用 System.Reflection;
使用 System.Configuration;
使用 DotNetHelpers.UltimateImageResizer;
使用 System.IO;
使用 System.Timers;
使用 System.Threading;

命名空间 ImageResizerService
{
public partial class Service1:ServiceBase
{
私人 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();
}
受保护 覆盖 void OnStart( string [] args)
{
scheduleTimer1.Interval = 15 * 60 * 1000 ;
scheduleTimer1.Enabled = true ;
scheduleTimer1.Start();
scheduleTimer1.Elapsed + = new ElapsedEventHandler(ResizeImages1);
// 线程t =新线程(新的ThreadStart(this.ResizeImages1)); //(new Thread(()=> DoLongRunningStartupWork()){IsBackground = true})。Start();
// t.Start();
eventLog1.WriteEntry( 服务已开始);
}
受保护 覆盖 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( 属性);
adptPro.Fill(dsPro, 属性);

string sImg = 从propertyImages;选择img_no,img_name,create_date,modify_date,img,flag
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 ]。行[ IPRO];
for int jPro = 0 ; jPro < zPro; jPro ++)
{
mid = mid + 0;
}

int fileNo = 10 ;
for int i = 1 ; i < = fileNo; i ++)
{
if (我< = 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 ]行[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 = ;
}
其他
{
flag = false ;
}
if (flag == true
断裂;
}

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( 选择img_name,img from propertyImages其中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( 选择img_name,img from propertyImages其中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();
}
}
}

解决方案

尝试使用以下代码:

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





如果图像是可执行文件所在的同一目录中的文件夹,则上述代码将起作用,否则您需要使用从应用程序开始的相对路径夹。



例如,如果images文件夹位于应用程序文件夹的一级,那么你需要按如下方式编写:



  string  ImgExist = Path.Combine(path,  ../ images / + stamp +   .JPG); 





如果它在应用程序目录的子文件夹(例如文件夹名称是:resources)内,那么你需要写如下:



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





希望这会有所帮助。 :)


由于您的代码太长,找不到问题的原因并不容易。



试试看在代码的每个主要步骤中记录消息,并检查它失败的位置。这可能是查找问题根本原因的方法之一。


从services.msc,您需要设置服务权限才能让它访问数据库服务器

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 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>




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();
        }
    }
}

解决方案

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, 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:

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. :)


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.


From services.msc, you need to set permissions to your service in order to let it access to database server


这篇关于Windows服务未与SQL数据库连接且未给出任何错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆