Entity Framework receives Access Denied, while plain SQL commands not - entity-framework-6.1

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)

Related

Unable to refresh dynamic data source in PowerBI service via using anonymous web API access?

This relates to my earlier question - How to iterate/loop through next pages in an API request in PowerQuery/PowerBI? ; which was resolved using below code:
//Declare base variables
let
BaseURL = "https://api.aaaaaa.com",
Entity = "/api/v1/user?&limit=1000",
Token = "zzzzzzzzzzzzzzzzzzzzzzzzzzzz",
Options = [Headers=[APITOKEN=Token]],
URL = BaseURL & Entity,
//Define a function that would take step/page as parameter and return results
GetData=(page as number) =>
let
Source = Json.Document(Web.Contents(URL & "&step=" & Number.ToText(page), Options)),
Data = try Source[results] otherwise null
in
Data,
//Iterate over GetData () to return all the records until last page i.e. until no "result" is retrieved from the API call
GeneratePageList =
List.Generate( ()=>
[Result = try GetData(1) otherwise null, Page=1],
each [Result] <> null,
each [Result = try GetData([Page]+1) otherwise null, Page=[Page]+1],
each [Result]
)
in
GeneratePageList
However, once this code is published to PowerBI service, we cannot schedule refresh for it, since it gives below error as:-
This dataset includes a dynamic data source. Since dynamic data sources aren't refreshed in the Power BI service, this dataset won't be refreshed. Learn more: https://aka.ms/dynamic-data-sources.
• Data source for Query1Discover Data Sources
Tried RelativePath & Query method as suggested here - https://blog.crossjoin.co.uk/2016/08/16/using-the-relativepath-and-query-options-with-web-contents-in-power-query-and-power-bi-m-code/ and here-
https://blog.crossjoin.co.uk/2019/04/25/skip-test-connection-power-bi-refresh-failures/
But, without any luck, see below how am using it:
let
BaseURL = "https://api.crewhu.com",
Entity = "/api/v1/user?&limit=1000&step=",
Token = "60afbdaf5d7d584762771f36",
Options = [Headers=[X_CREWHU_APITOKEN=Token]],
URL = BaseURL & Entity,
//Define a function that would take step/page as parameter and return results
GetData=(page as number) =>
let
Source = Json.Document(Web.Contents(BaseURL & [RelativePath = Entity, Query=[page]], Options)),
The BaseURL is reachable; but redirects to the login page, where our admin credentials (username+password) on the vendor site works well. However, same credentials do not work when using "Basic" connection method during accessing Web Content. Therefore, tried adding #Authorization = Basic in the header along with API key like - [Headers=[Authorization = Basic, X_CREWHU_APITOKEN=Token]]; but this also didn't work.
We've only got an Open API token/key from the vendor; but even that token/key also doesn't work from when providing that in "Web API" section during connecting/accessing Web Content, it gives error as:- "a web api key can only be specified when a web api key name is provided", but the same key/token works well from within PowerQuery (M) code using anonymous web api call method.
Have tried multiple permutation combinations of providing key/token in the username/password fields as suggested in some sites, but still no luck.

C# OleDbConnection

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.

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;
}

Query SCCM from Task Sequence - is it possible?

I have a VBscript which works abolultuly fine on my workstation. It queries SCCM to find out what domain a computer is in. When I run it as part of the task sequence, it fails. Note that this is almost the last step in the task sequence, under Windows 7, not Windows PE.
Option Explicit
Const wbemFlagReturnImmediately = &H10
Const wbemFlagForwardOnly = &H20
Dim computerName, userName, userPassword, server
Dim swbemLocator, swbemServices, providerLoc
Dim location, connection
Dim query, found, resource, resources
'--- Settings ---
userName = "domain\username"
userPassword = "password"
server = "domain.com"
'--- Get computer name ---
computerName = CreateObject("WScript.Network").ComputerName
WScript.Echo"Computer name: " & computerName
'--- Connect ----
Set swbemLocator = CreateObject("WbemScripting.SWbemLocator")
swbemLocator.Security_.AuthenticationLevel = 6
Set swbemServices = swbemLocator.ConnectServer(server, "root\sms",userName,userPassword)
Set providerLoc = swbemServices.InstancesOf("SMS_ProviderLocation")
For Each location In providerLoc
If location.ProviderForLocalSite = True Then
WScript.Echo "SiteCode: " & location.SiteCode
Set connection = swbemLocator.ConnectServer(server, "root\sms\site_" + location.SiteCode)
Else
WScript.Echo "Not provider for local site."
End If
Next
'--- Query & output ---
query = "SELECT * FROM SMS_FullCollectionMembership WHERE name = '" & computerName & "'"
Set resources = connection.ExecQuery(query, , wbemFlagForwardOnly Or wbemFlagReturnImmediately)
found = False
For Each resource In resources
WScript.Echo "Domain: " & resource.Domain & " (" & resource.CollectionID & ")"
found = True
Exit For
Next
If Not found Then WScript.Echo "Computer not found!"
If I open a command prompt ruing the task sequence (using F8 under Windows 7, not Windows PE) and run the script, I get:
SWbemLocator: Access is denied
on the line:
Set connection = swbemLocator.ConnectServer(server, "root\sms\site_" + location.SiteCode)
Any thoughts? Alternatively, any other suggestions on how to find out what domain a computer was in last time it was built?
Your Task Sequence runs in context of the the local system account, and per default this account has no rights in SCCM.
If you define "yourdomain\domain computers" in the SCCM admin console, Security Rights, Users, and give them read and read resource rights on Collection, you should be able to connect to your SCCM server.
Please notice, you have to do this on all site servers you want to connect to, these definitons are not replicated between sites.
I realise this is a very old post but I just had this problem myself.
You already have the username and password in the script and it is used here
Set swbemServices = swbemLocator.ConnectServer(server, "root\sms",userName,userPassword)
However just a bit further down you are making a connection to the site without the username and password.
Set connection = swbemLocator.ConnectServer(server, "root\sms\site_" + location.SiteCode)
Try this:
Set connection = swbemLocator.ConnectServer(server, "root\sms\site_" + location.SiteCode, userName, userPassword)
Hope this helps someone!