SSIS C# Script Error reading Windows Registry Key - c#

I have a huge problem and I don't even know what to check.
I have a big SSIS package which at beginning it runs an "Execute Script" task (named ST_2275f0b3eced4c84bd35d4c826cab866.csproj), wrote in C#, which looks like this:
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.Win32;
namespace ST_2275f0b3eced4c84bd35d4c826cab866.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
Dts.Variables["user_uca"].Value = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\TDCredentials").GetValue("user_uca").ToString();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
Bottom line is that it loads a SSIS package variable with the data from a specific Windows Registry key.
The issue is that when I ran the SSIS package from Visual Studio it works. But when I ran the Sql Agent Job which was made for that SSIS package, it gives me the error:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object. at ST_2275f0b3eced4c84bd35d4c826cab866.csproj.ScriptMain.Main()
This error means that the Windows Registry key does not exists. Because if I deleted on purpose the specific Windows Registry key and then ran the SSIS package from Visual Studio, I get the exact error message.
I have checked all that I could thing of: the sql server and the host having those Windows Registry key - they are the same. Also i gave permissions for "Everyone" for those keys, also I had put the key in HKLocalMachine, in order to be sure they exist for all the users, still same error.
Any hints?!
Thanks in advance, Bogdan.

The problem is ultimately a permissions issue. Either that the service account that runs SQL Agent or the Credentials you are running the subsystem jobs step of SSIS does not have the ability to read that part of the registry.
You need to either grant that user access or create a delegate that can read from the registry.
As a side note, you don't have to use your Script approach. Reading Registry values and assigning them to Variables is native functionality in SSIS. See Configurations for more information on the topic. You will still have to deal with the permission issue but then you won't have code copy and pasted throughout your packages.

As said, it was a permission issue for the account which was running the sql agent job.
Therefore the solution was first to make a new credential, from "Credentials" -> "New Credential". In the "Identity" field I choose an user with sysadmin rights (eg. john.doe). In the field "Credential name" I had filled "John". Then from Sql Server Agent -> Proxies -> SSIS Package Execution I created "New Proxy". I filled at "Proxy name" a name (ProxyJohn), at "Credential name" I choose the credential defined early, "John", then at field "Active to the following subsystems" I have checked the "Sql Server Integration Services Package" option.
Then, at my Sql Server Agent -> Jobs, on my job (which gave me the error message when ran), in proprieties -> Steps-> "Run As" I have choose the new credential created above, named "ProxyJohn" instead of "Sql Server Agent Service Account" (which was by default)
It worked like a charm.
Hope it will help.
Best regards, Bogdan

Related

Access Denied when running Windows Service

I have created a Windows Service using ASP.Net Core 3.x and C#. I started with the new Windows Service template when I built the project. When I run it from my development environment or from a console window it runs fine. When I install it as a Windows Service and attempt to start the service I get an
"Error 5: Access is denied." error.
I tried numerous things which I will outline below to eliminate the error but nothing seemed to work so I downloaded the sample app provided by Microsoft, at sample
Same result...when I run the sample app from within Visual Studio it runs fine, when running as a service I get the Access Denied error.
I am running all of this on my local machine, which I am an admin on.
I originally tried to run it using the default Local System account; got the Access Denied error.
I changed the Log On As to my domain account, the same one I use to log into my local machine which is an admin on this machine; got the same Access Denied error.
My account has the privilege set to run as a service.
The Event Viewer just shows the one message which says "Access Denied", no other messages are created.
I believe the Access Denied error is occurring before the C# code is even executed. What makes me believe this is that I added one line to the very top of the Program.Main.... File.WriteAllText("C:\\temp\\ws.log", $"Test of Worker Service # {DateTime.Now}. Content Root Path: {AppContext.BaseDirectory}");. My account has full access to the temp folder. This file gets created when I run the app from Visual Studio but it does not get created when I run the app as a service.
I have read numerous web sites, include this one and this one. No luck, everything I tried from these sites still produce the Access Denied error.
I have run out of ideas and am hoping someone here can provide me the answer. Thanks!
I found the solution and believe me I feel really stupid!!!
When I installed it as a service I only put the path in "binPath".
sc create WindowsService1 binPath="C:\temp".
Once I actually added the executable to the binPath parameter everything worked.
Changed it to sc create WindowsService1 binPath="C:\temp\WindowsService.exe" and it worked.
I know it is an Id10t error but Microsoft should really provide better messaging for the "sc" command. A message like "Cannot find file specified in the binPath parameter" would have been really helpful. Would have saved me about 6 hours of work.
Thanks everyone for reviewing and replying to this question.

IRDOSession.GetFolderFromPath throws MAPI_E_FAILONEPROVIDER error while Reading public folders through Redemption.dll

I am upgrading one Console Application which is Read Outlook Public Folder.
It's working fine when I run manually. But throws exception when run through IBM Tivoli Workload Scheduler.
So tried to give inbox folder name instead of public folder name. Then it's working fine in Scheduler also. So only I get below error while try to read public folder alone
Error in IMAPISession::OpenMsgStore: MAPI_E_FAILONEPROVIDER ulVersion:
0 Error: The attempt to log on to Microsoft Exchange has failed.
Component: Microsoft Exchange Information Store ulLowLevelError: 1144
ulContext: 1298
var session = new RDOSession();
session.Logon(string.Empty, string.Empty, false, true, null, null);
session.Stores.FindExchangePublicFoldersStore();
var publicFolder = session.GetFolderFromPath(folderPath);
Public folder:
\\Public Folders - example#domain.com\All Public Folders\XXX
Folders\YYY/Object & Data\ZZZ\
Not working
Inbox folder:
\\example#domain.com\Inbox
Working
Edit: Added log and find out Exchange connection mode changing
Manual Run ExchangeConnectionMode: olCachedConnectedFull
Scheduler Run ExchangeConnectionMode: olOnline
Note: We are using Redemption.dll - 5.10
Update:
Old server Using Redemption.dll - 5.2 and Outlook 2003 with Exchange Server 2010. It's working fine with TWS also.
New server Using Redemption.dll - 5.10 and Outlook 2016 with Exchange Server 2010. But doesn't work with TWS.
Chances are the Public Folder store is not cached, so when you log under a service (scheduler), the store provider does not have the credentials to open the store.
For this issue fix we need to do two things:
Click Interactive options in TWS Jobs
Purchase Distributable version of latest Redemption.dll and use it

Windows Service - UnauthorizedAccessException Error when Installing Service (C#)

So I am trying to create a service using C# in Visual Studio 2017 and I keep getting an error when I try to install it.
Right now, I don't even have anything in my service, I just want to be able to install the service. I created a new Project in Visual Studio 2017 using the Windows Service (.NET Framework) template under Visual C# > Windows Desktop. I then added the installer via Right Click > Add Installer. For serviceProcessInstaller1, I set the account to LocalSystem. And...that's it!
Now, I try to install it. I open up command prompt (run as administrator) and I do
InstallUtil ServiceTest.exe
Things start off smoothly, but then I get a message:
"An exception occured during the Install phase.
System.UnauthorizedAccessException: Attempted to perform an
unauthorized operation."
What could be generating this message?
I've googled and tried the following things:
Ensure I run command prompt as administrator.
Assign Full Control to
the project folder to my admin account.
Configure permissions to Full
Control for admin account in the security log of regedit.
Log into my
computer as an administrator (rather than regular user) and run it
that way.
Despite these things, I keep getting the same error. What else could I be doing wrong? Would really appreciate some advice!
Note: I am trying to install this service locally on my computer.
Edit: Per request, here are the logs. I named my project "FailedService", by the way, since I can't get it to work!
InstallUtil.InstallLog
Running a transacted installation.
Beginning the Install phase of the installation.
See the contents of the log file for the C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe assembly's progress.
The file is located at C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog.
An exception occurred during the Install phase.
System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.
The Rollback phase of the installation is beginning.
See the contents of the log file for the C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe assembly's progress.
The file is located at C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog.
The Rollback phase completed successfully.
The transacted install has completed.
FailedService.InstallLog
Installing assembly 'C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe'.
Affected parameters are:
logtoconsole =
logfile = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog
assemblypath = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe
Installing service Service1...
Creating EventLog source Service1 in log Application...
Rolling back assembly 'C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe'.
Affected parameters are:
logtoconsole =
logfile = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog
assemblypath = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe
Restoring event log to previous state for source Service1.
I was FINALLY able to resolve this issue. I was able to get to the bottom of it by using SysInternal's Process Monitor. I opened up the program and had it take logs for InstallUtil.exe. From there, I began to search for any logs that said "Access Denied". As I sorted through them, I noticed something interesting: it was trying to create a registry key, but it kept failing!
So I went into the registry and created a key named "ServiceTest". After that, I ran the InstallUtil command again, and it worked!
If anyone else is having trouble, the solution is to create a key named after your process name in the following location:
HKLM\System\CurrentControlSet\Services\EventLog\Application\
Enter the full path to installUtil & your service binary in an elevated prompt, that could do.

Creating Table in Azure Storage Emulator produces HTTP 500 Error

I've been attempting to create a table through my machine's Azure storage emulator. I can recreate the problem with a very simple program that uses only WindowsAzure.Storage nuget version 6.2.0 :
using Microsoft.WindowsAzure.Storage;
namespace StorageEmulatorTest
{
internal class Program
{
private static void Main(string[] args)
{
var cloudStorageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
var cloudTableClient = cloudStorageAccount.CreateCloudTableClient();
cloudTableClient.GetTableReference("JohnnyTest").CreateIfNotExists();
}
}
}
After 25 seconds, this will throw an exception of type Microsoft.WindowsAzure.Storage.StorageException with only this message:
The remote server returned an error: (500) Internal Server Error.
I have attempted:
Ensuring my WindowsAzure.Storage nuget package is the latest version (6.2.0).
Re-installing the Azure SDK for VS2015 2.8.1 (and ensuring that it's the latest version)
Stopping, clearing, initing the Azure Storage Emulator through the Azure Storage Emulator command line tool (seemed to work fine, no errors)
Reading the web response's stream through the exception's ".InnerException.Response.GetResponseStream()". This fails with an exception that states "Stream was not readable".
Restarting my machine (desperation kicked in)
My bag of tricks is running low. Has anybody encountered this issue?
I solved it. I had to completely wipe out my existing local storage emulation instance. Using "AzureStorageEmulator.exe clear" or "AzureStorageEmulator.exe init" was insufficient. Even uninstalling the Azure SDK was insufficient.
I started by stopping the storage emulation:
AzureStorageEmulator.exe stop
AzureStorageEmulator.exe clear
AzureStorageEmulator.exe init /forceCreate
That last command errored and indicated that it could not create the database.
Then I deleted (actually, I renamed them) these remaining files that comprised the database behind the azure storage emulator:
C:\Users\[Me]\AzureStorageEmulatorDb42_log.ldf
C:\Users\[Me]\AzureStorageEmulatorDb42_log.mdf
Finally, I started the emulator back up
AzureStorageEmulator.exe init /forceCreate
AzureStorageEmulator.exe start
Success!
I'm unsure what got me into the situation, but my best guess is that this was caused by a recent upgrade of the Azure SDK.
I think in many cases Johnny's answer will solve the issue.
In my case this also did not work, because AzStorageEmulator did not create the database AzureStorageEmulator510 (database instance (localdb)\MSSQLLocalDB) and also not the tables within.
So I used SSMS to create database AzureStorageEmulator510 from scratch,
then I found that an older version AzureStorageEmulator57 was still on my PC, so I attached it (you can find the databases in C:\Users\YOURACCOUNT) - extracted the database structure to a SQL script and ran it for AzureStorageEmulator510.
After that, I started the emulator and created a new blob container using AzStorageExplorer.
The Error 500 seemed to occur because that database (and structure inside) was missing and could not be recreated by the CLI command AzureStorageEmulator.exe init /forceCreate.
Other things you can check (possible issues):
It can also be AzStorageEmulator can't access its database. One of the reasons (and how it can be fixed) is described here.
After installing a newer version of the instance (localdb)\MSSQLLocalDB, it can be that the related database is not attached. This will result in a strange error like
Cannot open database "AzureStorageEmulator510" requested by the login. The login failed. Login failed for user 'YOURACCOUNT'.
If that is the case, you can fix it by simply connecting to localDb via SSMS, then attach the database: Right-click on databases, select Attach... in the context menu, then in the dialog, add the database file (located in C:\Users\YOURACCOUNT).

Error while starting Storage Emulator on windows azure

I'm getting the error below while starting the storage emulator. By mistake I deleted the mdf and log files in users/admin folder. It's holding reference someplace and not allowing me to create the DB again. Please help me.
Added reservation for 127.0.0.1:10000/ in user account RaviBorra-PC\Ravi Borra.
Added reservation for 127.0.0.1:10001/ in user account RaviBorra-PC\Ravi Borra.
Added reservation for 127.0.0.1:10002/ in user account RaviBorra-PC\Ravi Borra.
Found SQL Instance (localdb)\v11.0.
Creating database DevelopmentStorageDb201206 on SQL instance '(localdb)\v11.0'.
Cannot create database 'DevelopmentStorageDb201206' : Database 'DevelopmentStorageDb201206' already exists. Choose a different database name..
One or more initialization actions have failed. Resolve these errors before attempting to run the storage emulator again. Please refer to http://go.microsoft.com/fwlink/?LinkID=248088 for more details.
Thank you,
Ravi Krishna B.
Do these steps:
Open cmd.exe (Command Prompt)
Write this:
SqlLocalDb stop "v11.0"
SqlLocalDb delete "v11.0"
and press Enter
Note that "v11.0" is MyInstance.
For more details, visit this link.
This problem may occur if you delete the data file C:\Users\<Username>\DevelopmentStorageDb201206.mdf but do not delete the corresponding database on the LocalDB server instance. One possible solution is:
Connect to the (localdb)\v11.0 instance from SQL Server Management Studio.
Delete the DevelopmentStorageDb201206 database. There will be the error message that the database deletion ended with an error. Ignore this message and refresh the database list manually.
Now you can start the Azure Storage Emulator.
This is not a problem related with Azure components rather LocalDB instance is reporting back to Azure request that DB still exist. Check LocalDB instances in your machine using "sqllocaldb i" first and the delete the instance using "sqllocaldb d 'instance_name'". I could not test it in my machine but this may unblock you if localdb instance is blocking you.
In Windows Azure SDK 1.7, Windows Azure Storage Emulator uses LocalDB instance specific configuration at following location:
%LocalAppData%\DevelopmentStorage\DevelopmentStorage.201206.config
And based on that you will see that v11.0 instance is Windows Azure Storage Emulator specific so verify if that is running and deleting it will let DSInit to create the DB again in LocalDB.
If you have Sql Express installed on your local box then (localdb)\v11.0 is most likely not your local Sql instance. It is more likely {MyComputerName}\SQLEXPRESS.
Going to:
C:\Users\<yourloginname>\AppData\Local\DevelopmentStorage\DevelopmentStorage.201206.config
And changing:
<SQLInstance>(localdb)\v11.0</SQLInstance>
To:
<SQLInstance>{MyComputerName}\SQLEXPRESS</SQLInstance>
solved this error for me.
I hope this helps..
If you already tried and failed perform:
SQLLocalDB stop v11.0
SQLLocalDB delete v11.0
Delete all the files in C:\Users\<accontname>\WAStorageEmulatorDb* (usually one mdf and one ldf)
Create a new account (I called it Azure, with administrative rights)
Run again the installation
Installation completed!
For me this works... I had tried to format the PC before use this way. I supposte my problem is related to my username that contains "invalid" characters like Name 'NickName' Surname while the "Azure" account seems to be OK for him.
I figure it out 'cause somewhere in the log I have a property destination path set to "C:\Users\Name$_" that is far away for the path of my user account folder.
After that you can go on CMD.exe and prompt:
control userpasswords2
From the control you can delete the Azure login without delete the file folders!
Hope it helps!
I simply deleted all the mdf's and ldf's in C:\Users\accountname\ that started with DevelopmentStorage... or WAStorageEmulator.
Re-ran the install and it worked.
This can also be caused by the folder not existing for localDB. It looks like Visual Studio / Azure will not automatically create containing folders. I just copied the path from the error code into explorer and created the directory up to the .MDF file.
In visual studio go to Tools -> Options -> Database Tools-> Data connections and change a localdb instance name from v11.0 to some other name.
I did have SQL Express installed, as Brian Ogden suggested in his answer, but I wanted to try & point Azure Storage Emulator to my SQL Express instance without modifying configuration files.
I did this by running the initialization process for Storage Emulator & passing my server\instance details for SQL Express using the available switches. Below example of the command I executed (from an elevated command prompt):
AzureStorageEmulator.exe init -server MY-PC-NAME -instance MYSQLINST
This created the database successfully (in my SQL Express instance) & got my Storage Emulator working.
I am using a named instance, but I'm thinking this same approach can be used for default instances by omitting the -instance switch.

Categories

Resources