C# OleDbConnection - console-application

I have "Multiple-step OLEDB operation generated errors. Check each OLE DB status value, if available. No work was done." OleDbException while trying the following connection string:
source = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\SQLEXPRESS;initial catalog=Teacher;integrated security=true;"
OleDbConnection conn = new OleDbConnection(source);
conn.Open();

looks like you have an error in your connection string. Try changing the "integrated security=true" to "integrated security=SSPI" like below:
source = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\SQLEXPRESS;initial catalog=Teacher;integrated security=SSPI;"
OleDbConnection conn = new OleDbConnection(source);
conn.Open();
If that doesn't work, try connecting to SQLEXPRESS using SQL Server authentication, i.e. with username and password (in order for this work you need to allow mixed type authentication in SQL Server):
source = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\SQLEXPRESS;initial catalog=Teacher;User ID=myUsername;Password=myPassword;"
OleDbConnection conn = new OleDbConnection(source);
conn.Open();
Let us know the result.

Related

Using PowerShell to send data from SQL Server to service via SOAP

I'm fairly new to PowerShell and brand new (as in, today) to web services and SOAP. A vendor gave us documentation on their web service API that allows the creation of user accounts. I'm trying to use PowerShell to pull our users from SQL Server and send the data to their service. We will need to add users on an ongoing basis.
Below is a pared-down version of what I came up with and it actually seems to work; the vendor told me to include a dry_run parameter while testing and I'm getting a dry_run_success from the response_type.
My question is: Is this even close to being the appropriate way to do it with PowerShell?
# Open ADO.NET Connection to database
$dbConn = New-Object Data.SqlClient.SqlConnection;
$dbConn.ConnectionString = "Data Source=mydbserver;User ID=someuserid;Password=mypassword;Initial Catalog=mydatabase";
$dbConn.Open();
$sql = "select * from mytable";
$dbSqlCmd = New-Object Data.SqlClient.SqlCommand $sql, $dbConn;
$dbRd = $dbSqlCmd.ExecuteReader();
# Create a Web Service Proxy
$proxy = New-WebServiceProxy -Uri https://somedomain.com/service/wsdl
$namespace = $proxy.GetType().NameSpace
$param = New-Object($namespace + ".somemethod")
# Loop through records from SQL and invoke the web service
While ($dbRd.Read())
{
$param.user_id = $dbRd.GetString(0)
$param.password = $dbRd.GetString(1)
$param.display_name = $dbRd.GetString(2)
$request = $proxy.TheMethod($param)
if ($request.response_type -eq 'error')
{
$request.error.extended_error_text
}
}
# Clean up
$dbRd.Close();
$dbSqlCmd.Dispose();
$dbConn.Close();
A couple things you could improve:
Don't use select * in your SQL queries. Always specify the fields you need, in the order you need. As written, if someone were to restructure the table such that the user ID wasn't the first column, you'd have a mess on your hands because you're accessing the fields by their ordinal number
You're apparently storing those passwords in plaintext in your database. Anyone with access to your database knows the credentials for every one of your users. This is a very bad thing. Resolving this could be a very big discussion.
Your code keeps the database connection open until the script completes. Given the scope here, it's probably not going to cause a major problem, but your database access strategy should be to get in, get your data, get out & disconnect as quickly as possible.
$sql = "select user_id, password, display_name from mytable";
$QueryCmd = $dbConn();
$QueryCmd.CommandText = $sql;
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$QueryCmd.Connection = $dbConn;
$SqlAdapter.SelectCommand = $QueryCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet)
$dbConn.Close();
$dbConn.Dispose();
$MyResults = $DataSet.Tables[0];
$MyResults | foreach-object {
$param.user_id = $_.user_id;
$param.password = $_.password;
$param.display_name = $_.display_name;
$request = $proxy.TheMethod($param);
if ($request.response_type -eq 'error')
{
$request.error.extended_error_text;
}
}

My webservice using apache shiro always return unauthorized

I have this shiro.ini:
[main]
ds = org.apache.shiro.jndi.JndiObjectFactory
ds.requiredType = javax.sql.DataSource
ds.resourceName = java:/comp/env/jdbc/myDS
# JDBC realm config
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = "SELECT password FROM user WHERE username = ?"
jdbcRealm.dataSource = $ds
credentialsMatcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
# base64 encoding, not hex in this example:
credentialsMatcher.storedCredentialsHexEncoded = false
credentialsMatcher.hashIterations = 1024
jdbcRealm.credentialsMatcher = $credentialsMatcher
[urls]
/logout = logout
/** = authcBasic
Im debbuging JndiRealm in doGetAuthenticationInfo. I get an exception when shiro try to execute my authenticationQuery in getPasswordForUser method. Those are the lines that execute the select:
ps = conn.prepareStatement(authenticationQuery);
ps.setString(1, username);
My atuthenticationQuery is "SELECT password FROM user WHERE username = ?" so trying to access position 1 is invalid since it starts from position 0. Is that a bug on JndiRealm from apache shiro or i wrote my sql wrong?
Looks like you have a simple mock implementation of a realm.
For logging in to work, you needs 2 steps:
authentication (is the username/password correct)
authorization (what is the user allowed to do)
Looks like you have only created the first step, but you are just giving back the password in the return statement.
Shiro will hash the password that was entered by the user. You should have the same hash stored somewhere in your database. In the doGetAuthenticationInfo you should do a lookup based on the username that was entered and retrieve the hash (either from the db, or disk or whatever you prefer), that is what you should put in the SimpleAuthenticationInfo object and return, shiro will do the user password hashing and comparison for you.
For the second step, override the method doGetAuthorizationInfo. You could let it return an instance of SimpleAuthorixationInfo containg a set of permissions, the simplest being "*", when it has access to everything.
Creating such a method can be as simple as:
#Override
public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//here you can create custom permissions based on the principal
//that has been authenticated using your own logic
info.addStringPermission("*");
return info;
}

Entity Framework receives Access Denied, while plain SQL commands not

I am trying to force Entity Framework to create database at my desired location, but it always complains on "Access denied":
Error was: Unhandled exception: (System.Data.SqlClient.SqlException)
Unable to open the physical file "D:\te_mp\zeliboba_odin.mdf".
Operating system error 5: "5(Access denied.)".
But if I use plain SQL Commands with the same connection string - then DB is created successfully.
var createDbSql = String.Format(
"CREATE DATABASE {0} ON PRIMARY (NAME = {0}_Data, FILENAME = '{1}.mdf', SIZE = 10MB, " +
" FILEGROWTH = 10%) LOG ON (NAME = {0}_Log, FILENAME = '{1}.ldf', SIZE = 1MB, FILEGROWTH = 10%) ",
dbName, filename);
What's the difference between these two cases? Why EF fails?
Update 1:
First connection string is:
var sqlConnection = new SqlConnection(#"Server=.\SQLEXPRESS;Integrated Security=SSPI;");
This will work got plain SQL commands sent to server - I am creating databases right now.
Next I create DB, and I have its name. So I do like this:
var connectionString = String.Format(#"Data Source=.\SQLEXPRESS;Integrated Security=SSPI;database={0}", dbName);
sqlConnection = new SqlConnection(connectionString);
using (var db = new MyDbContext(sqlConnection, true)) {
// EF creates database without any troubles.
}
What I tried with EF - set AttachDatabaseFile (cant remember exact name of parameter). EF really tries to create a database at provided location, but it fails with Access denied error. I tried to play with args in connection string, but I failed, and I do not know how can I point EF to create database at particular folder with particular filenames (making sure SQL Server can create database there itself).
SQL Server database engine service account must have permissions to read/write in the new folder.
Attaching Database – Unable to Open Physical File (Access is Denied)

Calling WebAPI in UnitTest TestInitialize

im trying to write a UnitTest for a WebAPI and EF
Im trying to add Data do the database in den TestInitialize, but it didnt work. When i do the same command in a Console Applications, it works.
Is there a different in calling that webapi for tests?
[TestInitialize]
public void CreateEntityObjects()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:60609/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Department dep1 = new Department() { Id = Guid.NewGuid(), Name = "IT" };
client.PostAsJsonAsync("api/Department", dep1);
}
Edit:
So i still just do the initialize no cleanup (later). I was looking manually if there is some data in the database. But no data, no Error, nothing.
You may try looking at the result property of the request:
var response = client.PostAsJsonAsync("api/Department", dep1).Result;
and then look at what does the server return:
string responseContent = response.Result.Content.ReadAsStringAsync().Result;
Now analyze the responseContent variable to see what possible error message you might have gotten from the server. Also you probably want to self-host your Web API in the unit test before sending an HTTP request to it, otherwise your API might not even be started.

JBoss EAP 5.1 Server not using Windows Network Setting

I'm trying to call a web service from my application. My system is protected with a Firewall and I'm using a Proxy to access any external URL/internet access. The application is running on JBoss EAP 5.1 server. The application fails to write to the service URL with IO Exception: 'Could not transmit message'.
However, when I'm trying to access the service URL with IE/Firefox, it's opening. Although the XML response I'm receiving from Browser states a generic error - 'invalid request parameters...', which is quite obvious. Because I'm not sending a proper request XML from Browser.
I'm really confused with this disparity. I used to believe that JBoss will pick up standard windows network settings, but in my case it is not.
My code is as follows:
String strUrl = "http://theurlgoeshere";
String requestXml = "<request></request>";
String wsResponse="";
SOAPConnection conn = null;
try {
MessageFactory msgFac = MessageFactory.newInstance();
MimeHeaders mh = new MimeHeaders();
mh.setHeader("Content-Type", "text/xml; charset=UTF-8");
log.info("Request Xml:" + requestXml );
InputStream is = new ByteArrayInputStream(requestXml.getBytes("UTF-8"));
SOAPMessage reqMsg = msgFac.createMessage(mh, is);
SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();
conn = conFac.createConnection();
SOAPMessage repMsg = conn.call(reqMsg, strUrl);
ByteArrayOutputStream out = new ByteArrayOutputStream();
repMsg.writeTo(out);
wsResponse = new String(out.toByteArray());
}
catch (Exception e) {
e.printStackTrace();
}
Got it sorted few days back. Basically I am using HttpURLConnection now to add proxy setting in the java code itself while making the Webservice call. Just closing this question, since my query is solved.
Will update the new code, if anyone needs.