store procedure calling xp_cmdshell - asp.net

After insert Trigger on table calls Sp1. Some code before is executed, but when it comes to EXEC xp_cmdshell it goes to suspend mode (I used sp_who on SQL server). Suspended process is bulk import of some data from csv of NT SERVER\MSQLSERVER.
Sp1 (Store procedure does some job with SSIS package.)
EXEC master.sys.xp_cmdshell 'c:\"Program Files (x86)"\"Microsoft SQL Server"\120\DTS\Binn\DTExec.exe /f "C:\xxx\yyy\import_data.dtsx"'
What I have done to solve the problem:
Security on xp_cmdshell, user A which is used to connect form app to database is in sysadmin role, xp_cmdshell in enabled. User has execute permissions on xp_cmdshell on master table.
Tried with sp_cmdshell_proxy_user no luck
NT service\MSSQLserver has full control over 'c:\"Program Files (x86)"\"Microsoft SQL Server"\120\DTS\Binn AND C:\xxx
The best part:)
When I run Sp1 from SQL studio with user A it works just fine!
When I run from app (the same user A), it goes to suspend. APP is asp.net core.
Any idea where to look? I suspect it is security issue

Related

Various difficulties creating ASP.NET Session tables via aspnet_regsql.exe

We're trying to move ASP.NET session state for one of our Azure web apps into a database, and it seems like the aspnet_regsql.exe tool is the way to go. Unfortunately, I'm getting stuck on a few issues below. It's an Azure SQL database, and I'm connecting using the server's admin account.
I initially wanted to add the session tables to our existing database, so I ran .\aspnet_regsql.exe -U adminusername -P adminpassword -S servername.database.windows.net -d databasename -ssadd -sstype c. Which throws the exception "Database 'databasename' already exists. Choose a different database name"
Omitting the database name and running it again throws the exception: "Execution Timeout Expired" after about 30 seconds, which is just the default for SqlCommand.CommandTimeout. This occurs while executing the "CREATE DATABASE" command. I tried creating a database manually, and it takes about 50 seconds for some reason. This database is S0 tier and is not under any load
Running aspnet_regsql again on the already-created database (because it's idempotent, right?) leads to the "Database already exists" error, as does pre-creating an empty database for it to start from.
There's no flag that lets me increase the timeout, and I can't set command timeout using the -C (connection string) flag
Adding the -sqlexportonly flag to generate a script and just running that directly doesn't work either (yes, I know I'm not supposed to run InstallSqlState.sql directly). It throws a whole load of error messages saying things like:
Reference to database and/or server name in 'msdb.dbo.sp_add_job' is not supported in this version of SQL Server.
USE statement is not supported to switch between databases.
Which makes me think this script might have some issues with an Azure SQL database...
Does anyone have any ideas?
Update:
It looks like all the errors involving 'msdb' are related to removing and re-adding a database job called 'Job_DeleteExpiredSessions'. Azure SQL doesn't support database jobs, so the only options I can see are
Run SQL on a VM instead (vastly more expensive, and I'd rather stick with the platform services than have to manage VMs)
Implement one of those "Elastic Job Agents"
Perhaps move the same functionality elsewhere (e.g. a stored proc)?
Turns out Microsoft has an article about how to do exactly what I need, which I somehow
missed during my searching yesterday. Hopefully this answer saves someone else a few hours of frustration. All the info you need is at https://azure.microsoft.com/en-au/blog/using-sql-azure-for-session-state/ earlier.
Note that YMMV since it's from 2010 and also says in scary red letters
"Microsoft does not support SQL Session State Management using SQL Azure databases for ASP.net applications"
Nevertheless, they provide a working script that seems to do exactly what I need.

dynamics AX batch job through ODBC

I have problems with an ODBC connection used in a batch job: when executed, I have the following error message :
"The ODBC operation failed.Unable to connect to database
Invalid connection String attribute Trusted_Connection
Unabe to create object 'OdbcConnection' "
I try to connect to an Access database, I use the following code:
LoginProperty loginProperty;
OdbcConnection odbcConnection;
;
loginProperty = new LoginProperty();
loginProperty.setDSN("MyDSN");
loginProperty.setDatabase("MyDatabase");
odbcConnection = new OdbcConnection(loginProperty);
when debugging, it crashes on odbcConnection = new OdbcConnection(loginProperty). I tested the same code in a job in local client execution, there was no problem and it worked fine(without defining login password in code or DSN). My DSN seems to be OK on AOS, I'm using AX 2009 without SP1, I saw some examples where there was login/password defined in loginProperty object , the setUserName() and setPassword() methods are not available in my AX version loginProperty object. My class is executed on server-side (as any batch job).
Is there some particular setup to do to connect to ODBC datasource through batch job?
any ideas or suggestions?
thanks for your help
Edit:AOS is running on Windows server 2003 32 bits, ODBC tested on it, works fine but doesn't work in AX through batch job
Most likely you will need a 32-bit DSN connection for your AX. I would create both versions on the AOS server.
Look here for details.
It may be caused due to permisions. "trusted connection" refers to the fact that you connect to the database through the user logged to the current session. When you run a Job from the AX client, this is executed with the user that runs the current AX client (the one logged to the active session); When code is executed from server in a batch job, code is executed through the user that runs the AOS windows service.
Has this user permissions to read/write/access the access file and directory?
If you are on a 64 bit machine use C:\Windows\SysWOW64\odbca32.exe to create the datasource.
Check under which ID the AOS runs, log on with that ID and make sure you can 'see' the data source.
Also make sure that the AOS account has access to the directory/files (if using file-based odbc)

Can we delete old records from aspstatetempsessions table?

Recently I created Session State in my project, code is below
<sessionState mode="SQLServer" allowCustomSqlDatabase="true"
sqlConnectionString="Data Source=ADMIN-9F8C57749\SQLEXPRESS;Initial
Catalog=kecbliss;Integrated Security=True" timeout="60"
stateNetworkTimeout="60">
</sessionState>
The problem is day by day aspstatetempsessions table is becoming big
so my question is
Can i delete previous days records from aspstatetempsessions?
How to achieve this without affecting to project ?
Project details
Front end ASP.NET
Back end MS SQL Server
To resolve this issue:
Step1:
Make sure that the SQL Agent service is running and also check to see if the SQL Agent job called SSPdatabaseName_Job_DeleteExpiredSessions exists and run successfully.
If you have the SQL Agent Services is started and the SQL Agent Job is missing, proceed to the Step2
Step2:
Run the DeleteExpiredSessions Stored Procedure manually on the SSP database.
Connect to the database server using Microsoft SSMS --> Client on
New query.
Make sure you have selected the SSP database in the new query
windows.
Type in “EXEC DeleteExpiredSessions” and execute the query.
This command would clean up the ASPStateTempSessions table and not remove any active connections.
Note: Depending on the ASPStateTempSessions table size, it is recommended to run this command during off-peak times on the SharePoint/SQL server.
To register the job to be run automatically in the future follow the below steps:
Ensure the SQL Agent is on (it should be set as an Automatic startup
Windows service as well)
Obtain the SSP database name that contains the ASPStateTempSessions
table missing an associated SQL Agent Job.
Execute the following command on a WFE or any application servers
with the server farm:
From the command prompt get to the ASP .Net folder %WINDIR%\Microsoft.NET\Framework\v2.0.50727\
aspnet_regsql.exe -sqlexportonly exportfilepath.sql -ssadd -sstype c -d SSP db name
Open the exportfilepath.sql file in a note pad, make sure to select
the text between the following lines:
/* Create the job to delete expired sessions */
and
/**********************************/
Copy the above copied test and Execute the code on the SQL box
hosting the SSP database.
Now you should find a SQL Agent Job is created.
Raj
Source: support.microsoft.com/kb/970788

Automatic fix for tempdb error related to 'ASPStateTempSessions'

As per this how-to, I've successfully configured IIS on my XP-SP3 dev box for SQL Server 2008 Express to save ASP.NET session state information. I'm just using SQL Server because otherwise on every recompile, I was losing the session state which was obnoxious (having to re-login). But, I'm facing an annoying issue in that every time I restart SQL there's this error, and sometimes one or two other very similar friends:
The SELECT permission was denied on the object 'ASPStateTempSessions',
database 'tempdb', schema 'dbo'.
To fix the error, I just open Management Studio and edit the User Mapping for the login/dbo I'm using on the ASPState db, and re-add tempdb to that user with all but deny permissions. Apparently, once the right permissions are there, ASP.NET is able to automatically create the tables it uses. It just can't run that CreateTempTables sproc until the right security is there.
THE QUESTION...
Is there a way to not have to re-do this on every restart of the SQL Server?
I don't really care right now about keeping the temp data across restarts, but I would like to not have to go through this manual step just to get my web app working on localhost, which uses session state variables throughout. I suppose one could resort to some kind of stored procedure within SQL Server to accomplish the task for this machine when the service starts, to not have to do it manually. I'd accept such an answer as a quick fix. But, I'm also assuming there's a better recommended configuration or something. Not seeing an answer to this on the how-to guide or elsewhere here on StackOverflow.
Both answers seem valid; but with most things Microsoft, its all in the setup...
First uninstall the ASPState database by using the command:
aspnet_regsql –ssremove –E -S .
Note:
-E is to indicate you want to use integrated security connection.
-S informs what SQL server and SQL instance to use, and the "." (dot) specifies default local instance
Then re-install using the command:
aspnet_regsql –ssadd –sstype p –E -S .
Note:
The sstype has three options, t | p | c ... the first "t", tells the installer to host all stored procedures in the ASPState database, and all data in the tempdb. The second option "p" tells the installer to persist data to the ASPState database. The last option "c" allows you to specify a different 'custom' database to persist the session state data.
If you reinstall using the "-sstype p" you then need only to supply datareader/datawriter to the ASPState database for the user that's making the connection (in most cases, the application pool's identity in IIS).
The added benefit of persisting the data is that session state is retained even after a restart of the service. The only drawback is that you need to ensure the agent cleanup job is pruning old sessions regularly (it does this by default, every minute).
Important:
If you are running a cluster, you must persist session data. You're only option is to use sstype 'p' or 'c'.
Hope this sheds light on the issue!
For the record, I did find a way to do this.
The issue is that the tempdb is recreated from the model db each time the service restarts. The gist of the solution is to create a stored procedure that does the job, and then make that procedure run at startup.
Source code (credit to the link above) is as follows:
use master
go
-- remove an old version
drop proc AddAppTempDBOwner
go
-- the sp
create proc AddAppTempDBOwner as
declare #sql varchar(200)
select #sql = 'use tempdb' + char(13) + 'exec sp_addrolemember ''db_owner'', ''app'''
exec (#sql)
go
-- add it to the startup
exec sp_procoption 'AddAppTempDBOwner', 'startup', 'true'
go
Well done for finding the strangest way possible to do this.
The correct answer is as follows:
use master
go
EXEC sp_configure 'Cross DB Ownership Chaining', '1'
go
RECONFIGURE
go
EXEC sp_dboption 'ASPState', 'db chaining', 'true'
go

How To Query A Database That's Being Used By Asp.Net

I have a Sql Server 2008 Express database file that's currently being used by an ASP.NET application, and I'm not sure how to query the database without taking the website down.
I'm unable to copy the database files (.mdf and .ldf files) to another directory, since they're in use by the web server. Also, if I attach the databases to an instance of the sql server (using the 'Create Database [DB name] on (filename = '[DB filename.mdf]') for attach;' command at the sqlcmd prompt), then the application pool user becomes unable to access the database (i.e. the webpages start producing http 500 errors. I think this might have to do with the username for the application pool becoming somehow divorced from the login credentials in the sql server database).
Any suggestions? I realize this is probably a newbie question, since it seems like a rather fundamental task. However, due to my inexperience, I really don't know what the answer is, and I'm pretty stumped at this point, since I've tried a couple of different things.
Thanks!
Andrew
if I attach the databases to an instance of the sql server (using the 'Create Database [DB name] on (filename = '[DB filename.mdf]') for attach;' command at the sqlcmd prompt),
Don't do this to a live database - it's attempting to be setup an MDF to be written to by two different databases...
Use Backup/Restore
As you've found, Attach/ReAttach requires the database to be offline - use the Backup/Restore functionality:
MSDN: Using SSMS to Backup the Database
MSDN: Using SSMs to Restore the Backup
Be aware that the backup/restore doesn't maintain logins (& jobs if you have any associated with the database) - you'll have to recreate & sync if using an account other than those with uber access.
Maybe Linked Server would work?
Another alternative would be to setup another SQL Server Express/etc instance on a different box, and use the Linked Server functionality to create a connection to the live/prod data. Use a different account than the one used for the ASP application...

Resources