I'm creating a wpf application for internal deployment.
A user using the software is getting the following error when trying to create an excel interop instance.
Retrieving the COM class factory for component with CLSID (...) failed due to the following error: 80070002 The system cannot find the file specified
The section that is catching the error is the following
try
{
_excelApplication = new Microsoft.Office.Interop.Excel.Application();
GetWindowThreadProcessId(_excelApplication.Hwnd, out ExcelAppProcessId);
_excelApplication.ScreenUpdating = false;
}
catch(Exception e)
{
//TODO Move message box to parents
MessageBox.Show($"Termination Error: Could not open Excel Application: {e.Message}");
Environment.Exit(110);
}
Previously the same user had an issue while trying to open Access (can't remember what the exact error was) and I implemented the following to fix it.
try
{
//MessageBox.Show($"OS: {EnvironmentFunctions.is64BitOperatingSystem} Process: {EnvironmentFunctions.is64BitProcess}");
if (EnvironmentFunctions.is64BitOperatingSystem && !EnvironmentFunctions.is64BitProcess)
{
string PathValue = "";
string sAdd = "";
string strCommonFiles =
Environment.GetEnvironmentVariable("CommonProgramFiles(x86)");
sAdd = ";" + strCommonFiles + "\\microsoft shared\\DAO";
PathValue = Environment.GetEnvironmentVariable("Path");
PathValue += sAdd;
Environment.SetEnvironmentVariable("path", PathValue);
}
_accessApplication = new Microsoft.Office.Interop.Access.Application();
GetWindowThreadProcessId(_accessApplication.hWndAccessApp(), out AccessAppProcessId);
}
catch
{
MessageBox.Show("Termination Error: Could not open Access Application");
Environment.Exit(110);
}
Would there be a similar solution but for the Excel interop?
Notes about the user: They are one of the few left running windows 7.
Retrieving the COM class factory for component with CLSID (...) failed due to the following error: 80070002 The system cannot find the file specified
Typically this error is caused by only a few issues, which I will list below.
Recent Windows updates
Partition issue's and or problems
Bitness issue's (determined what Office is installed on the end machine and what the application is compiled against)
I asked earlier about what you were targeting because you have some code that is checking if the pc is 64bit and you have already ran into some issues. This then lead me to bitness issues with creating instances of Excel.
My recommendation and solution to your exact issue is because the end machine is 32bit, so compiling for x86/32bit should fix the issue.
On a final note, you may be able to remove that old code as it wouldn't be needed anymore.
My basic problem was converting a .docx file to .pdf. The problem would be solved incase I was allowed to use Microsoft.Office.Interop.Word.dll, which i am not since the server will not have MS Office installed. So I needed a free/open-source library that would allow me to do so. And i came across docx4j.NET.
http://www.docx4java.org/blog/2014/09/docx-to-pdf-in-c-net/
This worked fine as long as I ran it as a Console App. The following is the concerned code snippet:
string fileIN = #"C:\Users\...\Visual Studio 2013\Projects\HRDapp\HRDapp\Letter_Templates\AP.docx";
string fileOUT = #"C:\Users\...\Visual Studio 2013\Projects\HRDapp\HRDapp\Letter_Templates\AP.pdf";
log.Info("Hello from Common Logging");
// Necessary, if slf4j-api and slf4j-NetCommonLogging are separate DLLs
ikvm.runtime.Startup.addBootClassPathAssembly(
System.Reflection.Assembly.GetAssembly(
typeof(org.slf4j.impl.StaticLoggerBinder)));
// Configure to find docx4j.properties
// .. add as URL the dir containing docx4j.properties (not the file itself!)
Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + #"src\samples\resources\");
java.io.File file = new java.io.File(fileIN);
// OK, do it..
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file);
java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(fileOUT));
org.docx4j.Docx4J.toPDF(wordMLPackage, fos);
fos.close();
In case of using this in a Web App, the code runs fine till
java.io.File file = new java.io.File(fileIN);
and gets stuck at
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file);
Although the file path is correct and works fine in the console app, but there seems something else that I am missing here. The log also prints upto the following statement-
iisexpress.exe Information: 0 : [INFO] org.docx4j.jaxb.Context - Using Java 6/7 JAXB implementation
.. and stops. Any kind of reply directing me to the source of the error will be very helpful. Thanks.
As Jeroen (of IKVM fame) has explained, when there is no main assembly (eg in an ASP.NET application), the IKVM class loader can't find your assembly when the code is trying to dynamically load a class.
So you'll want to add not just:
ikvm.runtime.Startup.addBootClassPathAssembly(
System.Reflection.Assembly.GetAssembly(
typeof(org.slf4j.impl.StaticLoggerBinder)));
but also:
ikvm.runtime.Startup.addBootClassPathAssembly(
System.Reflection.Assembly.GetAssembly(
typeof(org.slf4j.LoggerFactory)));
ikvm.runtime.Startup.addBootClassPathAssembly(
System.Reflection.Assembly.GetAssembly(
typeof(org.docx4j.jaxb.Context)));
Similar questions have been asked before, but I want to try and refine it to my situation.
I am downloading a legacy file type (Excel 2003 (.xls)) and I need to strip the data from the file. The problem is I get :
{"Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass'
to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed
because the QueryInterface call on the COM component for the interface
I am currently trying to get this working on my machine before I send the app to production, which will/does have excel on the server.
I have tried reinstalling office, but that did not work. I think the problem lies more in the fact that I have office 2013 on my box and I am attempting to run a decade old file type through it.
I tried to use this:
public void Convert(String file)
{
var app = new Application();
var wb = app.Workbooks.Open(file);
wb.SaveAs(file + "x", XlFileFormat.xlOpenXMLWorkbook);
wb.Close();
app.Quit();
}
That still causes the same problem, because the file will not open.
Any suggestions?
UPDATE
Here is the full method I am using
public Worksheet GetExcelBy(string url)
{
var fileName = #"C:\temp\tempfile.xls";
var webClient = new WebClient();
webClient.DownloadFile(url, fileName);
Convert(fileName);
var excel = new Application();
var workbook = excel.Workbooks.Open(fileName);
return (Worksheet)workbook.Worksheets["Data 6"];
}
this is the URL:
http://tonto.eia.doe.gov/dnav/pet/xls/pet_pri_spt_s1_d.xls
I presume the line with var excel = new Application(); is the line where the exception is raised. From my experience in the matter, as I also tried to follow other advice found on the internet, the solution I accidentally found was to explicitly define the non use of 32 bit access mode for the interop dll.
For doing so in visual studio, I had to tick and then untick the box "Prefer 32-bit" in the build section of the project configuration, which added <Prefer32Bit>false</Prefer32Bit> in the .csproj file.
I have a SSIS package with a script task, I get the following error when i try to run it in my local system. It works fine for my collegues as well as in production. However, I am not able to run it locally, to test. I keep a debug point in the main method, but it is never reached, I get the error before it goes to main method.
I am using VS 2010, .Net framework 4.5.
The script task does compile. I get the following messages SSIS package "..\Test.dtsx" starting. Error: 0x1 at Test: Exception has been thrown by the target of an invocation. Task failed: Test SSIS package "..\Test.dtsx" finished: Success. The program '[2552] DtsDebugHost.exe: DTS' has exited with code 0 (0x0).
The following is the code:
public void Main()
{
try
{
LogMessages("Update Bug package execution started at :: " + DateTime.Now.ToLongTimeString());
LogMessages("Loading package configuration values to local variables.");
strDBConn = Dts.Variables["User::DBConnection"] != null ? Dts.Variables["User::DBConnection"].Value.ToString() : string.Empty;
strTPCUrl = Dts.Variables["User::TPCUrl"] != null ? Dts.Variables["User::TPCUrl"].Value.ToString() : string.Empty;
TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl));
WorkItemStore objWIS = new WorkItemStore(objTPC);
WorkItemCollection objWIC = objWIS.Query("SELECT...");
foreach (WorkItem wi in objWIC)
{
}
}
catch(Exception ex)
{
}
When I commented the code from TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl)); The script executes successfully. However, if i keep TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl)); and comment the rest, i get the exception.
I do have access to the URL.
I am using Microsoft.TeamFoundation.Client.dll and Microsoft.TeamFoundation.WorkItemTracking.Client.dll, in my script task. However the dll version in the package is 10.0, and the version of the dll in my GAC is 12.0. Would that cause a problem?
I had the same Problem (i.e. the same error code Error: 0x1 ...).
The issue was with some of the libraries referenced from a missing folder.
Removing the references and adding them back from the correct path fixed the issue.
The Microsoft Reference (https://msdn.microsoft.com/en-us/library/ms345164.aspx) related to the Error code is very generic and doesn't help you much.
However, reading other articles it is quite likely it indicates an unknown failure reason to run the Script Task.
Hexadecimal code: 0x1
Decimal Code: 1
Symbolic Name: DTS_MSG_CATEGORY_SERVICE_CONTROL
Description: Incorrect function.
I got this error message when I referred to a passed ssis variable in Dts.Variables["User::xxxx].Value(); where xxxx did not exist and was not passed from the calling program. It was a simple Console.Writeline referring to a passed variable that didn't exist.
I fixed this error by changing the TargetServerVersion of the SSIS Project.
Integration Services Project Property Pages
This is just a different situation and not intended to be the end all be all solution for everyone.
When I was installing my DLLs into the GAC I forgot to run my script as Administrator and the script ran silently without error as though it was working.
I felt really dumb when I realized that's what I did wrong. Hopefully this can help prevent other people from wasting time on something so silly.
For reference this is what I use for installing my DLLs into the GAC and I modified it to tell me when I am not running it as Administrator now:
#https://superuser.com/questions/749243/detect-if-powershell-is-running-as-administrator
$isAdmin = ([Security.Principal.WindowsPrincipal] `
[Security.Principal.WindowsIdentity]::GetCurrent() `
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if($isAdmin -eq $false)
{
Write-Host "You have to run this script as Administrator or it just won't work!" -ForegroundColor Red
return;
}
$strDllPath = "C:\PathToYourDllsHere\"
#Note that you should be running PowerShell as an Administrator
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$arr = #(
"YourDLL01.dll",
"YourDLL02.dll",
"YourDLL03.dll"
)
get-date
foreach($d in $arr)
{
$p = ($strDllPath + $d);
$p
$publish.GacInstall($p);
}
#If installing into the GAC on a server hosting web applications in IIS, you need to restart IIS for the applications to pick up the change.
#Uncomment the next line if necessary...
#iisreset
Credit for how to determine if your PowerShell script is running in Admin mode or not:
https://superuser.com/questions/749243/detect-if-powershell-is-running-as-administrator
In my case it was missing DLLs or not having the correct version installed on the server.
Locally all tests were fine but on the server the error message Runtime error Exception has been thrown by the target of an invocation kept popping up.
No exception handler would be able to catch that error - the code in the script task would not even be executed, as soon as a DLL would be needed, that is not in the assembly cache on the server (it could happen on a local machine as well, with the same error).
The difficulty here is finding out what is missing and then either update the references to the correct version or install the missing DLL in the assembly cache with gacutil. The way I approached the debugging was to remove parts of the code in the script task until that error wouldn't appear, then analyze the missing part for references.
After not having any luck with the other answers here, I finally found that in my package, the problem was that I had created a new variable but not carried its name across into my new copy of the C# script. The variables were the ones to be used as connection string expressions. So it was ultimately a matter of changing:
Dts.Variables["Exists"].Value = File.Exists(Dts.Variables["OldSSISPackageVariableName"].Value.ToString());
to:
Dts.Variables["Exists"].Value = File.Exists(Dts.Variables["NewSSISPackageVariableName"].Value.ToString());
Once I kept them in sync, it worked fine.
Its fixed, when added reference to dll version 12.0.0 and changed Target Framework to .Net Framework 4.5
My problem was that I, in the script task, tried to fetch data like this:
public void Main()
{
using (var connection = Dts.Connections["localhost.Test"].AcquireConnection(Dts.Transaction) as SqlConnection)
{
connection.Open();
var command = new SqlCommand("select * from Table;", connection);
var reader = command.ExecuteReader();
while (reader.Read())
{
MessageBox.Show($"{reader[0]} {reader[1]} {reader[2]}");
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
However, my connection is of the type OLE DB, and therefore I needed to connect to it like this instead:
public void Main()
{
var connectionString = Dts.Connections["localhost.Test"].ConnectionString;
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
var command = new OleDbCommand("select * Table;", connection);
var reader = command.ExecuteReader();
while (reader.Read())
{
MessageBox.Show($"{reader[0]} {reader[1]} {reader[2]}");
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
Notice that I'm using OleDbConnection here.
For me what fixed the issue was updating the string parameter I passed to the script. it was missing "" at the end of the path (i.e. "e:\arcive" - needed to add "" at the end)
I have a problem when trying to read .csv file with STATCONNECTORSRVLib (R(D)COM).
When I enter this code lines, it works:
var sc1 = new STATCONNECTORSRVLib.StatConnector();
sc1.Init("R");
sc1.EvaluateNoReturn("dataset=read.csv(file.choose())");
A pop up windows is opened, I choose file from c:\\ , it loads, and I can do calculation with it.
However, when I enter this almost exact code:
var sc1 = new STATCONNECTORSRVLib.StatConnector();
sc1.Init("R");
sc1.EvaluateNoReturn("dataset=read.csv('C:\\output.csv')");
I get this annoying exception:
"The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))"
The line dataset=read.csv('C:\\output.csv') works fine in R console.
What am I doing wrong, and how can my machine read file when I'm uploading manualy, but not automaticly?
I'm using: R 2.13.1 from RandFriend pack, and have all that is included within it.
OS Windows 7, 64 bit
All my projects in the solution are .NET 4, x86
Not tested, but I think C# is treating converting your double backslashes to a single backslash, which R is then interpreting as an escape sequence. Try changing your string to
"dataset=read.csv('C:\\\\output.csv')"
or
#"dataset=read.csv('C:\\output.csv')"
or
"dataset=read.csv('C:/output.csv')"