I am trying to make my application which have aim to make backup of database on disk and also send it through ftp or mail.
So I made a research and finally I wrote project of Windows service and another project in console which is making a backup of database. Both are working well and both are written in the same Visual Studio but when I am trying to put code of making backups in Windows service it doesn't work. I can't understand why. I tried put code instead of example (which is creating a file and writing one line there and this part is working well) and I even tried to make another method to do it and then call this method.
Windows service is completely the same as here and in the SpadesAdminService class instead of
System.Diagnostics.EventLog.WriteEntry("SpadesAdminSvc",
ServiceName + "::Execute()");
I made this code (is working well - making an empty file on my disk every 5 seconds, should be written "text to file" but files are appearing !):
using (FileStream fs = File.OpenWrite("C:\\place\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
{
Byte[] napis = new UTF8Encoding(true).GetBytes("text to files"));
fs.Write(napis, 0, napis.Length);
}
My class of making back up (alone is also working well):
namespace makeBackUpConsole
{
class Program
{
static void Main(string[] args)
{
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
}
}
}
I am copying this class instead of my code to making txt files and Windows Service is not working. Here is a code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace toni.exampleService.Services
{
public class exampleAdminService : exampleServiceBase
{
public exampleAdminService()
{
this.ServiceName = "exampleAdminSvc";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
protected override void OnStop()
{
base.OnStop();
}
protected override int Execute()
{
//using (FileStream fs = File.OpenWrite("C:\\development\\toni\\dd\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
//{
// Byte[] napis = new UTF8Encoding(true).GetBytes("Dzień i godzina: " + DateTime.Now.ToString("ddMMyyyy_HHmmss"));
// fs.Write(napis, 0, napis.Length);
//}
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
return 0;
}
}
}
Of course all libraries as well linked.
Looking for any advice, please help me.
Thank you in advance and have a nice day.
edit:
Hey, problem solved.
I created a database account (not Windows account) in sql management studio and I putted this account User Id and Password directly into my code in C# in Windows Service.
Anyway maybe somebody will use my code :)
Thanks for reply.
Have you checked that a Windows Service has permissions to write a file in the location you are specifying. Services don't necessarily run as a user, so don't assume that where you can write a file your service can too.
Have you tried writing to a folder underneath c:\ProgramData?
If you don't know precisely what the problem is then you need to find out. Try adding System.Diagnostics.Debugger.Launch(); at service startup and then track the changes inside the debugger.
The Windows Service you have programmed is using "Integrated Security" for your SQL Server.
If you don't want to enter login credentials in your code, you should either set the executing user to your local account or grant the required user (e.g. LocalSystem) access to your database in your SQL Management Studio.
Usually a Windows Service is running as LocalSystem, LocalService or NetworkService. Just change the setting for your Windows Service in services.msc
Related
How to restore SQL Server backup using C#?
try
{
string test = "D:\\backupdb\\05012017_130700.Bak";
sqlcmd = new SqlCommand("Restore database EmpolyeeTable from disk='D:\\backupdb\\05012017_130700.Bak'", con);
sqlcmd.ExecuteNonQuery();
Response.Write("restore database successfully");
}
catch (Exception ex)
{
Response.Write("Error During backup database!");
}
Quite weird requerement you have right there. I´ve never heard of someone restoring a database backup from a webpage, and as #Alex K. told, it would be quite rare that the user that uses your web application have the required previleges.
Anyway, supposing that everything told above is OK, the code to restore a backup would be this:
Use this:
using System.Data;
using System.Data.SqlClient;
Code:
private void TakeBackup()
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "RESTORE DATABASE AdventureWorks FROM DISK = 'C:\AdventureWorks.BAK' WITH REPLACE GO";
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
}
This is going to work specifically for the problem you posted. Be sure to set all the parameters of your database server on the connection string, it seems from the comments on your question that you are having communication issues. You have to solve that problems before you do anything. Some tips for that:
Be sure you set all the parameters on connection string the right way
Try to connect using another tool like ODBC so you can test all parameters
Check out SQL Network settings to see if TCP/IP is enabled
I'm working on a C# project in Visual Studio 2012 on Windows 10 and Oracle 11g.
In order to connect my c# project I had to install Oracle Data Access Components_ODTwithODAC121024 and everything worked fine.
I updated the target .NET framework of my project to 3.5, and now I get this error:
Could not load file or assembly 'Oracle.DataAccess, Version=2.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. An attempt was made to load a program with an incorrect format.
After really long search and test I think that caused by incompatibility issue.
I tried to enable .NET Framework 3.5 through Programs and Features -> Turn Windows features on or off.
I tried to read reference and importing the Oracle.DataAccess.dll from
C:\app\Samer\product\11.2.0\dbhome_1\ODP.NET\bin\2.x
and I also used the Oracle.DataAccess.dll that comes with Oracle Data Access Components
My project works fine when I disable the method that deals with oracle commands.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace backup_Check_v01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Read_const_File();
}
//Method for Reading Constants File
public void Read_const_File()
{
string File_Path;
File_Path = #"s:\test\result";
Get_File_info(File_Path);
}
//Method for reading file information ex(File Name,Size,and creation date..etc)
public void Get_File_info(string para1)
{
FileInfo info = new FileInfo(para1);
richTextBox1.AppendText(Environment.NewLine + "File Name: " + Path.GetFileNameWithoutExtension(info.Name));
richTextBox1.AppendText(Environment.NewLine + "File Size (Bytes): " + info.Length.ToString());
richTextBox1.AppendText(Environment.NewLine + "Creation Time: " + info.CreationTime.ToString());
richTextBox1.AppendText(Environment.NewLine + "Last Access: " + info.LastAccessTime.ToString());
richTextBox1.AppendText(Environment.NewLine + " **************************** ");
search_for_string(para1);
}
public void search_for_string(string para2)
{
string keywords = "sb_0501_Thu.dmp";
string oradb = "Data Source=sb_1901;User Id=sb_1901;Password=sb00;";
StreamReader sr = new StreamReader(para2);
richTextBox1.AppendText(Environment.NewLine + sr.ReadToEnd());
if (!richTextBox1.Text.Contains(keywords))
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',0,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
else
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',1,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
}
}
}
You refer to ODP.NET version 2.121.2.0. but it seems you have installed Oracle Client 11.2. The versions have to match with each other (at least the major version number)
Open your *.csproj file and set reference of Oracle.DataAccess like this:
<Reference Include="Oracle.DataAccess">
<SpecificVersion>False</SpecificVersion>
</Reference>
Attributes like Version=... or processorArchitecture=... are not required. Your application will load the correct Oracle.DataAccess.dll depending on selected architecture and target .NET framework
Am trying to convert my console application, which generates pdf reports, into a windows service. My code is as follows. Am I on the right direction? I installed this service and start/stop works fine but no report is generated! The console app alone works fine to generate Output.pdf. My aim is to Generate ouput when the service starts.
class Program : ServiceBase
{
public Program()
{
this.ServiceName = "My PdfGeneration";
}
static void Main(string[] args)
{
ServiceBase.Run(new Program());
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("My PdfGeneration Started");
//base.OnStart(args);
//Customise parameters for render method
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty; //"application/pdf";
string encoding = string.Empty;
string filenameExtension = string.Empty;
string deviceInfo = "<DeviceInfo>" + "<OutputFormat>PDF</OutputFormat>" + "<PageWidth>15in</PageWidth>" + "<PageHeight>11in</PageHeight>" + "<MarginTop>0.5in</MarginTop>" + "<MarginLeft>0.5in</MarginLeft>" + "<MarginRight>0.5in</MarginRight>" + "<MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>";
//Create a SqlConnection to the AdventureWorks2008R2 database.
SqlConnection connection = new SqlConnection("data source=localhost;initial catalog=pod;integrated security=True");
//Create a SqlDataAdapter for the Sales.Customer table.
SqlDataAdapter adapter = new SqlDataAdapter();
// A table mapping names the DataTable.
adapter.TableMappings.Add("View", "Route_Manifest");
// Open the connection.
connection.Open();
Console.WriteLine("\nThe SqlConnection is open.");
// Create a SqlCommand to retrieve Suppliers data.
SqlCommand command = new SqlCommand("SELECT TOP 10 [RouteID],[FullTruckID],[DriverID],[DriverName],[StopID],[CustomerID],[CustomerName],[InvoiceID],[last_modified],[Amount] FROM [pod].[dbo].[Route_Manifest]", connection);
command.CommandType = CommandType.Text;
// Set the SqlDataAdapter's SelectCommand.
adapter.SelectCommand = command;
command.ExecuteNonQuery();
// Fill the DataSet.
DataSet dataset = new DataSet("Route_Manifest");
adapter.Fill(dataset);
//Set up reportviewver and specify path
ReportViewer viewer = new ReportViewer();
viewer.ProcessingMode = ProcessingMode.Local;
viewer.LocalReport.ReportPath = #"C:\Documents and Settings\xxxxx\My Documents\Visual Studio 2008\Projects\PdfReportGeneration\PdfReportGeneration\Report.rdlc";
//specify the dataset syntax = (datasetofreport.rdlc,querydataset);
viewer.LocalReport.DataSources.Add(new ReportDataSource("podDataSet_Route_Manifest", dataset.Tables[0]));
//Now render it to pdf
try
{
byte[] bytes = viewer.LocalReport.Render("PDF", deviceInfo, out mimeType, out encoding, out filenameExtension, out streamIds, out warnings);
//output to bin directory
using (System.IO.FileStream fs = new System.IO.FileStream("output.pdf", System.IO.FileMode.Create))
{
//file saved to bin directory
fs.Write(bytes, 0, bytes.Length);
}
Console.WriteLine("\n YEP!! The report has been generated:-)");
/* //Save report to D:\ -- later
FileStream fsi = new FileStream(#"D:\output.pdf", System.IO.FileMode.Create);
*/
}
catch (Exception e)
{
Console.WriteLine("\n CHEY!!!this Exception encountered:", e);
}
// Close the connection.
connection.Close();
Console.WriteLine("\nThe SqlConnection is closed.");
Console.ReadLine();
}
protected override void OnStop()
{
EventLog.WriteEntry("My PdfGeneration Stopped");
base.OnStop();
}
}
I would advise that you move the code in your OnStart event to a separate thread, since
your service will need to start in a timely matter, else it can potentially time out
on start up.
E.g
using System.ServiceProcess;
using System.Threading;
namespace myService
{
class Service : ServiceBase
{
static void Main()
{
ServiceBase.Run(new Service());
}
public Service()
{
Thread thread = new Thread(Actions);
thread.Start();
}
public void Actions()
{
// Do Work
}
}
}
You might also want to check if the executing user (user context in which the service runs)
has rights to the folder you're writing to etc.
You will also need to write your errors to the event log instead of writing them to the
console window like seen in your snippet (your code is swallowing exceptions at the moment
thats why you cant pin point whats going wrong)
Read more over here:
C# Basics: Creating a Windows Service
Yes and no, what you should do is to define what OperationContract you are in the process of exposing by defining an interface.
For instance see this on channel 9:
http://channel9.msdn.com/Shows/Endpoint/Endpoint-Screencasts-Creating-Your-First-WCF-Service
you should define this service is a separate library assembly (because tomorrow you'll want to host this service somewhere else and very likely while developing, in a console application).
consuming the service you need to consider if it should be from an asp.net web page, a windows forms program or a console utility, really depending on your consumer scenario you'd want to externalize the actual pdf functionality in a separate class (in same library assembly) so that the day you want to just be able to do that in one of you other programs, it will not have to communicate with a wcf service somewhere on the network, though such a thing is nifty in itself it affects performance to integrate across process to a limited degree.
I know I have done this a few times before but for the life of me can't remember how.
I have a database I have created and I want to make a software that only inputs information into the database. The program works but my sql connection is the problem. So to test it out I basically tried to do it direct inserting hard-coded info but it still will not go. where am I going wrong?:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.Sql;
namespace InventoryTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static void CreateCommand()
{
SqlConnection myConnection = new SqlConnection("User Id=Jab" + "password=''" + "Data Source=localhost;" + "Trusted_Connection=yes;" + "database=InventoryTracker;" + "Table=Inventory;");
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO Inventory (ItemName, SerialNumber, Model, Department, Quantity, Notes) " + "Values (string,string,string,string, 1, string)", myConnection);
}
}
}
Thank you in advance! :-)
Your sql connection string is messed up, you need semi-colons between all parameters and your parameters are messed up too. I.e., something like
"Server=localhost;Database=InventoryTracker;Trusted_Connection=True;"
You are mixing trusted mode and specifying the user id -- trusted connection means to use your windows login credentials.
TableName does not go in the connection string.
This site is great for connection string examples http://www.connectionstrings.com/sql-server-2008
You SQL command, "INSERT INTO Inventory (ItemName ..." is pretty messed up too. Should be something like
INSERT INTO Inventory (ItemName ...) values(#ItemName ...)
You then pass in the values like
myCommand.Parameters.Add("ItemName", SqlType.VarChar).Value = "Dozen Eggs";
See Insert data into SQL Server from C# code for a simple example
Just use the SqlConnectionStringBuilder class.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx
Instead of:
"User Id=Jab" + "password=''" + "Data Source=localhost;" + "Trusted_Connection=yes;" + "database=InventoryTracker;" + "Table=Inventory;");
Try:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.UserID = "Jab";
builder.Password = "";
builder.DataSource = "localhost";
builder.InitialCatalog = "InventoryTracker";
// Don't put table name in your connection string
string connection_str = "Data Source = localhost ; uid = db_user; pwd = db_pass; database = db_name; ";
conn = new SqlConnection(connection_str);
conn.Open();
Try changing
"User Id=Jab" + "password=''" + "Data Source=localhost;" + "Trusted_Connection=yes;" + "database=InventoryTracker;" + "Table=Inventory;"
to
"User Id=Jab; " + "Password=''; " + "Data Source=localhost; " + "Trusted_Connection=yes; " + "Initial Catalog=InventoryTracker;"
(Changed upper/lower case, "Database" to "Initial Catalog", removed "Table" and added ";")
Also, you might want to try replacing "Data Source" by "Server".
Don't forget to call myCommand.ExecuteNonQuery to get it to actually execute your query. Without this, you are just creating a command, but not running it.
I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. I'm now able to connect the program with the database but not to recover the data that are in it. Here is my code :
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
Console.WriteLine("Field "+i);
Console.WriteLine("\t{0}",reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Console.WriteLine("Hello world");
string x = Console.ReadLine();
}
static private string GetConnectionString()
{
return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
+ "Integrated Security=SSPI";
}
}
}
But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method.
What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid).
I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that).
Thanks !
Your code should work.
A possible cause is: You are looking at a different database.
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code.