I have a project in Visual Studio 2010 (converted from 2008), and I have created a User control, like this:
namespace Common.Controls
{
public partial class Panel_BaseMap : UserControl
{
public Panel_BaseMap()
{
//Some properties initialization here, just like = new X();
InitializeComponent();
}
private void BaseMapPanel_Load(object sender, EventArgs e) {
//Here, a new Thread is initialized and started.
}
}
}
I don't have any problem with this, it is opened in Design Mode without any problem. But I have created a new UserControl that extends to the first one, like this:
using Common.Controls;
namespace BC.controls
{
public partial class MapPanel : Panel_BaseMap
{
public MapPanel()
{
InitializeComponent();
}
}
}
Well, in the very moment I try to open this new control on design mode, Visual Studio gets totally blocked, and I have to force it to close because it doesn't respond. I have tried many things, like for example:
public MapPanel()
{
if (!this.DesignMode)
InitializeComponent();
}
Still blocked. I have opened a second instance of Visual Studio, then on the first one "Debug --> Attach to process --> devenv" and I have put a breakpoint on the Load method and on both constructors on the second instance. The result: both instances totally blocked.
Can anyone help me, please?
Thank you very much in advance!
Ok I've found the problem.
Some code was executed by the designer, and that code crashed the application. It was inside a try-catch, and inside the catch I logged the error with a method that tried to load an encripted file with this: Directory.GetFiles(Application.StartupPath, "*.xml"). The problem is that Application.StartupPath is not my application path, but "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\Microsoft.Data.ConnectionUI.xml". So, when I tried to decrypt it, it throwed another exception, that was logged with the same method... so infinite loop!
Related
I am about to learn CommandBindings in WPF, but somehow I cannot create custom commands.
Following error is shown: (XDG0008) The name "CustomCommands" does not exist in the namespace "clr-namespace:CommandBindingWPF"
<Window.CommandBindings>
<CommandBinding Command="local:CustomCommands.Exit" CanExecute="ExitCommand_CanExecute" Executed="ExitCommand_Executed" />
</Window.CommandBindings>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = viewmodel;
}
//more code but not relevant for question
private void ExitCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
Application.Current.Shutdown();
}
}
public static class CustomCommands
{
public static readonly RoutedUICommand Exit = new RoutedUICommand
(
"Exit",
"Exit",
typeof(CustomCommands)
);
//Define more commands here, just like the one above
}
I even tried to copy-paste it from https://wpf-tutorial.com/commands/implementing-custom-commands/ and paste the CanExecute and Executed just for testing in MainWindow-class (and of course i changed the xmlns:self), but it still does not work. Can someone help me out? It is making me crazy.
The XAML designer in Studio takes information about types not from projects, but from their assemblies.
Therefore, if you made a change to the project, then the Designer will not see them until you make a new assembly of the project.
You do not need to close / open the Studio for this.
Go to the "Project" menu, select "Build" there.
Or the same can be done in the "Solution Explorer" in the context menu of the Project.
Also, if you made changes to the project, a new build will be performed automatically when the Solution is launched for execution.
In very rare cases (usually after some bugs, incorrect closing of the Studio), before building, you still need to perform a "Cleanup" of the Project or Solution.
P.S. Due to this peculiarity of the XAML Designer, in order not to constantly stumble upon such errors (and in some cases they can be very confusing and even lead to compilation errors), it is recommended to create all types used in XAML in other projects.
This makes it much easier to understand the source of the XAML Designer and Compiler errors and warnings.
I fixed it by myself!
I closed VS, rebuilt the project and the error did not pop up again (WPF designer issues : XDG0008 The name "NumericTextBoxConvertor" does not exist in the namespace "clr-namespace:PulserTester.Convertors").
I hate VS.
I have an application that I am deploying using ClickOnce. I am using the default InstallUpdateUpdateSyncWithInfo() method provided here. I made two changes though; I made the method public and static as I am calling it from a static class. I know bad practices. This is some lazy code just to try out ClickOnce.
Everytime the application updates it loads two instances, the old one and the new one.
Other than that though I am calling the method in my app.xaml.cs like this:
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
MainWindow window = new MainWindow();
CheckForUpdates.InstallUpdateSyncWithInfo();
window.Show();
}
}
I thought if I call Window.Show() after checking for an Update it would call the Application.Restart() method in InstallUpdateUpdateSyncWithInfo() before the old version could load, but this is not the case.
Does anyone know how I can prevent two instances of my application from loading after the application is updated?
There was another post on Stack Overflow which from the title, I thought would directly address this question, but I did not see how the poster modified his code to prevent two instances from loading.
There's no need to write the auto-update code yourself. First, I would remove your update code.
Next right-click on your C# project and select Properties. Then go to Publish and click Updates.... Tick the checkbox so your application checks for updates and ClickOnce will handle the rest.
I have created an Excel Addin project in C#. Now the solution contains a file ThisAddin.cs, which has a class ThisAddin. Later I have added an item called Form to the same solution. In Form, when I click on a button, for that button click event i want to call a method inside ThisAddin.cs file.
namespace ExcelAddIn
{
public partial class ThisAddIn
{
public void RefreshExcelData()
{
}
}
}
Now in MyForm.cs, while trying to create an object for ThisAddin class there is a compilation error that Thisaddin class doesn't have a constructor that takes 0 arguments.
private void btnUploadTestCases_Click(object sender, EventArgs e)
{
ThisAddIn objrefresh = new ThisAddin();
}
What am I missing here?
You are approaching the problem from the wrong direction. When you click the button, you don't want to create a new add-in, what you really want is to access the add-in instance which is created for you by VSTO when Excel starts up, which is accessible via Globals.ThisAddIn.
Change your code in the Form to the following:
private void btnUploadTestCases_Click(object sender, EventArgs e)
{
var addIn = Globals.ThisAddIn;
addIn.RefreshExcelData();
}
... and it should work a charm.
That being said, is there a good reason for this a method to be on ThisAddIn? In general, ThisAddIn should be used to wire up and tear down the add-in when Excel starts up / shuts down, and I would recommend to put as little logic in there as possible.
Use this code:
Globals.ThisAddIn.Application.StatusBar = "Referesh clicked!!!."; Globals.ThisAddIn.RefreshExcelData();
Just make sure your function remains public.
my project a three tier architecture project talking to a WCF service in the backend. When the backend is able to fetch data from the service, it notifies the business layer using publish-subscribe, which in return notifies the GUI layer.
I have added an OpenFileDialog to my UI design using Visual Studios designer. A button event handler calls the ShowDialog message. However, once I click the button, the whole UI hangs.
Having googled around a bit, I found out that using delegates is the preferred way to handle tasks like this. However, with nor without delegate the problem persists.
Currently my code looks like this:
private void bOpen_Click(object sender, EventArgs e)
{
Func<Image> del = delegate
{
OpenFileDialog d = new OpenFileDialog();
if (d.ShowDialog() == DialogResult.OK)
{
return Image.FromFile(d.FileName);
}
return null;
};
Invoke(del);
}
I'm coming from the Java world, so I'm not really familiar with the intricacies of C# UI programming.
Anything I'm missing here?
openFileDialog1->ShowHelp = true;
I put this line in my code then the problem was solved.
I seem to have solved the problem adding the [STAThread] Attribute to the main method. I was told to do so once I ran the program in a debugger - which I hadn't done before because I ran the service from Visual Studio and the client regularly from Windows.
[STAThread]
public static void Main(string[] args)
{
GUI gui = new GUI();
gui.ShowDialog();
}
Can anybody explain what exactly is going on though
This tends to be an environmental problem, when you use OpenFileDialog a lot of shell extensions get loaded into your process. A misbehaving one can easily screw up your program. There are a lot of bad ones out there.
Debugging this is difficult, you need an unmanaged debugger since these shell extensions are unmanaged code. You might be able to tell something from the call stack when you break in after the deadlock. Windows debugging symbols required, enable the Microsoft symbol server. But the most effective approach is to use SysInternals' AutoRuns utility. Start by disabling all of the shell extensions that were not produced by Microsoft. Then start re-enabling the ones you cannot live without one by one.
And, as you found out, these shell extension expect to run on an STA thread and fail miserably when they don't get it. The UI thread of a program must always be STA, also to support the clipboard and drag-and-drop and various kinds of controls like WebBrowser. Normally always taken care of automatically by the [STAThread] attribute on the Main() method, put there by the project template. And the Application.Run() call, required to implement the STA contract. Deadlock when you don't.
I believe the "delegate" prefered way actually refers to using a separate thread.
I'm gonna give you an example using BackgroundWorker.
It would look like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
m_Worker.DoWork += new DoWorkEventHandler(m_Worker_DoWork);
m_Worker.ProgressChanged += new ProgressChangedEventHandler(m_Worker_ProgressChanged);
m_Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_Worker_RunWorkerCompleted);
}
void m_Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Usually, used to update a progress bar
}
void m_Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Usually, used to add some code to notify the user that the job is done.
}
void m_Worker_DoWork(object sender, DoWorkEventArgs e)
{
//e.Argument.ToString() contains the path to the file
//Do what you want with the file returned.
}
private void bOpen_Click(object sender, EventArgs e)
{
OpenFileDialog d = new OpenFileDialog();
if (d.ShowDialog() == DialogResult.OK)
{
m_Worker.RunWorkerAsync(d.FileName);
}
}
BackgroundWorker m_Worker = new BackgroundWorker();
}
Now, as for the reason your UI "hangs", it's because by default, your operation runs on the UI thread, so if you run something heavy the UI won't respond.
I also met this problem. And I tried all the solution here and none can solve it. Then I change the target framework from .Net Framework 4.7 to 4.6.2, the problem solved...
I think my problem is different, as none of the above solutions worked for me.
I wrote temporary code to set the OpenFileDialog.FileName property to something not null or empty string (it was empty string when the hang up occured), and I restarted my computer. When I started up Visual Studio again, and ran it, it worked again without hanging up.
This has happened many times before, but I never bothered to figure out why, and now I am tired of it:
For instance, I derive a class from RichTextBox or Panel, I rebuild my project to have the class added to the VS designer toolbox, and then I drag & drop the custom user control to a Form. Everything works fine, and I can run my project...
The problem comes when I edit properties of the Form or the custom user control through the designer. Sometimes, the designer removes the initialization line from its code-behind, causing an exception in the designer and the executable because the control remains uninitialized.
In other words, the following line is removed from say, Form1.Designer.cs:
this.customRichTextBox1=new CustomRichTextBox();
No other line is removed from the code-behind, so the attributes of the custom control are still set, although the variable stays uninitialized.
My solution has always been to manually initialize my user control in the designer code-behind, but the designer eventually removes it again.
I believe that this does not happen when I build a Custom UserControl through the designer (but I am not completely sure of this). It only happens when I define something like the following manually:
class CustomRichTextBox:RichTextBox{}
This is so annoying. What am I doing wrong?
As #Cody requested, here are the steps to reproduce the problem. I am using VS2010, but I've had this problem since 2005, I think.
Step 1. Create new Windows Forms Application, any Framework
Step 2. Add the following class below your main Form class: (It just happens that this is the control that is causing me this problem this time.)
class CustomRichTextBox : RichTextBox
{
Timer tt = new Timer();
internal CustomRichTextBox()
{
tt.Tick += new EventHandler(tt_Tick);
tt.Interval = 200;
}
protected override void OnTextChanged(EventArgs e)
{
tt.Stop();
tt.Start();
}
void tt_Tick(object sender, EventArgs e)
{
System.Diagnostics.Trace.WriteLine("Hello world!");
}
}
Step 3. Press F6 to rebuild.
Step 4. Add the CustomRichTextBox control to your Form by dragging and dropping from the Toolbox.
Step 5. If you wish, you may press F5 to test the application, but it should work. Close the running application.
Step 6. Press F6 to rebuild, and at this point, the designer should crash with the following message: "The variable 'customRichTextBox1' is either undeclared or was never assigned." (In one case, the whole VS completely crashed, but the error is usually contained within the designer.)
Step 7. To correct the issue, go into the code-behind and initialize the variable, but next time you rebuild, the initialization line will be gone.
Thanks to everyone who tried answering my question and who posted comments that helped me diagnose and solve the problem.
The problem occurs when using an "internal" keyword with the control's constructor. Changing it to "public" fixes the problem. The reason for this behavior might be that the Designer's own classes cannot see the constructor because they are not within the namespace of my class unless it is marked public. This all makes sense, and I will use the public keyword from now on.
The class does not need to be in its own individual file or be the first declared class in the file as other answers suggested.
The following class works well because the constructor's keyword was changed to public.
class CustomRichTextBox : RichTextBox
{
Timer tt = new Timer();
public CustomRichTextBox()
{
tt.Tick += new EventHandler(tt_Tick);
tt.Interval = 200;
}
protected override void OnTextChanged(EventArgs e)
{
tt.Stop();
tt.Start();
}
void tt_Tick(object sender, EventArgs e)
{
System.Diagnostics.Trace.WriteLine("Hello world!");
}
}
Is your build set to Debug or it is Release?
I suppose that it is release as I think compiler optimizes the code and remove designer generated line.
Have you tried putting the control code in its own file? I've had problems even with the form designer in the past when the designer code was not int he first class in the file.
I had a similar problem that this posted helped me solve. I have a CustomControl that extends ComboBox, that class contained an internal private class YearItem. I've tried to highlight only the code needed to understand the problem and the solution.
public class YearsCbo : ComboBox //Inherits ComboBox
{
public YearsCbo() {
fill();
}
private void fill() { // <<<=== THIS METHOD ADDED ITEMS TO THE COMBOBOX
for(int idx = 0; idx < 25; idx++) {
this.Items.Add(new YearItem());
}
}
// Other code not shown
private class YearItem {} // <<<=== The VS designer can't access this class and yet
// it generated code to try to do so. That code then fails to compile.
// The compiler error rightfully says it is unable to access
// the private class YearItem
}
I could drag/drop that control YearsCbo onto a form and it worked correctly, but after I returned and edited the form the VS designer generated code that would not compile. The offending code something like this:
Dim YearItem1 As my.ns.YearsCbo.YearItem = New my.ns.YearsCbo.YearItem()
Dim YearItem2 As my.ns.YearsCbo.YearItem = New my.ns.YearsCbo.YearItem()
// This was repeated 25 times because in my constructor I created 25 of these
Me.YearsCbo1.Items.AddRange(New Object() {YearItem1, 2, 3, ..., YearItem25 });
Notice that the designer generated code which tried to access the private class. It didn't need to do that but for some reason it did.
Through trial and error, and this post: How to tell if .NET code is being run by Visual Studio designer came up with a solution:
I added a property to tell if I am running in the designer.
public bool HostedDesignMode
{
get
{
if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
return true;
else
return false;
}
}
I also changed the constructor so that it doesn't call fill() so when the designer runs, there are no items in the ComboBox so the designer doesn't feel the need to manually create those items.
The "fixed" code is shown below:
public class YearsCbo : ComboBox //Inherits ComboBox
{
public YearsCbo() {
if ( ! HostedDesignMode ) {
fill();
}
}
private class YearItem {} // <<<=== Now the VS Designer does not try to access this
}
This code was written using VS2012 Premium on Win7x64 OS (in case it matters).