I'm working on a C# project with WPF in Visual Studio. My application was building and running perfectly yesterday. As far as I know, I haven't made any changes to the build process.
Today, when I try to run a Debug build, it builds and deploys correctly, and a process starts, but the application startup window never displays (not even in the Windows Taskbar). I tried to attach the Visual Studio Debugger to the process as recommended in this (external) link, but the process is grayed out in the Visual Studio > Debug > Attach to Process... popup. It does not display even if I browse to the Debug folder and double-click the *.exe file.
The unusual thing about this is that if I run in Release rather than Debug, everything works fine. I've checked the Project > Properties > Debug configurations; Debug and Release are identical (I just used the defaults when I created the project). Other projects also work fine in both Debug and Release build. I tried comparing the *.csproj and *.sln files, but I couldn't find any significant differences.
I've tried searching for this, but it's really difficult to find anything useful. This question is unrelated, since the window does not even appear in the taskbar in my case. If I try to include the word "debug," I get a flood of questions about redirecting output to the console, which is not my problem.
I'm not sure what code/configurations are relevant to this question, so please let me know if you need more info about the setup.
Edit 1:
I tried putting a break in the InitializeComponent() method in the auto-generated part of my App class:
public partial class App : System.Windows.Application {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
#line 5 "..\..\App.xaml"
this.StartupUri = new System.Uri("Views\\MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
System.Uri resourceLocater = new System.Uri("/MyProject;component/app.xaml", System.UriKind.Relative);
#line 1 "..\..\App.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main() {
MyProject.App app = new MyProject.App();
app.InitializeComponent();
app.Run();
}
}
This will break for either Debug or Release if the code is between if(_contentLoaded) { and _contentLoaded = true; but everywhere else in the method, I get "The breakpoint will not currently be hit. No executable code of the debugger's target code type is associated with this line." I get the same message if I try to put a breakpoint anywhere in the Main() method.
Even though Debug breaks at the certain interval mentioned above, it still does not display if I continue.
Edit 2:
Things are starting to get weird. Since the project is backed up in Git, I rolled all the way back to the first commit and to several others along the way. I still couldn't get anything to display for Debug, but Release still worked fine. I even tried deleting the local repo and recloning it, but no success. The stranger part about this is that everything runs fine from the backup folder. Why does the folder name make a difference?
I never found out what caused the issue to occur in the first place, but I was eventually able to come up with two workable solutions.
As described in the edit: Copying the solution directory to another directory and running it from there works for some reason.
For some reason, running Debug|Any CPU didn't work, but running either Debug|x86 or Debug|x64 did.
It's unlikely that someone else will run into my exact situation, but I'm leaving my solutions here for posterity. Maybe someone else can benefit from this.
Related
I get this strange error from Visual Studio 2019 in the XAML editor, but the project compiles, runs and the assignment is actually working:
I get this error in all UserControls containing this expression. In my MainWindow the same logic causes no Problems. root is just the root namespace which is identical to local on the MainWindow. The settings object in App.xaml.cs looks like this:
public static readonly ISettings Settings;
ISettings is a simple interface for the ConfigurationBuilder of Config.Net.
using Config.Net;
using System;
namespace MyApp.Properties
{
public interface ISettings
{
[Option(Alias = "skin")]
string Skin { get; }
[Option(Alias = "cryptoID")]
string CryptoID { get; }
// ...
}
}
Cleaning, rebuilding, restarting, nothing helps to get rid of the message. I keep ignoring it, but I wish to get rid of it, please.
If your program runs correctly and Visual Studio displays the wavy line warning by mistake, you could try do the following settings to not display the warning wavy line.
Uncheck Display Error Curve :
Tools> Options> Text Editor> General >Display Error Curve
You can also reset the settings.
Tools→Import and Export Settings...→Reset all settings.
Well, the message basically explains what's wrong, so I went ahead and created the folder C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Logs and gave everyone full permission in the ACL security settings in the property window of the folder. Now Visual Studio stops complaining, although no files are created in the folder anyways.
I don't know why this has to be, but the message is gone eventually.
There's no error message and no indication why it is not displaying the window. The app initialises App.xaml.cs: App() {} and I can step through the App.xaml file. It gets the startup uri and then... silence. No output in the Output window and no unhandled exception and no window, I can't find where to put a breakpoint to debug as it isn't hitting the start of MainWindow.xaml.cs.
Really confused.
This was working 20m ago.
In that time all I did was add Windows.Office.Interop.Outlook reference. I removed the reference and rebuilt but still the same. Would that cause this problem? Has anyone seen this before? Google isn't helping!
EDIT :
App.xaml.cs:
public App()
{
using (var dbContext = new DBEntities())
{
if (!db.Exists())
{
try
{
db.Database.Create();
MessageBox.Show("Database created"); // this is the problem!!
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
I've added App.xaml.cs, I found that the problem was using a MessageBox to give info (this is still in development!). I'd been meaning to get rid of it and eventually did and my problem went away. This meant I could find relevent Goolge results:
MSDN query and answer for exactly my problem
I will be adding an 'loading window' in between app load and main window load eventually in which I will be able to feedback information using Bindings etc.
Fixed error by removing the MessageBox.Show(..) call. The selected answer from the MSDN URL given in the question states:
"I performed a test based on your description, the applicationi stop at the method : USER32!GetMessageW+0x33, calling USER32!NtUserGetMessage"
I assume this is what was occurring in my case, although I didn't test it.
What happens if you create a new window and set that as the StartupUri?
You also might want to create a new project and make sure that the namespaces referenced in the App.xaml in your existing app haven't somehow been inadvertently edited.
I'm working with a Silverlight 4 application and we use Prism/MEF to build modules.
Each module is created as a Silverlight application. We then use a ModulesCatalog.xaml file to control how the modules are loaded.
We had 6 modules and everything was working perfect.
This week we're adding a 7th module and we just have the new Silverlight application created. We setup the module class as follows.
[ModuleExport(typeof(InsightModule))]
public class InsightModule : IModule
{
}
Then we added an entry to our ModulesCatalog file.
Now when we run the application we start getting all types of recomposition errors. The stack shows this.
at System.ComponentModel.Composition.CompositionResult.ThrowOnErrors(AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ExportProvider.OnExportsChanging(ExportsChangeEventArgs e)
at System.ComponentModel.Composition.Hosting.CatalogExportProvider.OnCatalogChanging(Object sender, ComposablePartCatalogChangeEventArgs e)
at System.ComponentModel.Composition.Hosting.ComposablePartCatalogCollection.OnChanging(Object sender, ComposablePartCatalogChangeEventArgs e)
at System.ComponentModel.Composition.Hosting.AggregateCatalog.OnChanging(ComposablePartCatalogChangeEventArgs e)
at System.ComponentModel.Composition.Hosting.ComposablePartCatalogCollection.RaiseChangingEvent(Lazy`1 addedDefinitions, Lazy`1 removedDefinitions, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ComposablePartCatalogCollection.Add(ComposablePartCatalog item)
at Microsoft.Practices.Prism.MefExtensions.Modularity.MefModuleInitializer.CreateModule(ModuleInfo moduleInfo)
at Microsoft.Practices.Prism.Modularity.ModuleInitializer.Initialize(ModuleInfo moduleInfo)
Then you get the standard output.
The exception message was: The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced multiple composition errors, with 57 root causes. The root causes are provided below. Review the CompositionException.Errors property for more detailed information.
1) Change in exports prevented by non-recomposable import 'EyeCue.Common.AboutEyeCueView.ViewModel (ContractName="EyeCue.Common.AboutEyeCueVM")' on part 'EyeCue.Common.AboutEyeCueView'.
WHat's puzzling is why none of the other 6 modules caused this problem but now all of a sudden, this new module without anything going on in it is causing a recomposition of the catalogue. It makes no sense.
Plus I have ctor's that import in some cases and that's they what I had to do to get things to work, so this is not as simple as going to setting the Allow Recomposition attribut.
I've downloaded the VisualMFX but this line of code throws an Object Not initialized exception.
this.compositionInfo = new CompositionInfo(_aggregateCatalog, _container);
Both _aggregateCatalog & _container are not null when this happens.
In summary, why would a 7th module all of a sudden start causing recomposition? Especially when the module isn't even defining any exports or imports at this time? That leads to how do we stop it to address this problem?
The issue turned out to be a reference to an assembly which had Copy Local set to true.
Making sure all references which are also set in the main application assembly were set to Copy Local = false seems to resolved the problem.
I have a Windows Service that monitors a COM port connected to a vendors hardware. This is a very busy piece of hardware that is constantly polling other devices on the wire (this is a twisted-pair RS485 "network"). My software needs to emulate X number of hardware devices on this wire, so I've got a multi-threaded thing going on with a multi-tiered state machine to keep track of where the communications protocol is at any moment.
Problem is with a Windows Service (this is my first one, BTW) is that you need some debugging to let you know if stuff is working properly. When I was first developing this state machine/multi-thread code I had a windows form with a RichTextBox that displayed the ASCII chars going back-n-forth on the line. Seems like I can't really have that GUI niceness with a service. I tried opening a form in the service via another program that sent the service messages that are received via the OnCustomCommand() handler but it didn't seem to work. I had "Allow service to interact with desktop" checked and everything. I was using the Show() and Hide() methods of my debug form.
I guess I don't need to see all of the individual characters going on the line but man that sure would be nice (I think I really need to see them :-) ). So does anyone have any crazy ideas that could help me out? I don't want to bog down the system with some IPC that isn't meant for the voluminous amount of data that is sure to come through. It will only be very short-term debugging though, just confirmation that the program, the RS485-to-USB dongle, and hardware is all working.
Use OutputDebugString to write to the debugging buffer and then use DebugView to watch it. If you're running on Windows XP or earlier, then you can use PortMon to see the raw bytes going through the serial port. The advantage over a log file is that there's very little overhead, particularly when you're not watching it. You can even run DebugView from another machine and monitor your service remotely.
I dunno if it will work for you, but I always build my services with a extra Main that build them as console app to get debug output.
Edit:
Some example:
class Worker : ServiceBase
{
#if(RELEASE)
/// <summary>
/// The Main Thread where the Service is Run.
/// </summary>
static void Main()
{
ServiceBase.Run(new Worker());
}
#endif
#if(DEBUG)
public static void Main(String[] args)
{
Worker worker = new Worker();
worker.OnStart(null);
Console.ReadLine();
worker.OnStop();
}
#endif
// Other Service code
}
You could write the output to a log file and then use another application to watch that file. This question about "tail" outlines several options for watching log files with windows.
What I usually do when working on a Windows Service is to create it so that it can be run either as a service, or as a plain old command-line application. You can easily check whether you are running as a service by checking Environment.UserInteractive. If this property is true, then you are running from the command line. If the property is false, then you are running as a service. Add this code to Program.cs, and use it where you would normally call ServiceBase.Run(servicesToRun)
/// <summary>Runs the provided service classes.</summary>
/// <param name="servicesToRun">The service classes to run.</param>
/// <param name="args">The command-line arguments to pass to the service classes.</param>
private static void RunServices(IEnumerable<ServiceBase> servicesToRun, IEnumerable args)
{
var serviceBaseType = typeof(ServiceBase);
var onStartMethod = serviceBaseType.GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var service in servicesToRun)
{
onStartMethod.Invoke(service, new object[] { args });
Console.WriteLine(service.ServiceName + " started.");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
var onStopMethod = serviceBaseType.GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var service in servicesToRun)
{
onStopMethod.Invoke(service, null);
Console.WriteLine(service.ServiceName + " stopped.");
}
}
Now you can debug your service, set breakpoints, anything you want. When you run your application, you'll get a console window, appropriate for displaying console messages, and it will stay open until you hit a key.
I'm answering my own question here. I tried a couple of suggestions here but here's what I ended up doing...
I created a Windows Form application with a single Button and RichTextBox. This application constructed a NamedPipeServerStream on it's end. The Button's job was to send either "debug on" (command 128) or "debug off" (129) to the Windows Service. The initial value was "debug off". When the button was clicked, a command of 128 was sent to the Windows Service to turn debugging on. In the Windows Service this triggered an internal variable to be true, plus it connected to the Form application with a NamedPipeClientStream and started sending characters with a BinaryWriter as they were received or sent on the COM port. On the Form side, a BackgroundWorker was created to WaitForConnection() on the pipe. When it got a connection, a BinaryReader.ReadString() was used to read the data off of the pipe and shoot it to the RichTextBox.
I'm almost there. I'm breaking my pipe when I click the debug button again and a subsequent click doesn't correctly redo the pipe. All in all I'm happy with it. I can post any code if anyone is interested. Thanks for the responses!
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/