Can I get the NLogViewer to display entire log file? - wpf

I have a "long-running" WPF desktop application which uses NLog and the NLogViewer to display runtime status. It is used to monitor a database, pick up requests for processing, and then logging the results. (Yeah -- should have been a service, but we wanted to start out this way first -- baby steps.) The results are logged to a text log file and the NLogViewer shows the current items in the log in real time.
After the app has been running several hours, I've noticed I can only view a portion of the log -- from current entry back to an hour or so earlier. The scrollbar lets me scroll down to the most current entry, but stops way before the first entry. At this time, there isn't a lot of logging going on, i.e., no debugging or tracing, just Info, Warnings, and Errors, so I don't think the size of the log would have an impact.
Is there a way to have the NLogViewer let me view the entire log file or will it only show me a limited window into the log? Is there an alternate NLog viewer WPF control? I'm not really looking at a standalong NLog viewer at this time. If you need more information, please let me know.
Thanks!
Edit: I had some time to revisit this issue and got the NLogViewer source from GitHub. In the code-behind for the view, there is a hard coded value of 50 for the number of entries held in the items source for the ListView. For each item over 50, an item is removed from the beginning of the log. I could, of course, download the source and modify it to my liking which might be the final solution as the project hasn't been updated in 3 years. However, I might try and see if I can create a wrapper around the original control and allow for some basic extensions such as a configurable number of log entries to display and to always show the last entry added. If I have any success, I'll post what I did.

I made a new version of the NLogViewer. Without any limitation. You can also change the style if you want to
https://www.nuget.org/packages/Sentinel.NLogViewer
https://github.com/dojo90/NLogViewer

I spend a lot of time yesterday working on this, trying to just extend the existing class with new behaviors or properties. The biggest issue was with the hard coded 50 entries in a protected method that I couldn't access or override. And since the NLogViewer control is defined with XAML, I couldn't easily subclass it with a "non-XAML" class (compile errors). In the end, it seemed simpler to just use the original source code and make some mods to get the desired results.
I made the following changes:
I added 2 properties to the NLogViewer "view":
[Description("Automatically scroll last entry into view?"), Category("Data")]
public bool ScrollIntoView { get; set; } = true;
[Description("How many log entries should be kept in memory."), Category("Data")]
public int VisibleEntryCount { get; set; } = 50; // Original code default
These will control if the last log entry is scrolled into view and how many log entries will be available for display.
I modified the existing LogReceived handler to use the VisibleEntryCount property.
protected void LogReceived(NLog.Common.AsyncLogEventInfo log)
{
LogEventViewModel vm = new LogEventViewModel(log.LogEvent);
if (this.VisibleEntryCount == 0)
{
this.VisibleEntryCount = 50; // Original code default.
}
this.Dispatcher.BeginInvoke(new Action(() =>
{
if (this.LogEntries.Count >= this.VisibleEntryCount)
{
// We've reached our limit.
this.LogEntries.RemoveAt(0);
}
this.LogEntries.Add(vm);
}));
}
And I added a new event handler for whenever a new log entry is added. This will let me ensure the last entry is always visible (if specified by the user).
private void LogEntries_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (this.ScrollIntoView)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
if (this.logView != null)
{
int count = this.LogEntries.Count;
object selectedItem = (count > 0) ? this.LogEntries[count - 1] : null;
if (selectedItem != null)
{
this.logView.Dispatcher.BeginInvoke((Action)(() =>
{
this.logView.UpdateLayout();
this.logView.ScrollIntoView(selectedItem);
}));
}
}
}
}
}
It seems to be working OK. As always, I'm open to additional solutions or suggestions. Thanks!

Related

DataGrid virtualization on collectionview refresh

Specifically this is a follow-up to this question DataGrid filter performance, but there are many more similar questions relating to WPF DataGrid performance on StackOverflow.
After a lot of profiling and going through .NET source code, I have realized that many performance issues, such as filtering and sorting, boil down just one issue: A CollectionView.Reset event does not recycle containers (like scrolling does).
What I mean is that instead of assigning the existing rows a new datacontext, all rows are removed from the visual tree, new rows are generated and added, and a layout cycle (measure and arrange) is performanced.
So the main question is: Has anyone successfully managed to work around this? E.g. by manually manipulating the ItemContainerGenerator, or by creating their own version of the DataGridRowsPresenter?
So this is the gist of my approach so far.
public class CollectionViewEx
{
public event EventHandler Refresh;
public override void Refresh()
{
Refresh?.Invoke(this, EventArgs.Empty);
}
}
public class DataGridEx : DataGrid
{
protected override OnItemsSourceChanged(IEnumerable oldSource, IEnumerable newSource)
{
if (newSource is CollectionViewEx cvx)
{
cvx.Refresh += (o,a) => OnViewRefreshing;
}
}
private void OnViewRefreshing()
{
RowsPresenter.Refresh();
}
}
public class DataGridRowsPresenterEx : DataGridRowsPresenter
{
public void Refresh()
{
var generator = (IRecyclingItemContainerGenerator)ItemContainerGenerator;
generator.Recycle(new GeneratorPosition(0, 0), ???);
RemoveInternalChildRange(0, VisualChildrenCount);
using (generator.StartAt(new GeneratorPosition(-1, 0), GeneratorDirection.Forward))
{
UIElement child;
bool isNewlyRealised = false;
while ((child = generator.GenerateNext(out isNewlyRealised) as UIElement) != null)
{
AddInternalChild(child);
generator.PrepareItemContainer(child);
}
}
}
}
But the results are very confusing - obviously because I don't quite understand how to work with the ICG.
I have looked through .net source code to see their implementations (when adding/removing/replacing items), and also found a couple of online resources on how to create a new virtualized panel (e.g. virtualizingwrappanel), but none really address this particular issue, where we want to reuse all existing containers for a new set of items.
So the secondary question is: Can anyone explain if this approach is even possible? How would I do it?
I never use reset directly from CollectionView because a methode on CollectionView's Source do it. This IList is modified for my needs. I did it like Paul McClean explained here.
In this class you could notify OnCollectionChanged to inform the CollectionView. sondergard explained what NotifyCollectionChangedAction.Reset do. But NotifyCollectionChangedAction.Replace keep running the recyling for the Items.
Maybe my research helps.

How to show computed property values in EPiServer 8?

In page edit mode I want to show a read-only text that is based on a page property value. The text could for example be "A content review reminder email will be sent 2015-10-10", where the date is based on the page published date + six months (a value that will be configurable and therefore can change anytime). So far I've tried to accomplish something like this by adding another property on the page.
I've added the property CurrentReviewReminderDate to an InformationPage class we use. In page edit mode the property name is shown, but it doesn't have a value. How do I do to show the value in page edit mode (preferably as a label)?
[CultureSpecific]
[Display(
Name = "Review reminder date",
Description = "On this date a reminder will be sent to the selected mail to remember to verify page content",
Order = 110)]
[Editable(false)]
public virtual string CurrentReviewReminderDate
{
get
{
var daysUntilFirstLevelReminder =
int.Parse(WebConfigurationManager.AppSettings["PageReviewReminder_DaysUntilFirstLevelReminder"]);
if (CheckPublishedStatus(PagePublishedStatus.Published))
{
return StartPublish.AddDays(daysUntilFirstLevelReminder).ToString();
}
return "";
}
set
{
this.SetPropertyValue(p => p.CurrentReviewReminderDate, value);
}
}
EPiServer internally uses the GetPropertyValue method (i.e. the opposite of SetPropertyValue) when retrieving content for the UI.
This makes sense, otherwise your "made-up" value would be stored as the real value whenever the content is saved. This would make fall-back values etc impossible to implement.
So, this is by-design (and quite wisely so) in EPiServer. :)
However, you can customize how properties work by:
Using custom editors by applying UI hints
Modifying property metadata (for example, to display a generated value as a watermark in a textbox without interfering with the actual value being saved)
I could be misunderstanding what you're trying to do, but off the top of my head it looks like a custom editor could be a viable option for your use case?
Another solution would be to hook into the LoadedPage-event and add the value from there. This might not be the best way performance-wise since you need to do a CreateWritableClone, but depending on the site it might not matter.
[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class EventInitialization : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
ServiceLocator.Current.GetInstance<IContentEvents>().LoadedContent += eventRegistry_LoadedContent;
}
void eventRegistry_LoadedContent(object sender, ContentEventArgs e)
{
var p = e.Content as EventPage;
if (p != null)
{
p = p.CreateWritableClone() as EventPage;
p.EventDate = p.StartPublish.AddDays(10);
e.Content = p;
}
}
}

Do XAML objects remain virtually present when leaving a XAML page in Windows 8 App?

I use the MVVM Light Toolkit to define the association between the view-model and the view.
The container is instructed to register a view-model as a singleton instance. Thus, the same instance will always be returned when the GagaViewModel is required:
public GagaViewModel GagaViewModel
{
get
{
var vm = ServiceLocator.Current.GetInstance<GagaViewModel>();
vm.Setup(); //Clear the ObservableCollection
return vm;
}
}
You can click on a thumbnail item on PriorGaga.xml. The self-chosen item is then selected in the GridView "MyGridView" in Gaga.xaml. Code-behind file of Gaga.xaml:
protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
var itemId = navigationParameter as String;
if (String.IsNullOrEmpty(itemId))
{
throw new ArgumentException("navigationParameter was either null or empty");
}
await ((GagaViewModel)DataContext).Init(itemId); //Busy(-Indicator) while loading data from server, filling the ObservableCollection and writing the selected item down
BringItemIntoView();
}
private void BringItemIntoView()
{
var vm = (GagaViewModel)DataContext;
Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() => MyGridView.ScrollIntoView(vm.SelectedItem));
}
That works fine. As a sample: Item #45 appears within the viewport immediately (correct viewport position from the beginning).
But when you click the back button and return to Gaga.xaml by selecting an arbitrarily thumbnail item (let's just say #29), you will see item #1 and then the switch to #29 (the viewport is moving over the container). Do someone know what's going on under there? Are there any virtualized items in the container from the preceding Gaga.xaml visit?
My understanding is that the lifespan of the instance of your Gaga page is determined by its NavigationCacheMode property. By default, it is set to Disabled. Assuming that you haven't changed this property, you should be seeing a new instance of your Gaga page every time you navigate to it. You can verify this behavior by setting a breakpoint in its constructor. Consequently, I would think that each time you navigate to Gaga, the behavior of the UI should be identical, because everything is fresh.
(I wanted to add this as a comment, since I haven't actually answered your question, but sadly I do not have enough rep. I apologize in advance; please do not smite me down!)

Entity Framework and WPF best practices

Is it ever a good idea to work directly with the context? For example, say I have a database of customers and a user can search them by name, display a list, choose one, then edit that customer's properties.
It seems I should use the context to get a list of customers (mapped to POCOs or CustomerViewModels) and then immediately close the context. Then, when the user selects one of the CustomerViewModels in the list the customer properties section of the UI populates.
Next they can change the name, type, website address, company size, etc. Upon hitting a save button, I then open a new context, use the ID from the CustomerViewModel to retrieve that customer record, and update each of its properties. Finally, I call SaveChanges() and close the context. This is a LOT OF WORK.
My question is why not just work directly with the context leaving it open throughout? I have read using the same context with a long lifetime scope is very bad and will inevitably cause problems. My assumption is if the application will only be used by ONE person I can leave the context open and do everything. However, if there will be many users, I want to maintain a concise unit of work and thus open and close the context on a per request basis.
Any suggestions? Thanks.
#PGallagher - Thanks for the thorough answer.
#Brice - your input is helpful as well
However, #Manos D. the 'epitome of redundant code' comment concerns me a bit. Let me go through an example. Lets say I'm storing customers in a database and one of my customer properties is CommunicationMethod.
[Flags]
public enum CommunicationMethod
{
None = 0,
Print = 1,
Email = 2,
Fax = 4
}
The UI for my manage customers page in WPF will contain three check boxes under the customer communication method (Print, Email, Fax). I can't bind each checkbox to that enum, it doesn't make sense. Also, what if the user clicked that customer, gets up and goes to lunch... the context sits there for hours which is bad. Instead, this is my thought process.
End user chooses a customer from the list. I new up a context, find that customer and return a CustomerViewModel, then the context is closed (I've left repositories out for simplicity here).
using(MyContext ctx = new MyContext())
{
CurrentCustomerVM = new CustomerViewModel(ctx.Customers.Find(customerId));
}
Now the user can check/uncheck the Print, Email, Fax buttons as they are bound to three bool properties in the CustomerViewModel, which also has a Save() method. Here goes.
public class CustomerViewModel : ViewModelBase
{
Customer _customer;
public CustomerViewModel(Customer customer)
{
_customer = customer;
}
public bool CommunicateViaEmail
{
get { return _customer.CommunicationMethod.HasFlag(CommunicationMethod.Email); }
set
{
if (value == _customer.CommunicationMethod.HasFlag(CommunicationMethod.Email)) return;
if (value)
_customer.CommunicationMethod |= CommunicationMethod.Email;
else
_customer.CommunicationMethod &= ~CommunicationMethod.Email;
}
}
public bool CommunicateViaFax
{
get { return _customer.CommunicationMethod.HasFlag(CommunicationMethod.Fax); }
set
{
if (value == _customer.CommunicationMethod.HasFlag(CommunicationMethod.Fax)) return;
if (value)
_customer.CommunicationMethod |= CommunicationMethod.Fax;
else
_customer.CommunicationMethod &= ~CommunicationMethod.Fax;
}
}
public bool CommunicateViaPrint
{
get { return _customer.CommunicateViaPrint.HasFlag(CommunicationMethod.Print); }
set
{
if (value == _customer.CommunicateViaPrint.HasFlag(CommunicationMethod.Print)) return;
if (value)
_customer.CommunicateViaPrint |= CommunicationMethod.Print;
else
_customer.CommunicateViaPrint &= ~CommunicationMethod.Print;
}
}
public void Save()
{
using (MyContext ctx = new MyContext())
{
var toUpdate = ctx.Customers.Find(_customer.Id);
toUpdate.CommunicateViaEmail = _customer.CommunicateViaEmail;
toUpdate.CommunicateViaFax = _customer.CommunicateViaFax;
toUpdate.CommunicateViaPrint = _customer.CommunicateViaPrint;
ctx.SaveChanges();
}
}
}
Do you see anything wrong with this?
It is OK to use a long-running context; you just need to be aware of the implications.
A context represents a unit of work. Whenever you call SaveChanges, all the pending changes to the entities being tracked will be saved to the database. Because of this, you'll need to scope each context to what makes sense. For example, if you have a tab to manage customers and another to manage products, you might use one context for each so that when a users clicks save on the customer tab, all of the changes they made to products are not also saved.
Having a lot of entities tracked by a context could also slow down DetectChanges. One way to mitigate this is by using change tracking proxies.
Since the time between loading an entity and saving that entity could be quite long, the chance of hitting an optimistic concurrency exception is greater than with short-lived contexts. These exceptions occur when an entity is changed externally between loading and saving it. Handling these exceptions is pretty straightforward, but it's still something to be aware of.
One cool thing you can do with long-lived contexts in WPF is bind to the DbSet.Local property (e.g. context.Customers.Local). this is an ObservableCollection that contains all of the tracked entities that are not marked for deletion.
Hopefully this gives you a bit more information to help you decide which approach to help.
Microsoft Reference:
http://msdn.microsoft.com/en-gb/library/cc853327.aspx
They say;
Limit the scope of the ObjectContext
In most cases, you should create
an ObjectContext instance within a using statement (Using…End Using in
Visual Basic).
This can increase performance by ensuring that the
resources associated with the object context are disposed
automatically when the code exits the statement block.
However, when
controls are bound to objects managed by the object context, the
ObjectContext instance should be maintained as long as the binding is
needed and disposed of manually.
For more information, see Managing Resources in Object Services (Entity Framework). http://msdn.microsoft.com/en-gb/library/bb896325.aspx
Which says;
In a long-running object context, you must ensure that the context is
disposed when it is no longer required.
StackOverflow Reference:
This StackOverflow question also has some useful answers...
Entity Framework Best Practices In Business Logic?
Where a few have suggested that you promote your context to a higher level and reference it from here, thus keeping only one single Context.
My ten pence worth:
Wrapping the Context in a Using Statement, allows the Garbage Collector to clean up the resources, and prevents memory leaks.
Obviously in simple apps, this isn't much of a problem, however, if you have multiple screens, all using alot of data, you could end up in trouble, unless you are certain to Dispose your Context correctly.
Hence I have employed a similar method to the one you have mentioned, where I've added an AddOrUpdate Method to each of my Repositories, where I pass in my New or Modified Entity, and Update or Add it depending upon whether it exists.
Updating Entity Properties:
Regarding updating properties however, I've used a simple function which uses reflection to copy all the properties from one Entity to Another;
Public Shared Function CopyProperties(Of sourceType As {Class, New}, targetType As {Class, New})(ByVal source As sourceType, ByVal target As targetType) As targetType
Dim sourceProperties() As PropertyInfo = source.GetType().GetProperties()
Dim targetProperties() As PropertyInfo = GetType(targetType).GetProperties()
For Each sourceProp As PropertyInfo In sourceProperties
For Each targetProp As PropertyInfo In targetProperties
If sourceProp.Name <> targetProp.Name Then Continue For
' Only try to set property when able to read the source and write the target
'
' *** Note: We are checking for Entity Types by Checking for the PropertyType to Start with either a Collection or a Member of the Context Namespace!
'
If sourceProp.CanRead And _
targetProp.CanWrite Then
' We want to leave System types alone
If sourceProp.PropertyType.FullName.StartsWith("System.Collections") Or (sourceProp.PropertyType.IsClass And _
sourceProp.PropertyType.FullName.StartsWith("System.Collections")) Or sourceProp.PropertyType.FullName.StartsWith("MyContextNameSpace.") Then
'
' Do Not Store
'
Else
Try
targetProp.SetValue(target, sourceProp.GetValue(source, Nothing), Nothing)
Catch ex As Exception
End Try
End If
End If
Exit For
Next
Next
Return target
End Function
Where I do something like;
dbColour = Classes.clsHelpers.CopyProperties(Of Colour, Colour)(RecordToSave, dbColour)
This reduces the amount of code I need to write for each Repository of course!
The context is not permanently connected to the database. It is essentially an in-memory cache of records you have loaded from disk. It will only request records from the database when you request a record it has not previously loaded, if you force it to refresh or when you're saving your changes back to disk.
Opening a context, grabbing a record, closing the context and then copying modified properties to an object from a brand new context is the epitomy of redundant code. You are supposed to leave the original context alone and use that to do SaveChanges().
If you're looking to deal with concurrency issues you should do a google search about "handling concurrency" for your version of entity framework.
As an example I have found this.
Edit in response to comment:
So from what I understand you need a subset of the columns of a record to be overridden with new values while the rest is unaffected? If so, yes, you'll need to manually update these few columns on a "new" object.
I was under the impression that you were talking about a form that reflects all the fields of the customer object and is meant to provide edit access to the entire customer record. In this case there's no point to using a new context and painstakingly copying all properties one by one, because the end result (all data overridden with form values regardless of age) will be the same.

Start and Back Button pressed in rapid succession WP7

I asked this question in a similar post but there have been significant updates since then, but still no results so I will try to re-ask the question with the updated information.
Basically I have a pivot view with 4 pivot items. If I create the scenario where I hit the windows key then rapidly press the back key my application will reopen without reconstructing (this is the expected outcome). The functionality of the application is there. I can press application bar buttons etc.
What doesn't work is the pivot items are frozen. If I was on Pivot item A and I press the start and back button quickly I come back to Pivot Item A. If I try to switch Pivot Items, the screen does not update, its "frozen" on Pivot Item A BUT the functionality of Pivot Item B is there. (I know this because the application bar Icons for Pivot Item B are now showing).
I have read many articles on proper tombstoning scenarios and how to approach this problem. My data IS being tombstoned correctly, and upon reactivation the tombstoned data works. No objects are null so I don't have any exceptions being thrown at me.
I check to see if I need to reload the Main ViewModel (I don't need to in this case so the UI elements being created initially are not being re created).
What does fix the problem however is if the application is reconstructed. Lets say I go to the marketplace from my app, let it finish loading and press back, My application will be refreshed and working fine since it properly deactivated and reconstructed istelf. I don't rely on constructors doing all the work so I am not missing any key elements not being set when they aren't fired in the windows/back button scenario.
Does anyone have any idea why my screen would not be updating?
constructor/loaded event/on navigated to event
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (App.firstTimeLoading == true)
{
App.firstTimeLoading = false;
}
BuildApplicationBar();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.DataContext = App.ViewModel;
App.viewIdentifier = StringResource.MainPageView;
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
String bookTitle;
App.Parser.appBookInfoDict.TryGetValue(CPlayerInventoryKeys.kInventoryKeyTitleShortTitle, out bookTitle);
PivotBackground.Title = bookTitle.ToUpper();
CreatePivotItems();
}
if (App.playerController.chapterPlayer.Source == null)
App.restoreStateClass.RestoreState();
//applies the proper background image
if (App.isDarkTheme)
{
BitmapImage bitmapImage = new BitmapImage(new Uri(StringResource.PanoramaBlackImage, UriKind.Relative));
BackgroundImage.ImageSource = bitmapImage;
BackgroundImage.Opacity = .85;
}
else
{
BitmapImage bitmapImage = new BitmapImage(new Uri(StringResource.PanoramaWhiteImage, UriKind.Relative));
BackgroundImage.ImageSource = bitmapImage;
BackgroundImage.Opacity = .5;
}
if (App.firstTimeLoading == false && PivotBackground.SelectedItem != SuggestedPivotItem)
BuildApplicationBar();
else if (PivotBackground.SelectedItem == SuggestedPivotItem)
{
BuildMarketPlaceApplicationBar();
}
base.OnNavigatedTo(e);
}
I found the answer. Since I had a media element open (play/paused) and I was implementing the "non tombstoned" method of hitting windows key and back button very quickly, the media element source was corrupt. Even though I reset this source, apparently it can be ignored and not function properly. All I had to do was add a line of code to the Application Deactivated handler.
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
App.MainAudioPlayer.Source = null; //(only showing line added)
}
The behavior you are describing seems to be solely related to the way you are manipulating data internally and constructing your layout. I tested this both in the emulator and on a couple of physical devices, both producing normal output (even when bound to a view model).
Try creating a new Pivot-based application (without all your data - just using the default template) and see if the problem persists. Also worth mentioning - are you testing on a device or in the emulator?
Are you using transitions from the toolkit?
Are they defined in XAML?
If so that could be the issue. There's a bug which is fixed in the next version.
The solution for now is to remove the transitions or define them in code.

Resources