I try to execute a very simple SSIS Package using C#.
This package works fine when starting directly in Visual Studio 2015.
The name of the SSIS package is "Lesson 1.dtsx".
I try to start this process using C# with the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace run_ssis_project
{
public class ExecuteSSIS
{
public void exePackage()
{
String pkgLocation = #"C:\SSIS Tutorial\Lesson 1.dtsx";
Microsoft.SqlServer.Dts.Runtime.Package ssisPackage;
Microsoft.SqlServer.Dts.Runtime.Application app;
Microsoft.SqlServer.Dts.Runtime.DTSExecResult result;
app = new Microsoft.SqlServer.Dts.Runtime.Application();
ssisPackage = app.LoadPackage(pkgLocation,null);
result = ssisPackage.Execute();
if(result == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Failure");
}
}
}
}
When executing this code, I get an exception:
"Microsoft.SqlServer.Dts.Runtime.DtsRuntimeException", The package
failed to load due to error 0xC0011008 "Error loading from XML. No
further detailed error information.
The exception occurs in line: ssisPackage =
app.LoadPackage(pkgLocation,null);
I added two DLLs as references in this project:
Microsoft.SqlServer.DTSRuntimeWrap.dll
Microsoft.SqlServer.ManagedDTS.dll
Can someone help me please?
I didnt have any problem besides that i got an error about mix mode because it was running version 2.0 against a framework with version 4.0. So if this doesnt work you proberbly has an error in your ssis-package. Otherwise try to make a new ssis-packages which basically does nothing and see if you get success.
This is how my code looks like:
using Microsoft.SqlServer.Dts.Runtime;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
string pkgLocation;
Package pkg;
Application app;
DTSExecResult pkgResults;
MyEventListener eventListener = new MyEventListener();
pkgLocation =
#"C:\Users\thoje\Documents\Visual Studio 2015\Projects\Integration Services Project8\Integration Services Project8\Package37.dtsx";
app = new Application();
pkg = app.LoadPackage(pkgLocation, eventListener);
pkgResults = pkg.Execute(null,null,eventListener,null,null);
Console.WriteLine(pkgResults.ToString());
Console.ReadKey();
}
}
class MyEventListener : DefaultEvents
{
public override bool OnError(DtsObject source, int errorCode, string subComponent,
string description, string helpFile, int helpContext, string idofInterfaceWithError)
{
// Output Error Message
Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
return false;
}
}
}
And this is what i needed to correct in app.Config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
Related
I created a SSIS script task which reads data from excel sheets and saves it into different tables in SQL Server DB. When I execute the SSIS package inside Visual Studio SSDT it works fine.
When I am trying to execute my SSIS package from C# .NET code I get the following error.
Error in Microsoft.SqlServer.Dts.Runtime.TaskHost/Script Task : There was an exception while loading Script
Task from XML: System.Exception: The Script Task "ST_71d9425916264171ab93a0d340aad54d" uses version 14.0 script
that is not supported in this release of Integration Services. To run the package, use the Script task to create
a new VSTA script. In most cases, scripts are converted automatically to use a supported version,when you open a
SQL Server Integration Services packages in %SQL_Product_Short_Name% Integrtion Services.
I tried to change the deployment version by changing the TargetServerVersion to SQL server 2016 but I still get the same error.
Here is my code to execute the package.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Dts.Runtime;
namespace Execute_DriverImpact
{
class MyEventListener : DefaultEvents
{
public override bool OnError(DtsObject source, int errorCode, string subComponent,
string description, string helpFile, int helpContext, string idofInterfaceWithError)
{
// Add application-specific diagnostics here.
Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
return false;
}
}
class Program
{
static void Main(string[] args)
{
// The code provided will print ‘Hello World’ to the console.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
//Console.WriteLine("Hello World!");
//Console.ReadKey();
//ExecuteSSIS exec = new ExecuteSSIS();
//exec.ExePackage();
//ExecuteSSIS2 exec = new ExecuteSSIS2();
//exec.ExePackage2();
string pkgLocation;
Package pkg;
Application app;
DTSExecResult pkgResults;
MyEventListener eventListener = new MyEventListener();
pkgLocation =
#"D:\Driver_Impact\Driver_Impact\Package.dtsx";
app = new Application();
pkg = app.LoadPackage(pkgLocation, eventListener);
pkgResults = pkg.Execute(null, null, eventListener, null, null);
Console.WriteLine(pkgResults.ToString());
Console.ReadKey();
}
}
}
Tech Stack
Visual Studio 2017 with SSDT
SQL server 2016
This question already exists:
COM+ component - Class not registered error [closed]
Closed 2 years ago.
I have an application which is in Delphi and interacts with other .NET application through old COM+ component. The component is invoked from Delphi code and there was no issue until Microsoft introduced some security patches on Feb 11, 2020 (this year).
The issue it throws now is "Class not registered" After searching a lot on Google, I have tried the following things :
As this COM+ component is written in .NET (ComVisible attribute, had an assumption that it needs to be registered again. So tried to register it usign RegAsm using :
Regasm
But it didn't work though
Confirmed if assembly is in GAC. it is placed there indeed.
List item
Deleting registration of the DLL and then registering using regasm /u but that also provided no luck.
Some blogs over google suggested about COM+ security. Tried playing with that to.
Disabled the COM+ component to test whether COM+ component has any impact and yes indeed it turned to different error. Something like COmponent doesn't exist.
Someone suggested to run DCOMCNFG and traverse into DCOM config tree and press "Yes" if there are warnings to record the anomalies in registry. Still no luck.
Opened up Registry using RegEdit and tried to permit full control on relevant registries including Microsoft Ole. Still didn't work
Also, there were some thoughts around COM security, it was also checked and was permitted well.
The caveat is if we revert the microsoft patches, it works well again. I matched all the security settings before and after the patches which seems same.
PLEASE suggest if someone has sound knowledge about it.
Adding more details:
COM+ Component
COM component properties
Here is the .NET COM component code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.EnterpriseServices;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Text;
using System.Threading;
using System.Xml.XPath;
using Acclipse.Config;
using Acclipse.FileSystem.Shared;
using Aspose.Words;
[assembly: ApplicationActivation(ActivationOption.Library)]
[assembly: ApplicationAccessControl(false)]
[assembly: ApplicationName("Acclipse FileSystem Client")]
[assembly: Description("Client to communicate with the Acclipse FileSystem server.")]
namespace Acclipse.FileSystem
{
class Singleton
{
private static Singleton m_Instance = new Singleton();
private Singleton()
{
Trace.WriteLine("Singleton.Create");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
private IRemotedFS m_IRemotedFS;
public static Singleton Instance
{
get
{
return m_Instance;
}
}
internal static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
Trace.WriteLine("CurrentDomain_AssemblyResolve", "Acclipse.FileSystem");
try
{
string[] parts = args.Name.Split(',');
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), string.Format("{0}.dll", parts[0]));
//Trace.WriteLine(string.Format("Loading resolved assembly at {0}", path), "Acclipse.Licencing");
Assembly a = Assembly.LoadFile(path);
Trace.WriteLine(string.Format("Assembly is {0}, looking for {1}", a.FullName, args.Name), "Acclipse.FileSystem");
if (a.FullName != args.Name)
{
throw new ApplicationException("Unable to load correct assembly");
}
return a;
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Failed to resolve with error {0}", ex.Message), "Acclipse.FileSystem");
}
return Assembly.GetExecutingAssembly();
}
public IRemotedFS FS
{
get
{
Trace.WriteLine("Get IRemotedFS", "Acclipse.FileSystem");
if (m_IRemotedFS == null)
{
try
{
Trace.WriteLine("Creating IRemotedFS", "Acclipse.FileSystem");
Trace.WriteLine("Configfile at " + Path.GetFullPath("Config.file"), "Acclipse.FileSystem");
ConfigFile config = ConfigFile.FromFile("Config.file");
Trace.WriteLine("Loading url", "Acclipse.FileSystem");
string url = config["FileStore.Url"];
if (string.IsNullOrEmpty(url))
{
throw new ApplicationException("Url of server is not configured in Config.file");
}
Trace.WriteLine(string.Format("Url is {0}", url));
TcpClientChannel chan = new TcpClientChannel();
ChannelServices.RegisterChannel(chan, false);
m_IRemotedFS = Activator.GetObject(typeof(IRemotedFS), url) as IRemotedFS;
if (m_IRemotedFS == null)
{
Trace.WriteLine("Oops, RemoteFS is null!!");
}
}
catch (Exception e)
{
Trace.WriteLine(string.Format("Error in getting FS *** {0} - {1}", e.Message, e.StackTrace));
throw;
}
}
Trace.WriteLine("..Done");
return m_IRemotedFS;
}
internal set
{
m_IRemotedFS = value;
}
}
}
[ComVisible(true)]
[ProgId("Acclipse.FileSystem.SqlZipClient.SqlZipFileSystemRemote")]
[Guid("5A940543-24EF-4f31-B45B-6832C8211986")]
[ClassInterface(ClassInterfaceType.None)]
[JustInTimeActivation(true)]
public class SqlZipFileSystemRemote : ServicedComponent, IFileSystem
{
private IConfigFile m_Config;
public SqlZipFileSystemRemote()
{
Trace.WriteLine("SqlZipFileSystemRemote Created", "Acclipse.FileSystem");
m_Config = DefaultConfigFile.FromFile("Config.file");
}
static SqlZipFileSystemRemote()
{
Trace.WriteLine("Set Aspose.Words license info", "Acclipse.FileSystem");
try
{
new License().SetLicense("Acclipse.FileSystem.SqlZipClient.Aspose.Words.lic");
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Exception encountered setting license details: {0}", ex.StackTrace), "Acclipse.FileSystem");
throw;
}
Trace.WriteLine("Done", "Acclipse.FileSystem");
}
internal void AttachConfigFile(IConfigFile config)
{
this.m_Config = config;
}
}
}
I seem to be unable to use this library in project
Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'WindowsAzure' could not be found (are you missing a using directive or an assembly reference?) ClassLibrary2 \Visual Studio 2017\Projects\ClassLibrary2\ClassLibrary2\EntityListener.cs 24 Active
using WindowsAzure.Servicebus;
I installed using nuget packet manager, and it is defined in my packages.config file. Why can I not use it?
Packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="WindowsAzure.ServiceBus" version="4.1.10" targetFramework="net452" />
</packages>
If your .NET project version is exactly 4.5 (not 4.5.x), you will need to fall back to WindowsAzure.ServiceBus package version 4.1.3. Moreover, this
Here is the packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="WindowsAzure.ServiceBus" version="4.1.3" targetFramework="net45" />
</packages>
In addition, the correct namespace to use is the following:
using Microsoft.ServiceBus.Messaging;
Find below a sample .NET 4.5 Console Application that sends a message to an Azure Service Bus Queue. Please note this is just a sample and it is not production ready code. I hope this helps.
using System;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;
namespace ServiceBusSample
{
class Program
{
static void Main(string[] args)
{
const string ConnectionString = "your service bus connection string";
const string QueueName = "your service bus queue name";
string message = "Hello World!";
string sessionId = Guid.NewGuid().ToString();
SendMessage(ConnectionString, QueueName, sessionId, message).Wait();
Console.WriteLine("Press <ENTER> to exit...");
Console.ReadLine();
}
private static async Task SendMessage(string connectionString, string queueName, string sessionId, string message, string correlationId = null)
{
try
{
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new ArgumentException("Service bus connection string cannot be null, empty or whitespace.");
}
if (string.IsNullOrWhiteSpace(queueName))
{
throw new ArgumentException("Service bus queue name cannot be null, empty or whitespace.");
}
if (string.IsNullOrWhiteSpace(sessionId))
{
throw new ArgumentException("Session id cannot be null, empty or whitespace.");
}
QueueClient queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName);
BrokeredMessage brokeredMessage = new BrokeredMessage(message);
brokeredMessage.SessionId = sessionId;
await queueClient.SendAsync(brokeredMessage);
}
catch
{
// TODO: Handle exception appropriately (including logging)
throw;
}
}
}
}
Can I start appname.vshost.exe from debug folder under different username than the one used to start VisualStudio?
There is appname.vshost.exe.config with the following content. Is there a config for username? I have tried searching for it but couldn't find anything.
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
If you're trying to run your debugg executable
You can try shift right click and Run as different user.
Or do you want to run as different user via configuration?
I don't think you can start vshost.exe under different user than the one you have used to start Visual Studio. So now I am starting main console app under different user from another console app and attaching debugger to it and it works.
I have copied my code below if it helps anyone.
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using EnvDTE80;
using Process = System.Diagnostics.Process;
namespace StartService
{
class Program
{
static void Main(string[] args)
{
var secure = new SecureString();
foreach (var c in "password-from-config")
{
secure.AppendChar(c);
}
Process process = null;
try
{
process = Process.Start(#"C:\Test Projects\WcfServiceTest\WcfServiceTest\bin\Debug\WcfServiceTest.exe",
"TestUser", secure, "DomainName");
Attach(GetCurrent());
Console.ReadKey();
}
finally
{
if (process != null && !process.HasExited)
{
process.CloseMainWindow();
process.Close();
}
}
}
public static void Attach(DTE2 dte)
{
var processes = dte.Debugger.LocalProcesses;
foreach (var proc in processes.Cast<EnvDTE.Process>().Where(proc => proc.Name.IndexOf("WcfServiceTest.exe") != -1))
proc.Attach();
}
internal static DTE2 GetCurrent()
{
var dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.12.0"); // Specific to VS2013
return dte2;
}
}
}
I have a very large sql file I want to break up into batches for execution.
I want to make sure I'm parsing it the same way that SSMS and SQLCMD do.
Microsoft has a great mixed mode assembly named Microsoft.SqlServer.BatchParser with a class named Parser that seams like it would do the trick.
It wants an implementation of IBatchSource as an argument to SetBatchSource before calling Parse().
Where can I find an implementation of IBatchSource, and more information on how to make use of this functionality?
I found the assembly Microsoft.SqlServer.BatchParser in the GAC along with it's friend Microsoft.SqlServer.BatchParserClient that contains implementations the interface IBatchSource.
namespace Microsoft.SqlServer.Management.Common
{
internal class BatchSourceFile : IBatchSource
internal class BatchSourceString : IBatchSource
}
The following conversation then occurred.
Assembly: Hello! My name is
Microsoft.SqlServer.Management.Common.ExecuteBatch. Would you like to StringCollection GetStatements(string sqlCommand)?
Me: Yes, I would, BatchParserClient assembly. Thanks for asking!
Repeatable Instructions (Do try this at home!)
Install Microsoft SQL Server 2008 R2 Shared Management Objects
Copy Microsoft.SqlServer.BatchParser.dll and Microsoft.SqlServer.BatchParserClient.dll from the GAC to a folder in your solution.
Reference Microsoft.SqlServer.BatchParser & Microsoft.SqlServer.BatchParserClient
Program.cs
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using Microsoft.SqlServer.Management.Common;
namespace ScriptParser
{
class Program
{
static void Main(string[] args)
{
ExecuteBatch batcher = new ExecuteBatch();
string text = File.ReadAllText(#"Path_To_My_Long_Sql_File.sql");
StringCollection statements = batcher.GetStatements(text);
foreach (string statement in statements)
{
Console.WriteLine(statement);
}
}
}
}
App.Config
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
</configuration>
Another option is to use the ScriptDom as described in this answer: https://stackoverflow.com/a/32529415/26877.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.SqlServer.TransactSql.ScriptDom;
namespace ScriptDomDemo
{
class Program
{
static void Main(string[] args)
{
TSql120Parser parser = new TSql120Parser(false);
IList<ParseError> errors;
using (StringReader sr = new StringReader(#"create table t1 (c1 int primary key)
GO
create table t2 (c1 int primary key)"))
{
TSqlFragment fragment = parser.Parse(sr, out errors);
IEnumerable<string> batches = GetBatches(fragment);
foreach (var batch in batches)
{
Console.WriteLine(batch);
}
}
}
private static IEnumerable<string> GetBatches(TSqlFragment fragment)
{
Sql120ScriptGenerator sg = new Sql120ScriptGenerator();
TSqlScript script = fragment as TSqlScript;
if (script != null)
{
foreach (var batch in script.Batches)
{
yield return ScriptFragment(sg, batch);
}
}
else
{
// TSqlFragment is a TSqlBatch or a TSqlStatement
yield return ScriptFragment(sg, fragment);
}
}
private static string ScriptFragment(SqlScriptGenerator sg, TSqlFragment fragment)
{
string resultString;
sg.GenerateScript(fragment, out resultString);
return resultString;
}
}
}