Start process with Debugger - visual-studio-debugging

I am developing an extension for Visual Studio.
I would like a feature of this extension to be the ability to start a process with a debugger attached.
So far I can get the debugger to attach using code:
System.Diagnostics.Debugger.Launch();
DTE dte = ServiceProvider.GetServiceAsync(typeof(DTE)).Result as DTE;
var startInfo = new ProcessStartInfo()
{
FileName = "PATH_TO_DOT_NET_EXECUTABLE"
};
var process = System.Diagnostics.Process.Start(startInfo);
foreach (EnvDTE.Process proc in dte.Debugger.LocalProcesses)
{
if (proc.ProcessID == process.Id)
{
proc.Attach();
return;
}
}
Sometimes however, the process finishes before the debugger can attach.
Is there a way to create the process from within the Visual Studio Extension in such a way that the debugger is attached upon creation?

Related

How to execute a package task in a script task in debug mode in VS

I have an SSIS project containing two packages. Package1.dtsx should be called by Package2.dtsx. When doing so with an ExecutePackageTask, the debugger opens the second package once it gets called.
Now I need to adapt the code so that I'm not using the ExecutePackageTask but rather a ScriptTask. But then, the debugger won't open the second package.
Package2.dtsx now looks like this:
Here are the different things I tried within the ScriptTask:
public void Main()
{
var parentPackage = (Package)Dts.Variables["System::StartTime"].Parent;
var proj100 = (IDTSProject100)parentPackage.Project;
string packageStreamName = "Package1.dtsx";
// test 1 - using IDTSProject100.GetConfiguredPackageByName
var pkgTest1 = proj100.GetConfiguredPackageByName(packageStreamName);
pkgTest1.InteractiveMode = true;
var res1 = pkgTest1.Execute();
// test 2 - using IDTSProject100.GetPackageByName
var pkgTest2 = proj100.GetPackageByName(packageStreamName);
pkgTest2.InteractiveMode = true;
var res2 = pkgTest2.Execute(pConnections: proj100.GetConnections(), pVariables: proj100.GetVariables(), pEvents: null, pLog: null, pTransaction: Dts.Transaction);
// test 3 - using reflection to get the Project object and then load the package from the PackageItems
System.Reflection.PropertyInfo pInfo = proj100.GetType().GetProperty(
"Project",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
Project proj = (Project)pInfo.GetValue(proj100, null);
PackageItems pis = proj.PackageItems;
PackageItem childPackageItem = pis[packageStreamName];
Package pkgTest3 = childPackageItem.LoadPackage(null);
pkgTest3.InteractiveMode = true;
var res3 = pkgTest3.Execute();
// test 4 - using a new package added to the current project. This package contains an ExecutePackageTask that calls the child
Package pkgTest4 = new Package();
Executable execPackageTask = pkgTest4.Executables.Add("STOCK:ExecutePackageTask");
var taskHost = (TaskHost)execPackageTask;
var execPkgTask = taskHost.InnerObject as ExecutePackageTask;
execPkgTask.UseProjectReference = true;
execPkgTask.PackageName = packageStreamName;
//var execRes = taskHost.Execute(connections: Dts.Connections, variables: Dts.Variables, events: null, log: null, transaction: Dts.Transaction);
pkgTest4.InteractiveMode = true;
proj.PackageItems.Add(pkgTest4, "test.dtsx");
var res4 = pkgTest4.Execute();
}
Any ideas what I could be missing? Is it even possible?
I do not think it is possible to invoke a Visual Studio SSIS debugger from C# code.
Preface to this statement. SSIS Script task is a .NET independent language executable placed in a special placeholder. You can run VS debugger on the .NET code itself. From the structure point of view, when VS runs or debugs the SSIS package, it runs it in DtsDebugHost.exe process. VS executes SSIS package task by task knowing its structure, capturing events and progress and displaying it in its window.
The Script Task executes its code, your code samples are fine examples on how to get running Project and execute a Package from it. But - from VS point of view - it is an invocation of some class methods. You can proceed with Package output, capturing all task and component messages and then - store it in file or DB text field.

Visual Studio 2017 Enterprise : No tasks to display. (windows 7)

C#, .net 4.7
Debug => tasks shows : "No tasks to display."
Can anyone confirm it is supposed to work on windows 7 ?
Thx
First, the Task Window in Debug mode can work on window7.
I spend some time configuring the environment.(windows7 and .net4.7) to confirm it.
Steps: Create a new C# console app(.net framework). And add the code below:
static void Main(string[] args) **//line11**
{ **//line12**
Task t = Task.Factory.StartNew(() =>
{
// Just loop.
int ctr = 0;
for (ctr = 0; ctr <= 1000000; ctr++)
{ }
Console.WriteLine("Finished {0} loop iterations",ctr);
});
t.Wait();
}
1.Add the break point to line12 and start Debugging,nothing in Task window
2.Step into(F11), still nothing
3.Step into(F11), main task with ID 1 will display
In addition,I think you can get some help from this
document.
It introduces the usage of Task window in debug and for managed code like C#, Task window only works with System.Threading.Tasks.Task objects or with the await and async keywords (Await and Async in VisualBasic)
In C#,the task window is designed to work with task object. For those program without using the task object, this option won't work. And i think it may be the cause of your issue.

How to use WPF UserControls or Windows from inside Visual FoxPro 9

I have a very, very large and complex Visual FoxPro 9 application. I'd like to rewrite portions of this application in WPF with the ultimate goal of completing cutting over a couple of years from now. I've spent a considerable amount of time searching google and stackoverflow for an end to end "hello world" type sample of how to implement this with COM interop. Found bits and pieces but nothing complete that shows both the FoxPro side and the WPF side.
My gut tells me I'm likely to run into issues with XAML resources, third party controls, or other normal functionalities of a WPF app if I try to run it via COM Interop.
So, two questions. Can anyone point me to an small end to end sample that either launches WPF windows from FoxPro or lets me drop WPF user controls on a FoxPro form? Or am I right with my concerns of potential interop issues and should avoid this altogether? If so, is there a recommended way for these two executables to communicate with each other?
I have absolutely no idea whether you can run wpf inside visual FoxPro. I would guess you'd have to write it as an activex.
I recently did some work extending a MS Access app.
My wpf app is completely separate and runs alongside the ms access app.
I communicated between the two using MS Message Queue - which is a com component.
Maybe this sort of approach could work for you.
When I wanted to show a screen in wpf from access I added a piece of xml to the local message queue.
The wpf app listens for these messages, casts them to objects which tells it which screen to show and gives it any parameters.
MS Access subscribes to the received message event on the message queue and that way it can tell when the wpf window closes and the user is done.
This was intended to use the strangler pattern to gradually replace functionality in the old access app.
Here's some code for the queuelistener that drives everything. The various pop classes are deserialised from the message and I build that as a string in access.
internal class QueueListener
{
public const string qFromMadge = #".\private$\XXXXQ";
public static string qToMadge = #".\private$\XXXXReturnQ";
private MessageQueue mq;
internal QueueListener()
{
try
{
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
SubscribeHandler();
var mqSend = setUpQueue(qToMadge);
mqSend.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException.Message);
}
}
private MessageQueue setUpQueue(string qName)
{
MessageQueue q;
if (MessageQueue.Exists(qName))
{
q = new MessageQueue(qName);
}
else
{
q = MessageQueue.Create(qName);
}
q.ResetPermissions();
q.SetPermissions("Everyone", MessageQueueAccessRights.FullControl, AccessControlEntryType.Set);
q.Purge();
return q;
}
private void ReceiveMsgCompleted(Object source, ReceiveCompletedEventArgs asyncResult)
{
MessageQueue mq = (MessageQueue)source;
Message m = mq.EndReceive(asyncResult.AsyncResult);
m.Formatter = new XmlMessageFormatter(new[] { "XXXX.Popaaaa, XXXX"
, "XXXX.Popbbbb, XXXXX"
, "XXXX.Popcccc, XXXX"
, "XXXX.Popdddd, XXXX"
});
((BasePopView) m.Body).Pop();
mq.BeginReceive();
}
public void UnsubscribeHandler()
{
if (mq == null)
{
return;
}
mq.Close();
mq.ReceiveCompleted -= new ReceiveCompletedEventHandler(ReceiveMsgCompleted);
mq = null;
}
public void SubscribeHandler()
{
if(mq != null)
{
return;
}
mq = setUpQueue(qFromMadge);
mq.ReceiveCompleted += ReceiveMsgCompleted;
mq.BeginReceive();
}

Setup Database before run ui coded tests on Visual Studio 2010

I'm automating UI tests to my Silverlight App and I'm using Visual Studio 2010 for it. Some tests required a setup to my Oracle Database.
Things i've done:
1 - A setup.sql file where I connect to my Database and perform actions on it. I had this file as an existing item to my project and I add as a Deployment on TestSettings.
Code:
CONNECT USERNAME#DATABASE,
CREATE TABLE TABLE_NAME,
EXIT
2 - A set.bat file where I call the setup.sql file. I had the path of this file on Setup and Cleanup tab on TestSetings.
Code:
sqlcmd -S MARIALISBOA -i setup.sql
3 - I wrote a TestInitilize method on my TestClass.
Code:
[TestInitialize()]
public void Initialize()
{
System.Diagnostics.Process.Start("setup.bat");
}
4 - I connected do my Database throw Visual Studio (Data -> Add New Data Source).
I run a test on Visual Studio but the class isn't created on my database.
Could anyone help me? I'm trying to solve this problem since Monday and I starting to lose my mind
While it does not solve your initial problem, a solution would be to use something similiar to this;
Do not create the table within your tests. this should be created on install of the Test Environment
Clear down the table for each test you want to do using a Helper Method within the test.
For example (Please note that this is SQL Server, use OLE DB connection or similiar);
internal static object FireSqlStatement(string sqlStatement)
{
object result = null;
using (var cn = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionString].ConnectionString))
{
cn.Open();
var cmd = new SqlCommand
{
CommandText = sqlStatement,
CommandType = CommandType.Text,
Connection = cn
};
result = cmd.ExecuteScalar();
cmd.Dispose();
cn.Close();
}
return result;
}
An example of how I use this within my test;
[Test]
public void GetUserTriggers()
{
//Insert Test Record
Helper.FireSqlStatement("INSERT INTO [Users].[Triggers] (Id) VALUES (1)");
var request = new GetTriggersRequest()
{
TriggerType = TriggerType.UserTrigger
};
var response = ServiceInvoker.Invoke<IReports,
GetTriggersRequest, GetTriggersResponse>(
"Reports",
request,
(proxy, req) => proxy.GetTriggers(req));
foreach (var t in response.Triggers)
{
Console.WriteLine(t.Id.ToString());
}
Assert.NotNull(response);
Assert.NotNull(response.Triggers);
Assert.Greater(response.Triggers.Count, 0);
}
In your case, you could call;
Helper.FireSqlStatement("TRUNCATE TABLE tableName");
Any good?

Debugging silverlight in a WPF app

I am developing a WPF app that contains a webbrowser control that loads a silverlight application. I would like to be able to launch the app from visual studio (F5) and have the debugger attach to the silverlight code. However, I've not had any luck with this.
The best I can currently do is to launch the app without attaching, then once it is up and running, attach to the process manually with silverlight as the specified type of code to debug, and this works. (When I cause the web browser control to load the silverlight app, it will hit breakpoints in my silverlight code). I've written some macros to automate this launching/attaching somewhat, but it still isn't the best.
I've tried specifying the WPF app as the external program to run when launching/debugging the silverlight app, but Visual Studio attaches to the process wanting to debug the managed .NET code.
Any ideas? Ideally, I would really like to attach to the process and debug both the managed .NET and the silverlight code, but I don't think this is possible. I'd really like to automatically be attached to the silverlight code at launch so that I can easily debug all issues with the silverlight app, including those that occur on load.
Thanks for your ideas Brandorf and fatty. Brandorf's almost gets me to where I wanted to go, but does require that my SL app be capable of running on its own. I really want to have only the one app, which is both wpf and silverlight, with the SL side being debugged.
A long time after I asked this question (I forgot I had asked it here), I actually pieced together a solution that I'm really happy with. I use visual studio automation within the WPF/.NET side of my app, to find all running instances of visual studio, figure out which one produced my exe (since it typically sits in a folder below the vcproj/sln folder), and then use visual studio automation to have that VS attach to the app, debugging silverlight code. After this is done, I then load my silverlight content.
It works really well. You end up with an app that goes and finds a debugger to attach to itself every time it runs (so you probably want this code only in a debug build, or somehow able to be turned off). So you just launch the app with ctrl-F5 (launch without debugging) from visual studio whenever you want to debug the silverlight side.
Here's my code:
#if DEBUG
using System;
using System.Collections.Generic;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
namespace Launcher
{
//The core methods in this class to find all running instances of VS are
//taken/inspired from
//http://www.codeproject.com/KB/cs/automatingvisualstudio.aspx
class DebuggingAutomation
{
[DllImport("ole32.dll")]
private static extern int GetRunningObjectTable(int reserved,
out UCOMIRunningObjectTable prot);
[DllImport("ole32.dll")]
private static extern int CreateBindCtx(int reserved,
out UCOMIBindCtx ppbc);
///<summary>
///Get a snapshot of the running object table (ROT).
///</summary>
///<returns>
///A hashtable mapping the name of the object
///in the ROT to the corresponding object
///</returns>
private static Hashtable GetRunningObjectTable()
{
Hashtable result = new Hashtable();
int numFetched;
UCOMIRunningObjectTable runningObjectTable;
UCOMIEnumMoniker monikerEnumerator;
UCOMIMoniker[] monikers = new UCOMIMoniker[1];
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
while (monikerEnumerator.Next(1, monikers, out numFetched) == 0)
{
UCOMIBindCtx ctx;
CreateBindCtx(0, out ctx);
string runningObjectName;
monikers[0].GetDisplayName(ctx, null, out runningObjectName);
object runningObjectVal;
runningObjectTable.GetObject(monikers[0], out runningObjectVal);
result[runningObjectName] = runningObjectVal;
}
return result;
}
/// <summary>
/// Get a table of the currently running instances of the Visual Studio .NET IDE.
/// </summary>
/// <param name="openSolutionsOnly">
/// Only return instances that have opened a solution
/// </param>
/// <returns>
/// A list of the ides (as DTE objects) present in
/// in the running object table to the corresponding DTE object
/// </returns>
private static List<EnvDTE.DTE> GetIDEInstances(bool openSolutionsOnly)
{
var runningIDEInstances = new List<EnvDTE.DTE>();
Hashtable runningObjects = GetRunningObjectTable();
IDictionaryEnumerator rotEnumerator = runningObjects.GetEnumerator();
while (rotEnumerator.MoveNext())
{
string candidateName = (string)rotEnumerator.Key;
if (!candidateName.StartsWith("!VisualStudio.DTE"))
continue;
EnvDTE.DTE ide = rotEnumerator.Value as EnvDTE.DTE;
if (ide == null)
continue;
if (openSolutionsOnly)
{
try
{
string solutionFile = ide.Solution.FullName;
if (!String.IsNullOrEmpty(solutionFile))
{
runningIDEInstances.Add(ide);
}
}
catch { }
}
else
{
runningIDEInstances.Add(ide);
}
}
return runningIDEInstances;
}
internal static void AttachDebuggerIfPossible()
{
if (System.Diagnostics.Debugger.IsAttached)
{
//Probably debugging host (Desktop .NET side), so don't try to attach to silverlight side
return;
}
var ides = GetIDEInstances(true);
var fullPathToAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
var potentials = new List<EnvDTE.DTE>();
foreach (var ide in ides)
{
var solutionPath = ide.Solution.FullName;
var topLevelSolutionDir = Path.GetDirectoryName(solutionPath);
var assemblyName = fullPathToAssembly;
if (assemblyName.StartsWith(topLevelSolutionDir, StringComparison.OrdinalIgnoreCase))
{
potentials.Add(ide);
}
}
EnvDTE.DTE chosenIde = null;
//If you have multiple ides open that can match your exe, you can come up with a scheme to pick a particular one
//(eg, put a file like solution.sln.pickme next to the solution whose ide you want to debug). If this is not a
//concern, just pick the first match.
if (potentials.Count > 0)
{
chosenIde = potentials[0];
}
var dbg = chosenIde != null ? (EnvDTE80.Debugger2)chosenIde.Debugger : null;
if (dbg != null)
{
var trans = dbg.Transports.Item("Default");
var proc = (EnvDTE80.Process2)dbg.GetProcesses(trans, System.Environment.MachineName).Item(Path.GetFileName(fullPathToAssembly));
var engines = new EnvDTE80.Engine[1];
engines[0] = trans.Engines.Item("Silverlight");
proc.Attach2(engines);
}
}
}
}
#endif
It's a bit of a shot in the dark, but assuming your silverlight app is capable of running on its own, you can, under your solution settings, set visual studio to start both apps together, and you should be attached to both of them.
If you can't add the Silverlight project to your solution (which will start debugging automatically), you might be able to make use of this tip. It will load both projects at the same time
http://saraford.net/2008/07/28/did-you-know-you-can-start-debugging-multiple-projects-268/

Resources