У меня проблема с запуском службы Windows. Служба подключается к БД и через DataAdapter создает локальный файл XML. Затем он передает файл на FTP-сервер. Получите ошибку 1064 при попытке запустить службу.
Я проверил, и ошибка возникает при попытке создать файл XML из БД. Я использую соединение с БД, но не знаю, как это исправить.
Когда я запускаю этот код как консольное приложение, оно работает довольно хорошо, ошибок не возникает, но когда я запускаю его как сервис windows, это occuring: / Может быть, это что-то со строкой подключения? или с созданием файла XML через DataAdapter? В чем разница между консольным приложением и windows подключением службы к БД?
Чтобы проверить это, я прокомментировал часть с подключением к БД (метод Create XML ()), и она тоже работает, поэтому FTP-соединение не является проблемой.
Я пометил комментарием строку кода, которая выдает ошибку, она находится в методе Create XML ().
У вас есть полный код здесь
РЕДАКТИРОВАТЬ (решение): Если у вас возникла та же проблема, смените Сервис, чтобы использовать свой выигрышный счет. Работает без ошибок.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Timers;
namespace XMLShopService
{
public partial class XMLShopService : ServiceBase
{
Timer timer = new Timer();
//TIME MULTIPLIERS
private static int seconds = 1000; //miliseconds to SECONDS multiplier -- DON'T TOUCH --
private static int minutes = 60000; //miliseconds to MINUTES multiplier -- DON'T TOUCH --
private static int hours = 3600000; //miliseconds to HOURS multiplier -- DON'T TOUCH --
//TIME INTERVAL SETTINGS
private int timeInterval = 3; //SET HERE - time interval in (SECONDS or MINUTES or HOURS), then pick timeMultiplier below
private int timeMultiplier = minutes; //SET HERE - time format you would like to use in timer as interval (SECONDS or MINUTES or HOURS) pick one from above and implement after "="
public XMLShopService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Debugger.Launch();
WriteToFile("START : " + DateTime.Now);
CreateXML();
FtpFileUpload();
//TIMER
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Interval = timeInterval * timeMultiplier; // -- DON'T TOUCH -- Represent time interval in MILISECONDS
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("STOP : " + DateTime.Now);
}
//FUNCTIONS USED
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
WriteToFile("ReStart script at : " + DateTime.Now);
CreateXML();
FtpFileUpload();
WriteToFile("Script finished at : " + DateTime.Now);
}
private void CreateXML()
{
//XML file settings
string fileName = "file.xml"; //SET HERE - XML local file name
string localFilePath = @"path" + fileName; //SET HERE - XML local file path (full)
double priceMultiplier = 3; //SET HERE - price multiplier
//SQL Query - products codes & prices * multiplier
string queryString = "SELECT ItemCode, Price * " + priceMultiplier + " FROM database WHERE PriceList = 1 AND Price > 0";
//SQL connection string
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Server=server;" + //SET HERE - SQL Server
"Initial Catalog=database;" + //SET HERE - Server database
"Integrated Security=true";
//Creating XML file in the specific location, overwriting old file
try
{
using (SqlCommand sqlComm = new SqlCommand(queryString, conn) { CommandType = CommandType.Text })
{
WriteToFile("SQL 1: " + DateTime.Now);
SqlDataAdapter da = new SqlDataAdapter(sqlComm);
WriteToFile("SQL 2: " + DateTime.Now);
DataSet ds = new DataSet();
da.Fill(ds); //!!!---THIS IS WHERE ERROR OCCURS---!!!
WriteToFile("SQL 3: " + DateTime.Now);
ds.Tables[0].WriteXml(localFilePath);
WriteToFile("SQL 4: " + DateTime.Now);
}
WriteToFile("DB connection ok: " + DateTime.Now);
}
catch (Exception)
{
WriteToFile("ERROR - create file: " + DateTime.Now);
throw;
}
}
private void FtpFileUpload()
{
string ftpUsername = "userName"; //SET HERE - FTP username
string ftpPassword = "pass"; //SET HERE - FTP Password
string ftpFolderPath = @"ftpServerPath/test/"; //SET HERE - FTP folder dir -- TODO: TEST FOLDER PATH TO CHANGE --
string fileName = "file.xml"; //SET HERE - XML local file name
string localFilePath = @"path" + fileName; //SET HERE - XML local file dir (full)
//DELETE old file
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFolderPath + fileName);
request.Method = WebRequestMethods.Ftp.DeleteFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
WriteToFile(response.StatusDescription + " " + DateTime.Now);
}
}
//Throw on errors
catch (Exception)
{
WriteToFile("ERROR - delete old file: " + DateTime.Now);
throw;
}
//UPLOAD UpToDate file
try
{
//Set request
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFolderPath + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
//Load file
FileStream stream = File.OpenRead(localFilePath);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
//Upload file
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
WriteToFile(response.StatusDescription + " " + DateTime.Now);
}
request = null;
}
//Throw on errors
catch (Exception)
{
WriteToFile("ERROR - upload UpToDate file: " + DateTime.Now);
throw;
}
}
//SCRIPT LOGS
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog.txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}