I have developed a desktop application in C# with Microsoft SQL Server Compact Edition 3.5.
It works fine when I run .exe file from solution folder (bin\release or debug) but when I tried to deploy it by creating its setup it shows unhandled exception:
You don't have permission to access CustomersDB.sdf file.
Note there is no path error it is correct.
string lokasifile = Environment.CurrentDirectory + "\\CustomersDB.sdf";
string stringkoneksi = "Data Source = \"" + lokasifile + "\"";
SqlCeConnection koneksi = new SqlCeConnection(stringkoneksi);
koneksi.Open();
SecurityException
This is nothing but caller does not have the appropriate permission.
Environment.CurrentDirectory Property
try
{
//Call Path here you will get to what the exactly error is
}
catch (Exception ex)
{
if (ex is DirectoryNotFoundException|| ex is IOException|| ex is SecurityException)
{
//Your handling here
}
else
{
throw;
}
}
Related
I am trying to access my server's IIS pool in order to recycle it through C# code.
This is my code:
static void Main(string[] args)
{
try
{
string sMachine = "MyHostName";
string sAppPool = "MyAppPoolName";
string sPath = "IIS://" + sMachine + "/W3SVC/AppPools/" + sAppPool;
Console.WriteLine(sPath);
DirectoryEntry w3svc = new DirectoryEntry(sPath, "MyUserName", "MyPassword");
w3svc.Invoke("Recycle", null);
Console.WriteLine("Application pool recycled");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
I changed the sMachine / sAppPool / UserName, Password, but in my code I send them with the real data.
When I run it on my VM I get a message
Error: Unknown Exception
I think it occurs because the permission so I run it with the administrator of the VM and run as administrator the exe file, but still I get the same error.
How could I access the IIS?
Thanks in advance.
I have used following 3 SQL Server (Version SQL Server 2008 R2) DLLs in a WPF project:
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Management.Sdk.Sfc
Microsoft.SqlServer.Smo
Project works fine on the machine on which it was developed. However if I try to move the .exe to some other machine then application gets crashed.
I have set Copy Local = True for all the 3 DLLs so that during compilation it should copy all the 3 DLLs inside Debug folder. (These DLLs are required to find out the SQL Server DATA Root Directory.)
Following the code which I am trying to execute in my App.
try
{
MessageBox.Show("trying to open connection");
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();
con = new SqlConnection(conStr);
con.Open();
MessageBox.Show("connection opened ");
var serverConnection = new ServerConnection(con);
var server = new Server(serverConnection);
var defaultDataPath = string.IsNullOrEmpty(server.Settings.DefaultFile) ? server.MasterDBPath : server.Settings.DefaultFile;
var defaultLogPath = string.IsNullOrEmpty(server.Settings.DefaultLog) ? server.MasterDBLogPath : server.Settings.DefaultLog;
string restoreSql = #"RESTORE DATABASE [MyDB]
FROM DISK = '" + this.FilePath + #"'
WITH
MOVE 'MyDB' TO '" + defaultDataPath + #"\MyDB.mdf',
MOVE 'MyDB_Log' TO '" + defaultLogPath + #"\MyDB_Log.ldf',
RECOVERY, REPLACE, STATS = 10";
SqlCommand restoreCmd = new SqlCommand(restoreSql, con);
int status = restoreCmd.ExecuteNonQuery();
completedFlag = true;
}
catch (Exception ex)
{
MessageBox.Show("Database Restore Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
if (completedFlag)
MessageBox.Show("Database restore successful.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
else
MessageBox.Show("SYSTEM ERROR: Failed restoring database.\nPlease restart SQL Server Service and try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
Not able to find out why my application is crashing.
When distributing certain packages, just including the dll within your package may not help. You need to read the distribution guidelines of those libraries.
In the case of SMO, this is what MSDN says
If you develop an application that uses SQL Server Management Objects,
you need to make sure that the necessary support files are present on
the computer with the application. The SQL Server 2008 feature pack
contains a redistributable package for the SQL Server Management
Objects.
If you have these support packages installed with your external libraries, your problem should be solved.
I have a sql database where i am string filepath and file name of some files. I am using Visual Studio 2008 as IDE and SQL Server 2005 for development.
If I am trying to execute a SQL query to get filepath it returns correct result. But when I am executing SQL query from windows application in c#, it is returning Filepath in which all \ are changed to //.
Here is the SQL query I executed from SQL Server Management Studio:
select FilePath FROM dbo.[tbl_name] WHERE SerialNo = 2;
It results in FilePath being C:\Program Files\Test\Mydoc.pdf
But when I am trying through C# windows forms code as mentioned below. I am getting a wrong value for FilePath: C://Program Files//Test//Mydoc.pdf
try
{
using (connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT FilePath FROM dbo.[tbl_name] WHERE SerialNo LIKE #Sno", connection))
{
command.Parameters.Add(new SqlParameter("Sno", Serial));
FiletoOpen = command.ExecuteScalar().ToString();
Process.Start(FiletoOpen );
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception has occured!", MessageBoxButtons.OK);
}
finally
{
connection.Close ();
}
What may be the problem?
I guess you are seeing this path in your debugger. Debugger is just escaping the path and nothing else. If you write it somewhere, like console, you will get the original path (with single backslashes).
I'm updating a C# (.NET 3.5) application to interact with an Access database, but I keep getting this error:
ERROR: Unrecognized database format
This is the code I'm using to open a connection to the database:
String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=" + filePath;
try
{
this.conn = new OleDbConnection(connectionString);
this.conn.Open();
}
catch (Exception e)
{
Console.WriteLine("ERROR: " + e.Message);
Console.WriteLine(e.ToString());
}
I know that the file path is correct. I suspect that the Provider=Microsoft.Jet.OLEDB.4.0; is incorrect. How do I find out what the database format is? I did not make the database in question, but I do have read-access to it. Thanks.
You must add Data Source , user/password parametters . You can see http://connectionstrings.com/access
I have this code:
string TmpMakat, TmpIsShakil, TmpDes;
SqlCeDataReader read;
public bool LOOK()
{
try
{
TmpMakat = "";
TmpIsShakil = "";
TmpDes = "";
Cmd.CommandType = CommandType.TableDirect;
Cmd.CommandText = "Items";
Cmd.IndexName = "A";
Cmd.SetRange(DbRangeOptions.Match, new object[] { txtMakat.Text }, null);
try
{
read = Cmd.ExecuteReader(); // <--- This is the Error
}
catch
{
MessageBox.Show("Error");
return false;
}
while (read.Read())
{
TmpMakat = read[0].ToString();
TmpIsShakil = read[1].ToString();
TmpDes = read[2].ToString();
}
read.Dispose();
if (TmpMakat == "")
{
TmpMakat = "";
TmpIsShakil = "";
TmpDes = "";
lblDes.Text = "";
lblQty.Text = "";
return false;
}
else
{
IsShakil = (TmpIsShakil == "1") ? true : false;
lblQty.Text = (IsShakil == true) ? "B" : "A";
lblDes.Text = TmpDes;
return true;
}
}
catch
{
return false;
}
}
but if there is any error - it never goes into the catch
I get this error sometime:
Error
A native exception has occurred in
myProg.exe.
Select Quit and then restart this program, or select Details
for more information.
and when I press for more Details I see this:
Error
ExceptionCode: 0xc0000005
EceptionAddress: 0x41efaf7c
Reading: 0x00000000
Faulting module: sqlcese35.dll
Offset: 0x0005af7c
ExceptionCode: 0xc0000005
That's a nasty one, AccessViolationException in .NET speak. Clearly SQL Compact is crashing, it is probably doing so in a worker thread or your catch clause would have caught it. Diagnosing this is going to be difficult but start by mistrusting the database file content, it might be corrupted. Consider an out-of-memory problem, it is bombing on a null pointer dereference. Look for updates from Microsoft.
The error happens in native code (SQL CE), so
either the .NET compact framework is unable to catch this kind of error (don't know, would be strange, but hard to ignore)
or the error happens in the first line, which is outside the try/catch block.
As you are calling a CreateCommand method, which we can assume, calls down to SQL CE, the 2nd possibility is more likely.
Can you put the assignment in the try/catch block ?
I had exactly the same error and was pulling my hair out with frustration, not getting anywhere. I references the SQL CE dlls directly and copied them all to the device during deploy, so after I read the above solution I tried to remove all the files and redeploy from scratch. That also did not work. In the end I installed SQL Server CE 3.5 SP2 directly on to the device with the CAB file found in
C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v3.5\Devices\wce500\armv4i\sqlce.wce5.armv4i.cab
(ARMv4 in my case, your's may vary). After installing this to the device everything ran fine.