No read permission on MSysObject error - c#

I am trying to connect to an MS Access database (.mdb) through OleDb. My query is
SELECT * FROM ListQueries
which fetches me the error
SQL Execution Error.
Executed SQL Statement: SELECT * FROM ListQueries
Error Source: Microsoft JET Database Engine
Error Message: Records cannot be read; No read permission on 'MSysObjects'.
Then I tried this answer, but it did not help. Then I saw another answer says to do this.
strDdl = "GRANT SELECT ON MSysObjects TO Admin;"
CurrentProject.Connection.Execute strDdl
I do not know how to implement that in my web project. Was writing something like this as per this suggestion by #HansUp
Alternatively, it should work from c# if you run it from an OleDb connection to the Access db
The code is,
OleDbConnection con;
using (con = new OleDbConnection(Connection.connectionString()))
{
con.Open();
using (var com = new OleDbCommand("GRANT SELECT ON MSysObjects TO Admin", con))
{
com.ExecuteNonQuery();
}
using (var com = new OleDbCommand("Select * from ListQueries", con))
{
using (var dr = com.ExecuteReader())
{
while (dr.Read())
{
qryList.Add(SQLReaderExtensions.SafeGetString(dr, "Name"));
}
dr.Close();
}
}
con.Close();
}
The first com.ExecuteNonQuery() gives me this error.
Cannot open the Microsoft Jet engine workgroup information file.
I would really like to know how to grant permission for an OleDb call to work. Any suggestions will be wonderful
P.S: BTW, I am using MS Access 2010.

I strongly suggest that you do not use MS Access system objects. There are other and better ways to get the information.
You have a choice of ADO and DAO. Which would you prefer? Note that in ADO there is a difference between action (adSchemaProcedures) and select queries (adSchemaViews).
For example,
public static List<string> GetAllQueriesFromDataBase()
{
var queries = new List<string>();
using (var con = new OleDbConnection(Connection.connectionString()))
{
con.Open();
var dt = con.GetSchema("Views");
queries = dt.AsEnumerable().Select(dr => dr.Field<string>("TABLE_NAME")).ToList();
}
return queries;
}

Related

SQL request working fine in SQL Server Management Studio but returning an error when send with sqlCommand C#

I have this statement:
SELECT [nozzles].[nozzle_tag],[nozzles].[id]
FROM [dispensers]
INNER JOIN [nozzles]
ON [dispenser_id] = [dispensers].[id]
INNER JOIN (SELECT * FROM assets
WHERE [i4_Device_Name] = 'EH004T_SOURCE2'
AND [i4_site_name] = 'Les Loges - H2e Station (EH004R)')assets
ON [asset_id] = [assets].[id]
WHERE [dispenser_tag] ='Dispenser 2';
It works perfectly fine when I execute it inside SSMS.
The problem is, when run this SQL by using SQLcommand, I get an error with this message:
Incorrect syntax near 'Loges'.
I don't understand why.
The command above is extracted from a log file, it is exactly what is send using SQLCommand.
C# code is:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(HySoSQLCommandBuilder.GetAllNozzleOfDispenser(locationID, dispenserTag), connection))
{
logger.Info("SQL request {request}", HySoSQLCommandBuilder.GetAllNozzleOfDispenser(locationID, dispenserTag));
using (SqlDataReader reader = command.ExecuteReader())
{
try
{
while (reader.Read())
if (reader.HasRows)
{
list.Add(new nozzle((string)reader["nozzle_tag"], (int)reader["id"]));
}
}
catch { }
}
}
With HySoSQLCommandBuilder.GetAllNozzleOfDispenser() being fairly straight forward:
public static string GetAllNozzleOfDispenser(AssetLocationID assetLocation, string dispenserTag)
{
return $#"SELECT [nozzles].[nozzle_tag],[nozzles].[id]
FROM [dispensers]
INNER JOIN [nozzles]
ON [dispenser_id] = [dispensers].[id]
INNER JOIN (SELECT * FROM assets
WHERE [i4_Device_Name] = '{assetLocation.i4DeviceName}'
AND [i4_site_name] = '{assetLocation.i4SiteName}')assets
ON [asset_id] = [assets].[id]
WHERE [dispenser_tag] ='{dispenserTag}';";
}
None of the injected values are accessible from outside the code. They do not come form a editable field accessible from a user. If SQL injection happens, then that means that it is in the source, done by someone that worked on the code, and can already do whatever they want to the database without the need to encode an SQL injection.
changed the code so it uses SQLparameters instead and now it's working. I don't understand why it wasn't working and that annoy me alot, because fixing an issue without understanding it is not how it should work. but at least now it works.

Open database into application c#

I have added a SQL Server .mdf database file to my C# application, but when I try to connect with this code, the program causes a connection error.
CODE:
DataSet data;
string con = "Data Source=dbinterno.mdf;";
string queryString = "Select * FROM Dati";
try
{
using (SqlConnection connection = new SqlConnection(con))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
data = new DataSet();
adapter.Fill(data);
MessageBox.Show(data.ToString());
connection.Close();
}
}
catch
{
MessageBox.Show("\n Problemi di connessione al database");
}
The error is:
ERROR IMAGE
Here are a couple observations:
Your connection string will need to be modified. Try using
string con = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
using Windows Authentication or this:
string con = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"; using standard security, Source: connectionstrings.com. This should be managed some other way than in code as well. Desktop applications can be de-compiled, and if the password changes, you would need a rebuild. In a ASP.NET application, Microsoft advises to use a web.config file or in the windows registry using a custom subkey.
You will want to use ExecuteReader() for a SELECT statement as ExecuteNonQuery() will not return a result set. See this answer that describes the differences in the types of SQL Server methods
you don't need connection.Close();, the using statement will handle that.

Fetch MS Access Data Using C# in Table or Formatted Form

I am bit new on c# Window application Development, i have developed lots of working applications in c#, and now i am working on Database using MS Access ODBC. I get success in data insertion into Database but now i am fetching the data, and facing issue of not getting data into the form.
So please can anybody let me know the best way to fetch Data from MS Access Database using c# in an proper table form.
string connectionString = #"Provider=Microsoft Office 12.0 Access Database Engine OLE DB Provider;" + #"Data source= C:\Users\user\Documents\Visual Studio 2012\Projects\WindowsFormsApplication5\WindowsFormsApplication5\bin\debug\Database21.accdb";
string queryString = "SELECT * FROM newdb2";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
while (reader.Read())
{
reddd.Text = reader.GetString(0).ToString();
reddf.Text = reader.GetString(1).ToString();
// Insert code to process data.
}
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Source);
}

access list in sharepoint 2007 using c#

I'm looking to compile data from a few diffrent custome lists in sharepoint 2007
Its a hosted sharepoint site so I don't have access to the machine backend.
Is there any example code to access the sharepoint site using c#?
here is my code thus far (i get the error Cannot connect to the Sharepoint site ''. Try again later.)
DataSet dt = new DataSet();
string query = "SELECT * FROM list";
string site = "http://sp.markonsolutions.com/Lists/Security/";
string list = "35E70EO4-6072-4T55-B741-4B75D5F3E397"; //security db
string myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=2;RetrieveIds=Yes; DATABASE="+site+";LIST={"+list+"};";
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
OleDbCommand myAccessCommand = new OleDbCommand(query,myConnection);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myConnection.Open();
myDataAdapter.Fill(dt);
//execute queries, etc
myConnection.Close();
If you can't deploy code on the SharePoint machine, then you pretty much have to use the web services.
The lists web service is what you're after.
It will be located on http://yousharepointsite.com/_vti_bin/Lists.asmx and should be open by default. Note that if your site is configured with FBA, you will have to use the _vti_bin/Authentication.asmx to log in before you query lists.asmx.
Here is an article that gives all the information you need :
http://sharepointmagazine.net/articles/writing-caml-queries-for-retrieving-list-items-from-a-sharepoint-list
For the reasons mentioned above, skip the part on using the object model to query SharePoint lists and go directly to Retrieving list items with CAML using the SharePoint web services.
The article is pretty complete, so I think you should be OK with that.
As per your edit, I don't think that you can create a connection to your remote site like that. You can't query SharePoint with SQL like that, you really need to use CAML...
Once you've added the reference to the web service :
ListService listsClient = new ListService.Lists();
listsClient.Url = #"http://sp.markonsolutions.com/" + #"/_vti_bin/lists.asmx";
listsClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
listsClient.GetListItems(...);
Read more on the GetListItems here
Like I said, you need to use the web services. You are heading towards a dead end if you are trying to create connection like that to query the database directly. It is not recommended.
Not sure if what you try to do is possible unless you use an ado.net connector for SharePoint, have a look at http://www.bendsoft.com/net-sharepoint-connector/
It enables you to talk to SharePoint lists as if they where ordinary sql-tables
In example to insert some data
public void SharePointConnectionExample1()
{
using (SharePointConnection connection = new SharePointConnection(#"
Server=mysharepointserver.com;
Database=mysite/subsite
User=spuser;
Password=******;
Authentication=Ntlm;
TimeOut=10;
StrictMode=True;
RecursiveMode=RecursiveAll;
DefaultLimit=1000;
CacheTimeout=5"))
{
connection.Open();
using (SharePointCommand command = new SharePointCommand("UPDATE `mytable` SET `mycolumn` = 'hello world'", connection))
{
command.ExecuteNonQuery();
}
}
}
Or to select list data to a DataTable
string query = "SELECT * FROM list";
conn = new SharePointConnection(connectionString);
SharePointDataAdapter adapter = new SharePointDataAdapter(query, conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
Or using a helper method to fill a DataGrid
string query = "Select * from mylist.viewname";
DataGrid dataGrid = new DataGrid();
dataGrid.DataSource = Camelot.SharePointConnector.Data.Helper.ExecuteDataTable(query, connectionString);
dataGrid.DataBind();
Controls.Add(dataGrid);

Connect to AS400 using .NET

I am trying to build a .NET web application using SQL to query AS400 database. This is my first time encountering the AS400.
What do I have to install on my machine (or the AS400 server) in order to connect?
(IBM iSeries Access for Windows ??)
What are the components of the connection string?
Where can I find sample codes on building the Data Access Layer using SQL commands?
Thanks.
You need the AS400 .Net data provider. Check here:
https://www-01.ibm.com/support/docview.wss?uid=isg3T1027163
For connection string samples, check here:
https://www.connectionstrings.com/as-400/
Also, check out the redbook for code examples and getting started.
http://www.redbooks.ibm.com/redbooks/pdfs/sg246440.pdf
Following is what I did to resolve the issue.
Installed the IBM i Access for Windows. Not free
Referred the following dlls in the project
IBM.Data.DB2.iSeries.dll
Interop.cwbx.dll (If Data Queue used)
Interop.AD400.dll (If Data Queue used)
Data Access
using (iDB2Command command = new iDB2Command())
{
command.Connection = (iDB2Connection)_connection;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue(Constants.ParamInterfaceTransactionNo, 1);
command.CommandText = dynamicInsertString;
command.ExecuteScalar();
}
Connection String
<add name="InterfaceConnection"
connectionString="Data Source=myserver.mycompany.com;User ID=idbname;Password=mypassxxx;
Default Collection=ASIPTA;Naming=System"/>
UPDATE
i Access for Windows on operating systems beyond Windows 8.1 may not be supported. Try the replacement product IBM i Access Client Solutions
IBM i Access Client Solutions
As mentioned in other answers, if you have the IBM i Access client already installed, you can use the IBM.Data.DB2.iSeries package.
If you don't have the IBM i Access software, you can leverage JTOpen and use the Java drivers. You'll need the nuget package JT400.78 which will pull in the IKVM Runtime.
In my case I needed to query a DB2 database on an AS400 and output a DataTable. I found several hints and small snippets of code but nothing comprehensive so I wanted to share what I was able to build up in case it helps someone else:
using com.ibm.as400.access;
using java.sql;
var sql = "SELECT * FROM FOO WITH UR";
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
Connection conn = DriverManager.getConnection(
"jdbc:as400:" + ServerName + ";prompt=false", UserName, Password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int ct = md.getColumnCount();
DataTable dt = new DataTable();
for(int i=1; i<=ct; i++)
dt.Columns.Add(md.getColumnName(i));
while (rs.next())
{
var dr = dt.NewRow();
for (int i = 1; i <= ct; i++)
dr[i - 1] = rs.getObject(i);
dt.Rows.Add(dr);
}
rs.close();
The conversion from RecordSet to DataTable is a little clunky and gave me bad flashbacks to my VBScript days. Performance likely isn't blinding fast, but it works.
Extremely old question - but this is still relevant. I needed to query our AS/400 using .NET but none of the answers above worked and so I ended up creating my own method using OleDb:
public DataSet query_iseries(string datasource, string query, string[] parameterName, string[] parameterValue)
{
try
{
// Open a new stream connection to the iSeries
using (var iseries_connection = new OleDbConnection(datasource))
{
// Create a new command
OleDbCommand command = new OleDbCommand(query, iseries_connection);
// Bind parameters to command query
if (parameterName.Count() >= 1)
{
for (int i = 0; i < parameterName.Count(); i++)
{
command.Parameters.AddWithValue("#" + parameterName[i], parameterValue[i]);
}
}
// Open the connection
iseries_connection.Open();
// Create a DataSet to hold the data
DataSet iseries_data = new DataSet();
// Create a data adapter to hold results of the executed command
using (OleDbDataAdapter data_adapter = new OleDbDataAdapter(command))
{
// Fill the data set with the results of the data adapter
data_adapter.Fill(iseries_data);
}
return iseries_data;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
And you would use it like so:
DataSet results = query_iseries("YOUR DATA SOURCE", "YOUR SQL QUERY", new string[] { "param_one", "param_two" }, new string[] { "param_one_value", "param_two_value"});
It returns a DataSet of the results returned. If anyone needs/wants a method for inserting/updating values within the IBM AS/400, leave a comment and I'll share...
I'm using this code and work very good for me!
Try
Dim sqltxt As String = "SELECT * FROM mplib.pfcarfib where LOTEF=" & My.Settings.loteproceso
dt1 = New DataTable
Dim ConAS400 As New OleDb.OleDbConnection
ConAS400.ConnectionString = "Provider=IBMDA400;" & _
"Data Source=192.168.100.100;" & _
"User ID=" & My.Settings.usuario & ";" & _
"Password=" & My.Settings.contrasena
Dim CmdAS400 As New OleDb.OleDbCommand(sqltxt, ConAS400)
Dim sqlAS400 As New OleDb.OleDbDataAdapter
sqlAS400.SelectCommand = CmdAS400
ConAS400.Open()
sqlAS400.Fill(dt1)
grid_detalle.DataSource = dt1
grid_detalle.DataMember = dt1.TableName
Catch ex As Exception
DevExpress.XtraEditors.XtraMessageBox.Show("ComunicaciĆ³n Con El AS400 No Establecida, Notifique a Informatica..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
I recently found the ADO.Net driver available on NuGet. I have the iSeries client access installed on my PC, so I can't say if it works as a standalone, but it does connect. Theonly problem is I can't actually see any tables or procedures. I think there may be a schema or library or something I still haven't gotten down to. I will post if I find the answer. Meanwhile I can still get to the server and write most of my code with the NuGet adapter.
Check out http://asna.com/us/ as they have some development tools working with SQL and the AS400.

Categories

Resources