DSN Util C#(Won't create) - c#

I was following this other post --> C# DSN Util
So I have the following code. (Slightly Modified)
OdbcConnection DbConnection = null;
try
{
DbConnection = new OdbcConnection(
"DataSourceName=NEWDSN;"+
"Driver=SQL Server;" +
"Description=New DSN;" +
"Server=<NameofServer>;");
DbConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
System.Environment.Exit(0);
}
Everything seems to work fine, I get no errors but nothing is created? I have tried troubleshooting with the following techniques
I am able to create one when doing it manually in the ODBC Admin tools
When adding "DatabaseName=blah;"
I have tried many things in this field but am unable to produce anything.
EDIT:
Hmm, there may not be a way to create one using this code. DBConnection.Open seems to be my only decent option. Is it even possible to create one that will appear in the ODBC Data Source Admin?

The code and example you are using is for opening a DSN that has already been created, not for actually creating them in the first place.
You probably need something more like this example
http://www.codeproject.com/KB/database/DSNAdmin.aspx

Related

Pushing DataBase to PDA results in empty database with RAPI2

I have a WorkAboutPro 4 and on this i run an application.
This application uses an SQLlite database.
Now i also run a computer program along side it, in here i use RAPI2 to work with my handheld device.
As soon i connect my device a function triggers and it first pulls my database from my handheld to my computer.
I then do some stuff with it and go on to push it back. problem is that the database that returns is always 0kb and has no data, not even tables.
//Create my Paths
string myDevice = device.GetFolderPath(SpecialFolder.ProgramFiles);
string deviceFile = myDevice + #"\PPPM\SQL_PPPM.s3db";
string myComputer = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
string localFile = myComputer + #"\SQL_PPPM.s3db";
//Get the Database
RemoteFile.CopyFileFromDevice(device, deviceFile, localFile, true);
//Do Stuff
try
....
catch(Exception ex)
....
//Push The Database back
RemoteFile.CopyFileToDevice(device, localFile, deviceFile, true);
Now first i thought it was beccause i am not able to push a database over the connection. So i tried to pull a full database to my computer. but this works just fine.
Then i went on and placed an empty Txt file on my hadn held. pulled it, added text and pushed it and also this works fine.
So the only thing that goes wrong is when i try i push a full database back to my HandHeld resulting in an 0kb empty database.
Anyone an idea why this is?
Lotus~
Edit: if you know a beter way to detect if a device is connected and push/pull files from a PDA please let me know.
So i faced the same problem as well.
It most likely has to do with your Sqlite connections still being open.
The thing that worked out best for me was to modify my SqlDataAccess class and start using the 'using'.
Example:
using(var connection = new SQLiteConnection(ConnectionString))
{
try
{
connection.Open();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
connection.Close();
}
}
For me the same worked with DataAdapters.
Good luck in the future, and remember never throw yourself in a case of Denvercoder9. You should have answered this a long time ago.

How to create SPs, Tables, Functions and Triggers

I'm currently working on application where one of the requirements is the ability to create SP, Tables, Functions, Triggers, etc. from inside ASP.NET. The language I'm using is C# but I don't know if this is even possible. Would you mind pointing me to the right direction or provide me with some code examples?
I tried looking online but I'm unable to find any information regarding this.
#rmayer06, I followed your advice and below is my code:
protected void createproc_Click(object sender, EventArgs e)
{
string sqlscript = File.ReadAllText(Server.MapPath("~/sp_create.sql"));
try
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand(sqlscript, con);
cmd.CommandType = CommandType.Text;
con.ConnectionString = ConfigurationManager.ConnectionStrings["TCKT"].ConnectionString;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
throw new Exception("An error has occurred" + ex);
}
}
It may be possible using SqlCommand.ExecuteNonQuery(), or by using the classes in Microsoft.SqlServer namespace. I found this in a quick search: http://forums.asp.net/t/1703608.aspx/1
However, I would ask for additional clarification on your requirements if I were you. It seems odd that you would need to create SPs dynamically; generally, it is better to design them as part of the database if they are needed, as SPs will need to be optimized, debugged, etc.
On a related note, I have run database update scripts from within c#, which did create stored procedures as part of updating the database code. If that is what you are doing, I recommend the following:
Script your entire database to a single .SQL file.
Use the sqlcmd utility to execute the file against your local server. This can be done by calling System.Diagnostics.Process.Start() from the web application and supplying the necessary command-line parameters.
As a caveat, your web app process will need permissions to launch the sqlcmd process. Or as an alternative, you can use the SqlCommand class and just dump the entire contents of your SQL script into a string, which you pass to the command. I think I've done that too, and it worked.

SQL Server perform backup with C#

I've investigated the possibilities of creating database backups through SMO with C#.
The task is quite easy and code straightforward. I've got only one question: how can I check if the backup was really created?
SqlBackup.SqlBackup method returns no parameters and I don't even know if it throws any exceptions. (the only thing that I know is that it is blocking, because there's also SqlBackupAsync method)
I would appreciate any help.
you can and its very possible to do what you asked for,
but doing the backup it self using SMO its not very hard, but the hard part is managing the backup and the restore.
it would be hard to put all the code here, but its wont fit. so I will try my best to put the lines you need.
SqlBackup.SqlBackup doesn't return any value, its a void function.
but it takes one parameter which is "Server", try out the following code:
Server srvSql;
//Connect to Server using your authentication method and load the databases in srvSql
// THEN
Backup bkpDatabase = new Backup();
bkpDatabase.Action = BackupActionType.Database;
bkpDatabase.Incremental = true; // will take an incemental backup
bkpDatabase.Incremental = false; // will take a Full backup
bkpDatabase.Database = "your DB name";
BackupDeviceItem bDevice = new BackupDeviceItem("Backup.bak", DeviceType.File);
bkpDatabase.Devices.Add(bDevice );
bkpDatabase.PercentCompleteNotification = 1;// this for progress
bkpDatabase.SqlBackup(srvSql);
bkpDatabase.Devices.Clear();
I've investigated the problem using Reflector.NET (I suppose this is legal since RedGate is Ms Gold Certified Partner and Reflector.NET opens .NET libraries out of the box). As I found out the method throws two types of exceptions:
FailedOperationException - in most cases, other exceptions are "translated" (I suppose translating means creating new FailedOperationException and setting InnerException to what was actually thrown)
UnsupportedVersionException - in one case when log truncation is set to TruncateOnly and server major version is more or equal to 10 (which is sql server 2008?)
This solves my problem partially, because I'm not 100% sure that if something goes wrong those exceptions will actually be thrown.

Checking whether a database is available?

My problem involves checking if I have a valid database connection before reading from the database. If the database is down I'd like to write to a xml file instead. I have the location of the database (if it's up) at runtime so if the database was working I can create a new sqlConnection to it.
Use a typical try...catch...finally structure, and based on the specific exception type and message, decide whether you want to write to xml or not.
try
{
SqlConnection connection = new SqlConnection(DB("Your DB Name"));
connection.Open();
}
catch (Exception ex)
{
// check the exception message here, if it's telling you that the db is not available. then
//write to xml file.
WriteToXml();
}
finally
{
connection.Close();
}
I would just use something like:
using(SqlConnection conn = new SqlConnection(c)) {
conn.Open();
}
It will throw an exception if invalid. You could write to the xml in the exception.
An easy way would be to execute a simple query and see if an error occurs:
For Oracle:
SELECT * FROM DUAL
For SQL Server
SELECT 1
Basicly just some kind of relatively "free" query that will let you know that the database is up and running and responding to requests and your connection hasn't timed out.
You cannot really tell whether the DB is up and running without actually opening a connecting to it. But still, connection might be dropped while you're working with it, so this should be accounted for.

Paradox Tables in C#

I'm trying to read a Paradox 5 table into a dataset or simular data structure with the view to putting it into an SQL server 2005 table. I've trawled google and SO but with not much luck. I've tried ODBC:
public void ParadoxGet()
{
string ConnectionString = #"Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;DefaultDir=C:\Data\;Dbq=C:\Data\;CollatingSequence=ASCII;";
DataSet ds = new DataSet();
ds = GetDataSetFromAdapter(ds, ConnectionString, "SELECT * FROM Growth");
foreach (String s in ds.Tables[0].Rows)
{
Console.WriteLine(s);
}
}
public DataSet GetDataSetFromAdapter(DataSet dataSet, string connectionString, string queryString)
{
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcDataAdapter adapter = new OdbcDataAdapter(queryString, connection);
connection.Open();
adapter.Fill(dataSet);
connection.Close();
}
return dataSet;
}
This just return the error
ERROR [HY000] [Microsoft][ODBC Paradox Driver] External table is not in the expected format.
I've also tired OELDB (Jet 4.0) but get the same External table is not in the expected format error.
I have the DB file and the PX (of the Growth table) in the Data folder... Any help would be much appriciated.
I've had the same error. It appeared when I started my C# project on Win2008 64 (previos OS was Win2003 32). Also I found out that it worked fine in console apps and gave different errors in winforms. It seems that problem comes from the specifics of 32 ODBC driver working on 64-bit systems.
My solution was:
// Program.cs
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// it is important to open paradox connection before creating
// the first form in the project
if (!Data.OpenParadoxDatabase())
return;
Application.Run(new MainForm());
}
The connectionstring is common:
string connStr = #"Driver={{Microsoft Paradox Driver (*.db )}};DriverID=538;
Fil=Paradox 7.X;DefaultDir=C:\\DB;Dbq=C:\\DB;
CollatingSequence=ASCII;";
After opening connection you may close it in any place after creating first Form (if you need to keep DB closed most of time), for example:
private void MainForm_Load(object sender, EventArgs e)
{
Data.CloseParadoxDatabase();
}
After doing that you may open and close connection every time you want during execution of your application and you willn't get any exceptions.
Maybe this will help you out,
http://support.microsoft.com/support/kb/articles/Q237/9/94.ASP?LN=EN-US&SD=SO&FR=1
http://support.microsoft.com/support/kb/articles/Q230/1/26.ASP
It appears that the latest version of the Microsoft Jet Database Engine
(JDE) does not fully support Paradox unless the Borland Database Engine
(BDE) is also installed.
Try to Run all The Applications with the "Run As Administrator" privileges especially run the VS.NET with "Run As Administrator "... and I am sure your problem get solved
This isn't an answer, but more of a question: any particular reason you're trying to use C# to do the data manipulation as opposed to using SQL Server tools to load the data directly? Something like DTS or SSIS would seem like a better tool for the job.
Thanks, I'll give that a try. I wanted to use C# so I can put it on some web pages without the extra set of putting it in SQL server.

Categories