Adding existing project into new VS2012 solution programmatically fails - c#

We have the following code in wizard to add existing project to a new solution:
//generating files
if (dte.Solution.Projects.Count < 1) // Solution is empty or doesn't exist
{
dte.Solution.Create(oneFolderHigher(Params.OutputDir, solutionName),
solutionFileName(solutionName));
}
// adding created project to solution
dte.Solution.AddFromFile(Path.Combine(Params.ProjectRootFolder,
Params.ProjectName + ".csproj"));
It works just fine under MS Visual Studio 2010, but fails under 2012 (I experimented with second parameter):
System.Runtime.InteropServices.COMException (0x80004004): Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
at EnvDTE.SolutionClass.AddFromFile(String FileName, Boolean Exclusive)
at Wizard.Generator.NewProjectGenerator.Generate(Action`1 logMessage)
at Wizard.Forms.WizardForm.Finish()
After this error I'm adding the new project to the solution manually and everything works OK. But we can not just say, "Sorry, we can not add newly generated project for you so please add it by yourself."
MSDN proposes:
You can use the LaunchWizard method rather than AddFromFile to execute a wizard if you want to suppress its UI during execution. LaunchWizard has a parameter that allows you to disable the UI.
But this method requires some wizard file, so it can not be a solution.
Could someone help?
Wizard is running from "New -> Project" menu.

Here the workaround for the issue (proposed by my boss):
Before adding the project to solution, project file should be converted to
VS2012 format.
But code is little ugly:
using (StreamReader sr = new StreamReader(newFile))
using (StreamWriter sw = new StreamWriter(projectFile, false, Encoding.UTF8))
{
while (sr.Peek() >= 0)
{
string s = sr.ReadLine();
if (s.Contains("<Project ToolsVersion=\"4.0\""))
{
s = s + Environment.NewLine + importProject;
}
... and so on
Maybe someone knows the way to do it awesome? I mean converting. I'll let the question to be unanswered some time. Waiting for your comments.

Related

Null Reference Exception when calling iText7 PdfAcroForm.GetAcroForm() in .Net Core 3.1 class library

I am working on converting an application to .Net Core 3.1, and in my class library I am generating a PDF form from an existing template, and filling that form with data. In ITextSharp, the predecessor to IText7, the PdfAcroForm static method ".GetAcroForm()" worked perfectly, but in the current version of iText7 (7.1.12) a Null Reference Exception is thrown. I have followed the documentation to the best of my ability, but I am unsure how to continue. Any suggestions would be appreciated.
NOTE: The template path exists, the new document shows that it has been filled properly, and it is impossible to "new" a PdfAcroForm, you are required to use the static .GetAcroForm() method.
A null check will not solve this issue, as the object should never be null. The documentation indicates that the .GetAcroForm() method will create a new form if the parameter "createNotExist" is set to true, which I have done here.
I have researched and have located an issue on the iText GitHub that indicates that this issue was "fixed" around a year ago: https://github.com/itext/itext7/pull/44#issue-351612749
The following is the method which prepares the forms:
public string DocumentGenerator(string templatePath, FormFieldSet[] formFieldSet, bool useSpecailOutputPath)
{
if(!File.Exists(templatePath))
{
throw new Exception("The template file provided does not exist: MC-071(iText)");
}
string newFile = useSpecailOutputPath ?
m_SpecialOutputPath :
Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf";
try
{
PdfDocument newDocument = new PdfDocument(new PdfReader(templatePath), new PdfWriter(newFile));
PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(newDocument, true); // <=== Exception Thrown Here
foreach (FormFieldSet fs in formFieldSet)
{
acroForm.GetField(fs.FieldName).SetValue(fs.FillValue);
}
// Sets form flattening
acroForm.FlattenFields();
// Closes and writes the form
newDocument.Close();
return newFile;
}
catch { return string.Empty; };
}
Any suggestions would be greatly appreciated
I had the same problem, and after digging down all the way to iText7's internal objects and methods, I finally "solved" my problem.
Apparently iText has some internal errors/exceptions that they are just sort of "skipping" and "pushing past", because I realized by accident that I had "Enable Just My Code" in Visual Studios disabled, and so my system was trying to debug iText7's code as well as mine. The moment that I re-enabled it in my Visual Studio settings (Tools > Options > Debugging > General > Enable Just My Code checkbox), the problem magically went away.
So I spent four hours trying to troubleshoot a problem that was in THEIR code, but that they apparently found some way to work around and push through the method anyways even on a null reference failure.
My convert to PDF function is now working just fine.
Just an update to anyone looking for this issue. This is a known issue and is fixed in the current development branch. You are safe to bypass the exception in visual studio until it is corrected. This has no negative impact on the functionality and is the result of a misplaced return in the original iText7 source.

SSIS Script Task is not running code inside but not failing

I'm new in generating SSIS packages programmatically and I have an issue in one of the components that I'm generating.
I'm generating a Script Task programmatically with the code below:
private void EditScriptTask(ref ScriptTask pScriptTask, List<VariablesSsis> variablesSsis)
{
pScriptTask.ScriptProjectName = ScriptTaskProjectName;
// Set the script language - "CSharp"
pScriptTask.ScriptLanguage = VSTAScriptLanguages.GetDisplayName("CSharp");
// Set variables to be used in the script task code (read and write variables)
pScriptTask.ReadWriteVariables = ReadVariableScriptString(variablesSsis);
// Create a new project from the template located in the default path - script task associated project
pScriptTask.ScriptingEngine.VstaHelper.LoadNewProject(pScriptTask.ProjectTemplatePath, null, ScriptTaskProjectName);
//Initialize the designer project, add a new code file, and build
pScriptTask.ScriptingEngine.VstaHelper.Initalize("", true);
pScriptTask.ScriptingEngine.VstaHelper.AddFileToProject("ScriptMain.cs", "file contents");
pScriptTask.ScriptingEngine.VstaHelper.Build("");
// Persist the VSTA project + binary to the task
if (!pScriptTask.ScriptingEngine.SaveProjectToStorage())
{
throw new ArgumentNullException("Save failed");
}
// Replace ScriptMain contents
var contents = GetScriptMainContent();
pScriptTask.ScriptStorage.ScriptFiles["ScriptMain.cs"] = new VSTAScriptProjectStorage.VSTAScriptFile(VSTAScriptProjectStorage.Encoding.UTF8, contents);
// Reload the script project, build and save
pScriptTask.ScriptingEngine.LoadProjectFromStorage();
pScriptTask.ScriptingEngine.VstaHelper.Build("");
//Cleanup
pScriptTask.ScriptingEngine.DisposeVstaHelper();
}
private string GetScriptMainContent()
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "Va.Api.MyServiceSSIS.Infrastructure.Scripts.ScriptMain.txt";
Stream stream = assembly.GetManifestResourceStream(resourceName);
StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
The package and the Script Task in it are generated with no issues but when I try to run the package in Visual Studio that's when I get the issue:
for the Script Task it seems that it runs the code inside (giving execution finished with success) but actually it doesn't.
To solve this problem I have to open the script task editor, click on "Edit Script" that opens Visual Studio and the code to be run by the Script Task, then close VS and click OK in the Script Task editor.
If I do the above the Script Task runs the code correctly and I have no problems.
I'm using SQL Server 2014, VS 2013 (but when I open the script of the Script Task he opens the VS 2012)
Anyone had already a similar problem? Or can give me a tip?
I think it's maybe compilation problem, but theoretical in my code I'm already doing it by calling the Build method or not? (if I look at the xml code it seems like it has already hte binary code has already been built)
Thanks in advance.

Changing SSIS package in C# causing LoadFromXML fail

I am attempting to create a copy of an existing dtsx file so I can change a few variables based on input from the user. I am able to make a copy of the file, look at the variables, and set the variables to the correct input. However, when I go to look at the file in Visual Studio I get a few errors.
Microsoft Visual Studio is unable to load this document: The package failed to load to to error 0xC0010014 "One or more error occurred. There should be more specific errors preceding this one that explains the details of the errors. This message is used as a return value from functions that encounter errors". This occurs when CPackage::LoadFromXML fails.
The errors contained in the error list:
Error 3 Error loading test.dtsx: Error loading value "<DTS:Property xmlns:DTS="www.microsoft.com/SqlServer/Dts" DTS:Name="PackageFormatVersion">6</DTS:Property>" from node "DTS:Property". E:\test.dtsx 1 1
The version number in the package is not valid. The version number cannot be greater than current version number.
I looked into these errors and I saw potential issues with the server year and visual studio year. Both of these are the 2008 version.
My code:
string pkgPath = #"\\server\TestFolder\test.dtsx"
app = new Microsoft.SqlServer.Dts.Runtime.Application();
pkg = app.LoadPackage(pkgPath, null);
Console.WriteLine(pkg.Variables["filename"].Value.ToString());
pkg.Variables["filename"].Value = "testFile";
Console.WriteLine(pkg.Variables["filename"].Value.ToString());
app.SaveToXml(pkgPath, pkg, null);
If I open the file I am using to make a copy of in Visual Studio, it works no problem -- something strange is happening when I do app.SaveToXML();
Any ideas or suggestion would be wonderful.
To run this as a process from DTEXEC, it would look something like below. Please check out these two links for further details about ProcessStartInfo and how to use /SET so you can add that to your argument. Test this from the command line first because the syntax can be finicky.
https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo(v=vs.110).aspx
https://technet.microsoft.com/en-us/library/ms162810(v=sql.105).aspx
Using System.Diagnostics;
string args = #"/F'c:\MyPackage.dtsx' /SET'\package.variables[myvariable].Value;myvalue'";
ProcessStartInfo executePackage = new ProcessStartInfo("dtexec", args);
executePackage.UseShellExecute = false;
executePackage.RedirectStandardError = true;
executePackage.RedirectStandardOutput = true;
executePackage.CreateNoWindow = true;
StringBuilder output = new StringBuilder();
Process executing = Process.Start(executePackage);
while(!executing.StandardOutput.EndOfStream)
{
output.AppendLine(executing.StandardOutput.ReadLine();
}
executing.WaitForExit():

Visual Studio Installer > PostBuildEvent error code '1'

I'm trying to run a .js file with PostBuildEvent in Visual Studio 2010 and fail when i build the solution with the error code
Error 2 'PostBuildEvent' failed with error code '1' 'Error no especificado'
I already check the names of the files, the path, and the code in my project and js file, and everything seems right...
the js file contain this
// http://blogs.msdn.com/b/heaths/archive/2006/02/01/64-bit-managed-custom-actions-with-visual-studio.aspx
var msiOpenDatabaseModeTransact = 1;
var msiViewModifyUpdate = 2
var filespec = WScript.Arguments(0);
var projdir = WScript.Arguments(1);
var installer = WScript.CreateObject("WindowsInstaller.Installer");
var database = installer.OpenDatabase(filespec, msiOpenDatabaseModeTransact);
// Update the Binary table...
var sql = "SELECT `Name`,`Data` FROM `Binary` where `Binary`.`Name` = 'InstallUtil'";
var view = database.OpenView(sql);
view.Execute();
var record = view.Fetch();
record.SetStream(2, projdir + "InstallUtilLib.dll");
view.Modify(msiViewModifyUpdate, record);
view.Close();
database.Commit();
Anyone already solve a problem like this??
Any help, please...
Since you are using Visual Studio Installer, location of JS File is also important. Your js file should be in the same directory as the .vdproj file for your setup project.
This should be of some help to you
http://blogs.msdn.com/b/astebner/archive/2006/08/12/696833.aspx
In a desperate attempt to solve the problem, I found the solution.
After checking everything else, i move my project to another folder, and I discovered that the path was too long.
The path of my project, despite having less than 255 characters, as indicated by the Microsoft site, cause the Visual Studio 2010 give back this error.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
But attention, being a little explanatory error may result from other errors in other cases. In my case solved the problem.

Exception thrown in referenced project?

I have a Visual Studio 2010 solution consisting of 2 projects:
Core, a C# class library project which handles the functionality and data access
UI, an ASP.NET 4 website (.NET Framework 4) that references the Core, and calls functionality in the Core.
My exception handler is set in Global.asax (Application_Error.)
When an exception occurs in the UI, everything works perfectly, I get filename, line number, etc.
This is not the case for exceptions that occur in the Core.
For this, I get a stacktrace like:
{FillUserCount at offset 2376 in file:line:column <filename unknown>:0:0}
P.S. The Core.dll and Core.pdb are present in the UI Bin folder.
In Visual Studio -> Tools -> Options -> Debugging -> "Enable just my code" is unchecked and "Enable source server support" is checked.
Is there a way to get stackframe info (filename, class, method, line number) also for errors that occured in my referenced project ?
The solution to get this working was to create a new web site and re-referencing the Core project.
Still, the prerequisites that Jon Skeet mentioned remain the same:
the projects have to be built in Debug configuration, and not Release
while referencing a project, make sure PDB files are copied
on code side, when retrieving info about the exception that occured, and using StackTrace, make sure you create the instance with the second parameter set to true (true to capture the file name, line number, and column number; otherwise, false.)
This is my final working code. It may help others:
Exception ex = Server.GetLastError().GetBaseException();
StackTrace trace = new StackTrace(ex, true);
if (trace.FrameCount == 0)
return;
StackFrame stackFrame = trace.GetFrame(0);
string className, fileName, functionName, message;
int line = 0;
// if for some reason, filename is being retrieved as null
if (stackFrame.GetFileName() == null)
{
className = ex.TargetSite.ReflectedType.Name;
fileName = ex.TargetSite.ReflectedType.Name;
functionName = ex.TargetSite.Name;
message = ex.Message;
}
else
{
// Collect data where exception occured
string[] splitFile = stackFrame.GetFileName().Split('\\');
className = splitFile[splitFile.Length - 1];
fileName = stackFrame.GetFileName();
functionName = stackFrame.GetMethod().Name;
message = ex.Message;
line = stackFrame.GetFileLineNumber();
}
How are you referencing Core? If you've added a reference to the "Release" DLL, that would explain it... if you've just added a reference to the project and you're running a build with the "Debug" configuration then it should be okay.

Categories

Resources