I have an application which has several tabs. I am trying to add logging with NLog where the output is directed to a richtextbox.
My main form is an instance of a class MyNamespace.MainWindow and its name is MainWindow1. It has a tab and in that tab I have a RichTextBox called rtbLogBox
I have imported WpfRichTextBox extension from NuGetand place this piece of code in the MainWindow class's loaded event
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if(logger == null) logger = LogManager.GetCurrentClassLogger();
WpfRichTextBoxTarget rtbTarget = new WpfRichTextBoxTarget
{
Name = "rtbLog",
ControlName = "rtbLogBox",
FormName = "MainWindow"
};
LogManager.Configuration.AddTarget(rtbTarget);
LogManager.Configuration.AddRule(LogLevel.Info, LogLevel.Fatal, rtbTarget.Name);
logger.Info("This");
}
The problem is that this does not produce any outputs in the RichTextBox control.
I have an output to a file in addition to this and that target gets the log when I run the app.
Since the logger is created before you are changing the LogManager's configuration, you need to notify the logger of the change.
Calling LogManager.ReconfigExistingLoggers() should do the trick.
Documentation is here.
You can also use my wpf control. (https://github.com/dojo90/NLogViewer). There is also a nuget package available.
Related
I just want to start by saying that I've done a lot of research but couldn't find an answer, hence the post.
I'm adding user settings functionality to my app which works as a plugin inside a common off the shelf program for architecture (called Autodesk Revit). The main project (let's call it MainProj) has several dependencies including a project that handles logging and usage (let's call it Loggers). I created a Settings file inside the Loggers project with the goal to have users change the logging level from Error to Debug when there are issues so I can ask them to make the change and send me the log.
The issue I'm facing is that when I change the log level directly inside the config file and re-run the command from within Revit, the change doesn't get translated into the log, as if the log level is somehow compiled during design and is never changed.
I actually tried to reproduce the problem in a simpler way and created a little console program and I'm facing the same issue. Below is the code from the Loggers project.
namespace Loggers
{
public static class Logger
{
public static string RunMe()
{
if (Properties.Settings.Default.LogMode == "Debug") { return "DEBUG"; }
else return "NOTHING";
}
}
}
I then changed the LogMode property from Debug to anything else in the config file but the console kept on returning DEBUG.
static void Main(string[] args)
{
Console.WriteLine(Logger.RunMe());
Console.Read();
}
I also tried changing the setting from user to application and editing its value in the config file and re-running the command but the outcome was the same.
Any help would be very much appreciated. I've been stuck on this for a while. Thank you.
Thanks to #BurnsBA, the link you shared had comments saying that the user.config lives in a different folder and it's not created until the user changes a setting. This made me understand that there wasn't a point in manually editing the app.config and expect the settings to work.
I then did some testing by creating a simple form with a checkbox linked to the Property I wanted to change and the user.config file gets created straight after I call the Save() method on the Properties.
private void btnOK_Click(object sender, EventArgs e)
{
if (chkDebugMode.Checked == true)
Loggers.Properties.Settings.Default.LogMode = "Debug";
else Loggers.Properties.Settings.Default.LogMode = "Error";
Loggers.Properties.Settings.Default.Save();
Close();
}
I have created a boolean algebraic simplifier. It simplifies expressions and I am content with it. However, I am trying to add a feature that allows users to check if two expressions are equivalent. For this I have created a new form that allows the user to input two expression by clicking buttons. To do this, I thought it best to simplify both expressions and then compare the two for equivalency. As I have got lots of subroutines and code that works for simplification in another form, I thought making the form a child form of the form with the code in would allow me to call the subroutines instead of copying them onto the form. I have made these protected in the parent form. I have inherited like so:
public partial class Expression_Equivalency_Form : Expression_Simplifier
However, when I click onto the form designer, this error appears and I cannot view the graphical interface of the form:
"Could not find file File Path"
The file is in the debug folder which is within the bin folder within the folder containing the program and is recongised in the parent class. The file is read from and appeneded by the parent form without issue. I have tried to research this but have been unable to find a solution. Does anyone know one?
I have read to the file and appended to it. I have also used the following code to remove any blank lines from my text file:
File.WriteAllLines("PreviousExpressionInputs.txt",
File.ReadAllLines("PreviousExpressionInputs.txt").Where(l => !string.IsNullOrWhiteSpace(l)));
Code that writes to the file:
using (BinaryWriter Writer = new BinaryWriter(File.Open("PreviousExpressionInputs.txt",
FileMode.Append)))
{
Writer.Write(expressionandanswertowritetotextfile);
}
Code that reads from the file:
foreach (string line in File.ReadLines("PreviousExpressionInputs.txt"))
{
try
{
LinesInFile.Add(line);
}
catch (Exception)
{
}
}
Consider following facts:
When you open a form in design mode, the constructor of its base class will run.
When you look for a relative file name, the path will be resolved relative to the current working directory of the application.
When the form is in design mode, the current application is Visual Studio and its working directory is where the devenv.exe is located.
It describes why you cannot find your text files. Because you have some code in the constructor of your base form(or fir example load event handler of the base form) which looks for the file and since the filename is relative, its looking for the file in the Visual Studio working directory and could not find file.
How to prevent the problem? Check DesignMode property to prevent running the code:
public partial class MyBaseForm : Form
{
public MyBaseForm()
{
InitializeComponent();
}
private void MyBaseForm_Load(object sender, EventArgs e)
{
MessageBox.Show("This will show both in run-time and design time.");
if (!DesignMode)
MessageBox.Show("This will show just in run-time");
}
}
Create the derived form and open it in designer to see what happens:
public partial class Form1 : MyBaseForm
{
public Form1()
{
InitializeComponent();
}
}
To learn more about how designer works take a look at this post.
I have a WPF application which is localized.
When I set Format to Hindi(India) from ControlPanel -> Region -> Formats, Following lines of code in my WPF application at the beginning of launching of my WPF Application is not reading CultureInfo.CurrentCulture(hi-IN) instead it uses en-US.
Application.Current.MainWindow = new MainWindow();
Application.Current.MainWindow.Show();
Because of this, My WPF Application is not using greeting message from Resources.resx file. Instead, it is use greeting message from in Resources.en.resx
I am getting proper value in CultureInfo.CurrentCulture.
Any idea why above lines of code are not picking proper value?
The ControlPanel->Region->Formats setting doesn't apply to .resx files. It is in ControlPanel->Region->Language that you specify the default language.
What is the difference between CurrentCulture and CurrentUICulture properties of CultureInfo in .NET?
Alternatively you could specify the default language of your resources in your App class (App.xaml.cs):
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Resources.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
}
}
Please refer to the following link for more information: https://social.msdn.microsoft.com/Forums/vstudio/en-US/6bfb8d13-3a86-4c10-a632-bb20c99d0535/localization-in-wpf-using-resx-files-for-different-languages?forum=wpf.
I have a problem that I am using coding4fun dll in my WP7 application for showing the popup messages.
I am using:
Micrsoft.Phone.Controls.Toolkit
Coding4fun.Phone.Controls
At first launch of deployment on device its crashing saying that value cannot be null(parameter name element) while on emulator its running fine. I have tried the latest version of this dll but the result was same.
While adding Micrsoft.Phone.Controls.Toolkit of latest version 1.4.8 is giving warning that adding a silverlight library may result in unexpected consequences.
while I tried other version of this dll still no success.
I am getting exception in stacktrace
Clarity.Phone.Extensions.DialogService.InitializePopUp
Clarity.Phone.Extensions.DilaogService.Show
Basically i am using that popup inside constuctor of mainpage.xaml(first page) after InitializeComponent() and it is throwing null reference type at first launch while deploying but app is getting installed. again if i run application on device then it is appearing correctly.
My code is:
notificationPrompt = new MessagePrompt();
notificationPrompt.Title = "Notification"
notificationPrompt.Body = "";
notificationPrompt.ActionPopUpButtons.Clear();
Button btnDisclaimer = new Button() { Content = "Yes" };
btnDisclaimerContinue.Click += new RoutedEventHandler(btnNotificationPromptYes_Click);
Button btnDisclaimerCancel = new Button() { Content = "No" };
btnDisclaimerCancel.Click += new RoutedEventHandler(btnNotificationPromptNo_Click);
notificationPrompt.ActionPopUpButtons.Add(btnDisclaimerContinue);
notificationPrompt.ActionPopUpButtons.Add(btnDisclaimerCancel);
notificationPrompt.Show();
I think it's the better to move all this code outside the constructor, and put it inside the Loaded event (occurs when a FrameworkElement has been constructed and added to the object tree: http://msdn.microsoft.com/en-us/library/ms596558(vs.95)) of the PhoneApplicationPage class, or just override the OnNavigatedTo method:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
// What you want here...
...
}
Often when you have exceptions in the constructor of a PhoneApplicationPage, they will not show, making the debug more difficult and annoying...
This may be a long shot, but I'm using ComponentOne's Spellchecker control for Silverlight. I made a test project, added a plain textbox and a button to it, added the references to the C1.Silverlight and C1.Silverlight.SpellChecker bits, and added the dictionary file to my project.
In the code, I called up the spellchecker on button1's click event and it worked SPLENDIDLY. The spellchecker dialog shows up, and works exactly as it should.
Since that test was successful, I then tried to implement this into my existing project. I've had no success for absolutely NO reason that I can determine, since I used the EXACT SAME code.
Here's the code I use to call the component:
using C1.Silverlight;
using C1.Silverlight.SpellChecker;
using C1.Silverlight.Resources;
public partial class MainPage : UserControl
{
C1SpellChecker spellChecker = new C1SpellChecker();
public MainPage()
{
InitializeComponent();
spellChecker.MainDictionary.LoadAsync("C1Spell_en-US.dct");
}
private void btnSpelling_Click(object sender, RoutedEventArgs e)
{
var dlg = new C1SpellDialog();
spellChecker.CheckControlAsync(txtArticle, false, dlg);
}
The references to C1.Silverlight and C1.Silverlight.Spellchecker are added to this project as well, and the dictionary as been added in the same fashion as well. The issue seems to be that for whatever reason the dictionary is not loading, because the spellChecker.Enabled method returns whether or not the main dictionary has been loaded. If I call MessageBox.Show("SpellChecker Enabled = " + spellChecker.Enabled.ToString()); it shows false, even though the call to load the dictionary is there (as you can see).
What would cause the dictionary to not load? Have I added it to my project incorrectly somehow?
EDIT: I suspect that I have added the dictionary to the project incorrectly, because the ComponentOne reference states:
If C1SpellChecker cannot find the
spelling dictionary, it will not throw
any exceptions. The Enabled property
will be set to false and the component
will not be able to spell-check any
text.
I just don't know what's wrong though because it was added in the same way that it was in the test project (Right clicked on the project.web->Add->Existing Item)
As always, thank you!
-Sootah
You could add the dictionary to the Silverlight app as an embedded resource and then load it using this code:
public MainPage()
{
InitializeComponent();
// load C1SpellChecker dictionary from embedded resource
var asm = this.GetType().Assembly;
foreach (var res in asm.GetManifestResourceNames())
{
if (res.EndsWith(".dct"))
{
using (var s = asm.GetManifestResourceStream(res))
{
sc.MainDictionary.Load(s);
break;
}
}
}
}
I think this post is duplicated in our forum as well, but will answer first here. Please try this:
1) Try to access the .dct file using your browser. If you cannot see it, it's probably because your web server is not serving that type of files. You need ton configure the web server to allow it.
2) verify the URL you are using is correct.http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/86955/241328.aspx#241328
3) Check you are setting everything correctly: http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/81924/227790.aspx#227790
Hope this helps!