SQL Backing up with SMO & C#? - c#

I'm using the following code to back up a SQL Database :
void BackupDatabase(string sConnect, string dbName, string backUpPath)
{
using (SqlConnection cnn = new SqlConnection(sConnect))
{
cnn.Open();
dbName = cnn.Database.ToString();
ServerConnection sc = new ServerConnection(cnn);
Server sv = new Server(sc);
// Create backup device item for the backup
BackupDeviceItem bdi = new BackupDeviceItem(backUpPath, DeviceType.File);
// Create the backup informaton
Microsoft.SqlServer.Management.Smo.Backup bk = new Backup();
bk.PercentComplete += new PercentCompleteEventHandler(percentComplete);
bk.Devices.Add(bdi);
bk.Action = BackupActionType.Database;
bk.PercentCompleteNotification = 1;
bk.BackupSetDescription = dbName;
bk.BackupSetName = dbName;
bk.Database = dbName;
//bk.ExpirationDate = DateTime.Now.AddDays(30);
bk.LogTruncation = BackupTruncateLogType.Truncate;
bk.FormatMedia = false;
bk.Initialize = true;
bk.Checksum = true;
bk.ContinueAfterError = true;
bk.Incremental = false;
// Run the backup
bk.SqlBackup(sv);
}
}
In my system (Win7 x64) it works fine but in destination system (WinXP SP3 x86) I receive the below error :
How can I fix it ?
Thanks.

If you check out the assembly directory on the Win7 machine (GAC) you'll see an entry called Microsoft.SqlServer.ConnectionInfo. (Browse to %windir%\assembly) On my machine it looks like this:
In my case I'm using version 10.0.0.0. In your case, you will at least see version 9.0.242.0 as that is what your program is compiled against (I find it unlikely that you're not referencing the dll from the GAC). If you don't have the same version installed on both machines, you've spotted the problem and you need to update the client library accordingly. I think it's likely that you have a newer version running on the XP machine, since you just installed 2008 there.
If you need more help after checking this out, you can comment here.

The sql server dll's for 32bit and 64bit are different.
It looks like your project is referencing the 64 bit dll's. When you try and run it on a machine with only 32bit dll's available you get a "file not found" / "could not load dll" type error.
If you want this to work on a 32 bit machine you should reference the 32bit version of sql server dll's.

Related

corrupted resources in wince application using Compact Framework 3.5

I'm maintaining a windows ce form application developed on compact framework 3.5
The problem that i'm struggling with is that the application running on a windows ce 6.0 device after a few days of working crashes. It presents an exception:
SerializationException 255 at Systems.Resources.ResourceReader.ParseMessageEnd() at
System.Resources.ResourceReader.LoadBitmap(Int 32 typeIndex) etc
I've used then .Net Reflector to analyse the exe file that runs on the device and I found out that some resources are corrupted and they have a value: Invalid resource TypeCode '-1' and the type is System.BadImageFormatException, mscorlib, Veersion=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 whilst the non corrupted resources have Version=2.0.0.0
It's really strange how the files get corrupted and the version changes.
I also found in the code a 200ms timer that runs forever and in that timer there was also this code which caused a lagging in the ui:
if (Global.ParSotteraneiQuadro.typepompa == ClParSottQuadro.EnTipoPompa.PNEUM)
{
ImagesMOTORE[0] = Resources.pump_OFF;
ImagesMOTORE[1] = Resources.pump_OFF;
ImagesMOTORE[2] = Resources.pump_ON;
ImagesMOTORE[3] = Resources.pump_ON;
btPompa.ImageBack = Resources.pump_OFF;
btPompa.ImageFore = Resources.pump_ON;
MemImageMOTORE = new ClassMemImage(ImagesMOTORE);
ImagesTempWait[0] = Resources.anim12_230;
ImagesTempWait[1] = Resources.anim22_230;
ImagesTempWait[2] = Resources.anim32_230;
ImagesTempWait[3] = Resources.anim42_230;
ImagesTempWait[4] = Resources.sfondo_arancio; // arancione vuoto
ImagesTempWait[5] = Resources.sfondo_red; // rosso vuoto
ImagesTempWait[6] = Resources.warning_230;
ImagesTempWait[7] = Resources.ok_230;
ImagesTempWait[8] = Resources.eco_top;
ImagesTempWait[9] = Resources.abil_pompa_pump;
ImagesTempWait[10] = Resources.abil_24VOLT_sfumato;
ImagesTempWait[11] = Resources.ok_230_giallo;
MemImageWaitTemp = new ClassMemImage(ImagesTempWait);
}
else
{
ImagesMOTORE[0] = Resources.motor_OFF;
ImagesMOTORE[1] = Resources.motor_OFF;
ImagesMOTORE[2] = Resources.motor_ON;
ImagesMOTORE[3] = Resources.motor_ON;
btPompa.ImageBack = Resources.motor_OFF;
btPompa.ImageFore = Resources.motor_ON;
MemImageMOTORE = new ClassMemImage(ImagesMOTORE);
ImagesTempWait[0] = Resources.anim12_230;
ImagesTempWait[1] = Resources.anim22_230;
ImagesTempWait[2] = Resources.anim32_230;
ImagesTempWait[3] = Resources.anim42_230;
ImagesTempWait[4] = Resources.sfondo_arancio; // arancione vuoto
ImagesTempWait[5] = Resources.sfondo_red; // rosso vuoto
ImagesTempWait[6] = Resources.warning_230;
ImagesTempWait[7] = Resources.ok_230;
ImagesTempWait[8] = Resources.eco_top;
ImagesTempWait[9] = Resources.abil_pompa;
ImagesTempWait[10] = Resources.abil_24VOLT_sfumato;
ImagesTempWait[11] = Resources.ok_230_giallo;
MemImageWaitTemp = new ClassMemImage(ImagesTempWait);
}
Has someone faced something like this? Thank you for your help
IIRC resources are loaded in writable memory, this means that application may overwrite that data if the pointers are used in the wrong way. Usually you don't access pointer directly in .NET, but those "Mem" classes may need some more investigation.
And just a small not on performances, maybe all the assignments and allocations should be done only if Global.ParSotteraneiQuadro.typepompa has changed since the last check.
To autorun from external storage on insert:
"Auto-Run Applications on Compact Flash Cards
Starting with Windows CE 3.0 it is possible to have an application run from a Compact Flash memory card when it is inserted into a device. This allows an application to auto-install from a Compact Flash card.
To set an application to be auto-run, you must place the application in aspecific folder for the CPU targeted by your application. The folder name isbased on the CPU number returned in the dwProcessorType member of theSYSTEM_INFO structure returned from calling GetSystemInfo. Table 3.7 shows the possible values and their associated constants.
Constant
Value
PROCESSOR_MIPS_R4000
4000
PROCESSOR_HITACHI_SH3
10003
PROCESSOR_HITACHI_SH3E
10004
PROCESSOR_HITACHI_SH4
10005
PROCESSOR_MOTOROLA_821
821
PROCESSOR_SHx_SH3
103
PROCESSOR_SHx_SH4
104
PROCESSOR_STRONGARM
2577
PROCESSOR_ARM720
1824
PROCESSOR_ARM820
2080
PROCESSOR_ARM920
2336
PROCESSOR_ARM_7TDMI
70001
Table 3.7. Processor values and associated constants
Thus, if you want your application to auto-run and the application is compiled for MIPS, you should rename your application to autorun.exe and place it in a folder called \4000, for example, \4000\autorun.exe.
If your application is compiled for CEF (Common Executable Format), you should place the autorun.exe file in a folder called \0, for example, \0\autorun.exe.
The application autorun.exe is passed the command line parameter "install" when a Compact Flash card is inserted, and with the command line parameter "uninstall" when the card is removed. This allows your autorun.exe application to uninstall itself when the card is removed. ..."
[From book: Windows CE 3.0 Application Programming]

Pythonnet Runtime Error using C# dll (Database Incompatibility)

enter image description hereI am using a C# dll using pythonnet on python 2.7.13 (which uses other dll files and .mdb database files) to make some technical calculations. This dll files does not have a good documentation (only namespaces, class and method names). Well the program in most PC Works Fine but in all office computers it throws a runtime Error from Dll files (my doubt is connection with database). This dll files are compiled to target .NET 4.0 (in office computers is installed .NET 4.7.1 or other versions newer than 4.0) and EntityFramework is also being used (programs target 5.0 and this is a dll file in program folder, but in office computers is installed EntityFramework 6.2 tool). Microsoft database Engine 2010 is also installed in those computers.
In every other computer that I have tested the program it works perfectly. In office computers I found a group of input data for which program works, but anyway this is not correct because it should work also for the default data.
To make tests in office computers I have compiled python code using PyInstaller (I repeat, compiled version work fine in other PCs).
I am using .NET Reflector to decompile dll files and programs Exception to find the Error. The method that throws Exception is in the following code.
Thanks in advance!
public int LoadRanghiAmmessi(int[] vRanghi, string geometria)
{
int index = 0;
CrConnection connection = new CrConnection(this.PathDB);
string query = "SELECT * FROM RanghiAmmessi WHERE (Geometria='" + geometria + "') ORDER BY NRanghi";
OleDbDataReader recordset = connection.GetRecordset(query, #"\Coils.mdb;");
if (!recordset.HasRows)
{
if (recordset != null)
{
recordset.Close();
}
query = "SELECT * FROM RanghiAmmessi WHERE (Geometria='*') ORDER BY NRanghi";
recordset = connection.GetRecordset(query, #"\Coils.mdb;");
while (recordset.Read())
{
vRanghi[index] = int.Parse(recordset["NRanghi"].ToString());
index++;
}
if (recordset != null)
{
recordset.Close();
}
}
return index;
}
public OleDbDataReader GetRecordset(string query, string NomeDB)
{
string connectionString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + this.PathDB + NomeDB + "Jet OLEDB:Database Password=123456";
this.ChiudiConnessioni();
this.conn = new OleDbConnection(connectionString);
OleDbCommand command = new OleDbCommand(query, this.conn);
try
{
this.ApriConnessione();
return command.ExecuteReader();
}
catch (Exception exception)
{
exception.Message.ToString();
this.ChiudiConnessioni();
return null;
}
}
After many tests I found out that the program is working also in other PC after declaring some objects like function parameters and after compiling running the program as compatible with Windows 7. Before the objects were created like variables and those variables were passed as parameters, (in this case, reasonably the first thought is that the problem is "pass by reference" mechanism and that some values are not inserted in the right mode, but this is not the case because:
- the same exactly code did function very well in most PC (compatibility
problem)
- the same exactly mechanism is used to specify the objects attributes and
to make calculations
In this conditions I would say that it is not clear where the problem was. In the first version installing the SQL Server Express made possible for the program to work well even without last modifications.
Umm... given the details that it works fine on "Other PC", I am guessing that the problem is your so-called database. I don't see in any way, however, how anyone could be certain at what the problem is until it is solved.

SEHException on OleDb connection open

I'm developing a small application that will simplify logging, it does so by adding some inputs to an MS Access database through OleDB.
let private conn = new OleDbConnection(connectionString)
let private submitCmd date wins =
let cmd = new OleDbCommand("INSERT INTO ArenaStats ([Date], [Wins]) VALUES (#Date, #Wins)",
Connection = conn, CommandType = CommandType.Text)
["#Date", box date; "#Wins", box wins]
|> List.iter (cmd.Parameters.AddWithValue >> ignore)
cmd
let private submit date wins =
try
conn.Open()
(submitCmd date wins).ExecuteNonQuery() |> ignore
finally
conn.Close()
[<CompiledName "AddEntry">]
let addEntry(date:DateTime, wins:int) =
submit date wins
Now testing this through FSI works just as expected. However, when I consume this API from a C# WPF project it will throw an SEHException at conn.Open(). I am really scratching my head over why this is happening.
Edit
As suggested, I have also tried to implement the same code purely in C# and in the same project, it will throw the same exception at the same place but I am posting the code below for reference.
class MsAccessDatabase : IArenaWinsDatabase {
private OleDbConnection connection = new OleDbConnection(connectionString);
private OleDbCommand SubmitCommand(DateTime date, int wins) {
return new OleDbCommand("INSERT INTO ArenaStats ([Date], [Wins]) VALUES (#Date, #Wins)") {
Connection = connection,
CommandType = System.Data.CommandType.Text,
Parameters = {
new OleDbParameter("#Date", date),
new OleDbParameter("#Wins", wins)
}
};
}
public void Submit(DateTime date, int wins) {
try {
connection.Open();
SubmitCommand(date, wins).ExecuteNonQuery();
}
finally {
connection.Close();
}
}
}
With some help from Philip I was able to figure it out. It seems that by default FSI is configured to run in 64-bit by default while the WPF project is set to "prefer 32-bit". Changing the target platform for the WPF project to 64-bit resolved the issue.
When trying to run the following code:
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", FilePath);
OleDbConnection OleDbConnection = new System.Data.OleDb.OleDbConnection(connectionString);
OleDbConnection.Open();
An SEHException exception is thrown at runtime, with the error message 'External Component has thrown an Exception'
This will usually occur when the build configuration platform in Visual Studio is incorrect, this can occur in both build configuration platforms, x86 and x64.
This is due to a mismatch between the build configuration platform of your project and the Microsoft Access Database Engine which is installed on your machine.
In order to resolve this error:
Change the build configuration platform in Visual Studio - make sure it matches the Microsoft Access Database Engine version on your machine
Recompile and run your project
The run time error should now be resolved
I know this is a really old thread, but I just ran into the same problem with a different solution.
When I installed the Access Database Engine 2016 Redistributable (x64) for the ACE provider the installer gave me an error that VCRUNTIME140.DLL wasn't installed, but the installer completed anyways and the ACE provider was available.
Uninstalling the Access Database Engine, installing the VC++ 2015 Redistributable R3 (https://www.microsoft.com/en-us/download/confirmation.aspx?id=52685), then re-installing the Access Database Engine solved the problem.

Crystal Report Connection Failed After Refresh Report

I have build an Report application using C# and Crystal Report
I build program with Formula Selection to Change Query when User need to Filter the report.
The program build in Windows 7.
In the windows 7 program is running well as I needed, data and anything is shown like I needed.
But I need to run in Windows XP.
I try to filter date into to day.
The problem is on CrystalReportViewer RefreshReport();
If I don't use that function data on report doesn't refresh, but if I use that function The connection failed to logon
Here is the code:
skr = DateTime.Now.ToString("yyyy/MM/dd");
dp = new DailyParking();
dp.SetDatabaseLogon("user", "passwd", "host", "dbname");
repotviewer.ReportSource = dp;
repotviewer.SelectionFormula = "Date({transaksi1.masuk})=Date('" +skr+ "') ";
repotviewer.RefreshReport();
repotviewer.Refresh();
The answer is, Install the Another MySql Connector which compatible in XP, after that create the connection in MyODBC.
Change The code like here:
skr = DateTime.Now.ToString("yyyy/MM/dd");
dp = new DailyParking();
dp.SetDatabaseLogon("user", "passwd", "host", "dbname");
dp.RecordSelectionFormula = "Date({transaksi1.masuk}) = Date('" + skr + "') ";
repotviewer.ReportSource = dp;
repotviewer.Refresh();
Change the MySQL.Data reference with new MySQL connector same with installed in XP and Rebuil Program.

Unable to execute script from c# using smo

I have developed a C# Windows application in which I need to create a database on client machine for which I have created a script file and installed SQL Server 2008 R2 on client machine.
But when I execute script from my code it always shows an error:
Failed to connect database.
I have added referenced the SMO assemblies from
C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
And my code is :
string sqlConString = #"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=mydatabase;Data Source=(local)";
FileInfo file = new FileInfo(dbPath);
string script = file.OpenText().ReadToEnd();
SqlConnection con = new SqlConnection(sqlConString);
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
How about something like this:
using (SqlConnection cnn = new SqlConnection(sqlConString))
{
var cmds = File.ReadAllText(#"path\to\file").Split(new string[] { "GO" },
StringSplitOptions.RemoveEmptyEntries);
cnn.Open();
foreach (var cmd in cmds)
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.ExecuteNonQuery();
}
}
}
With this approach you get what you want, the script gets executed, but you don't have to use the slow and bloated SMO interface. Further, you're leveraging the using statement so you don't have to worry about unmanaged resources being left open.
Now, to address the failed to connect to database..., which I clearly missed the first time I read it, if that's happening that means this:
Initial Catalog=mydatabase;Data Source=(local)
is likely not right. And if it is, your server may not be accepting Windows Authentication.
I don't know the setup of your local machine, but it's likely that the server is (local)\SQLEXPRESS.

Categories