Resharper suggestion Page_Load = PageLoad - naming-conventions

Usually when the Page_Load event handler is added to a codebehind file by Visual Studio (e.g. double clicking the page in designer mode), it ends up looking like this:
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Page_Load(object sender, EventArgs e)
{
// ...
}
But Resharper suggests Name 'Page_Load' does not match rule 'Methods, properties and events'. Suggested name is 'PageLoad'. I'm guessing there's a better way to define the handler for page load, but I can't remember what the syntax is, but I imagine it would resolve this Resharper warning?
Perhaps something like:
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// ...
}
but I seem to recall that OnLoad and PageLoad aren't exactly the same?

Just for completeness I thought I would add here the answer you got from one "David Benson" when you asked on jetbrains.net:
If you go to ReSharper Options, under Languages select C# Naming Style. Select the Advanced settings... button and in the Event subscriptions on fields:, remove the On in front of $event$ so it is $object$_$event$. That should remove the warning.
For me this is the easiest way of placating ReSharper in the face of a large existing web application codebase.

OnLoad and Page_Load are essentially the same. Page_Load is invoked via reflection if AutoEventWireup is enabled on the Page. OnLoad is a protected virtual method of the Control class (which the Page class inherits).
See Inside AutoEventWireup for an in-depth analysis of how AutoEventWireup works and why it exists.
The StackOverflow community also has some input on whether it is better to handle the Load event or override the OnLoad method.

It's a bug in ReSharper 6.0 and lower. In 6.1 it's fixed.
For AutoEventWireup handlers it will not suggest any changes doesn't matter which naming settings you have.

Related

XBF Error with DataTemplate in Application.Resources

Universal Windows Platform app with Visual Studio 2015 (RTM)
I have a DataTemplate that is used in multiple pages of my app, so I'd prefer to write it once and access it from anywhere I need to. In order to make it accessible by any page, I write it in my App.xaml's <Application.Resources>:
<Application
x:Class="MyApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyApp"
xmlns:viewmodels="using:MyApp.ViewModels"
RequestedTheme="Light">
<Application.Resources>
<DataTemplate x:Key="DetailContentTemplate" x:DataType="viewmodels:DataViewModel">
...
</DataTemplate>
</Application.Resources>
The DataTemplate portion of the code above works just fine in an individual page, but of course that means I'd have to copy and paste it multiple times to other pages, which just isn't efficient. However, I get this error when I use the DataTemplate in App.xaml:
XBF generation error code 0x09c4
I've determined that it stems from the x:DataType="viewmodels:DataViewModel" (without this, and hence, without any bindings the code works just fine). Looking up the error results in next to nothing. Is there a convenient workaround/solution to being able to reuse a DataTemplate with bindings in a Universal Windows Platform/WinRT app, preferably in XAML?
EDIT: As requested, the code in full for App.xaml.cs:
namespace MyApp
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Allows tracking page views, exceptions and other telemetry through the Microsoft Application Insights service.
/// </summary>
public static Microsoft.ApplicationInsights.TelemetryClient TelemetryClient;
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
// Set the default language
rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
rootFrame.NavigationFailed += OnNavigationFailed;
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MasterDetailPage));
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
You can find some explanation here from the latest build session at 20:10
You basically need to create a resource dictionary in XAML and attach a class to it. This class file is needed to allow the compiler to generate its code.
Depending on what you have to do and how you can change your code, you can still use the "old" {Binding} markup which will work as before.
<Application.Resources>
<DataTemplate x:Key="DetailContentTemplate">
<TextBlock Text={Binding myValue} />
</DataTemplate>
</Application.Resources>

Exception handling in asp.net mvc view

I am handing exception in Controller, and other layers that I have manually added like DataAccess.
I have also placed exception handling in Views.
Is it necessary to do so, or can I remove the exception handling code from view?
This is not necessary, ASP.NET haves exception handling by itself. You only have to throw a exception. The view will catch it automatically when running on 'release' mode
Just add the 'FilterConfig' in your App_start
public class FilterConfig
{
/// <summary>
/// The register global filters.
/// </summary>
/// <param name="filters">
/// The filters.
/// </param>
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}

User customizable validation with metadata saved in a database

I'm working on an application which should validate the model based on some metadata saved in a database. The purpose of this is to allow administrators change how some models are validated, without changing the code, depending on clients' preferences. The changes are applied for the entire application, not for specific users accessing it. How it is changed, doesn't matter at the moment. They could be modified directly on the database, or using an application. The idea is that they should be customizable.
Let's say i have the model "Person" with the property "Name" of type "string".
public class Person
{
public string Name { get; set; }
}
This model is used by my app which is distributed and istalled on several servers. Each of them is independent. Some users may want the Name to have maximum 30 letters and to be required when creating a new "Person", others may want it to have 25 and not to be required. Normally, this would be solved using data annotations, but those are evaluated during the compile time and are somehow "hardcoded".
Shortly, I want to find a way to customize and store in a database how the model validates, without the need of altering the application code.
Also, it would be nice to work with jquery validation and have as few request to database(/service) as possible. Besides that, i can't use any known ORM like EF.
You could create a custom validation attribute that validates by examining the metadata stored in the database. Custom validation attributes are easy to create, simply extend System.ComponentModel.DataAnnotations.ValidationAttribute and override the IsValid() method.
To get the client side rules that work with jQuery validation you will need to create a custom adapter for the type of your custom validation attribute that extends System.Web.Mvc.DataAnnotationsModelValidator<YourCustomValidationAttribute>. This class then needs to be registered in the OnApplicationStart() method of your Global.asax.
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(YourCustomValidationAttribute), typeof(YourCustomAdapter));
Here's an example adapter:
public class FooAdapter : DataAnnotationsModelValidator<FooAttribute>
{
/// <summary>
/// This constructor is used by the MVC framework to retrieve the client validation rules for the attribute
/// type associated with this adapter.
/// </summary>
/// <param name="metadata">Information about the type being validated.</param>
/// <param name="context">The ControllerContext for the controller handling the request.</param>
/// <param name="attribute">The attribute associated with this adapter.</param>
public FooAdapter(ModelMetadata metadata, ControllerContext context, FooAttribute attribute)
: base(metadata, context, attribute)
{
_metadata = metadata;
}
/// <summary>
/// Overrides the definition in System.Web.Mvc.ModelValidator to provide the client validation rules specific
/// to this type.
/// </summary>
/// <returns>The set of rules that will be used for client side validation.</returns>
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return new[] { new ModelClientValidationRequiredRule(
String.Format("The {0} field is invalid.", _metadata.DisplayName ?? _metadata.PropertyName)) };
}
/// <summary>
/// The metadata associated with the property tagged by the validation attribute.
/// </summary>
private ModelMetadata _metadata;
}
This may also be useful if you would like to asynchronously call server side validation http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute(v=vs.108).aspx

Web Service nHibernate SessionFactory issue

I have a C# .Net Web Service. I am calling a dll (C# .Net) that uses nHibernate to connect to my database. When I call the dll, it executes a query to the db and loads the parent Object "Task". However, when the dll tries to access the child objects "Task.SubTasks", it throws the following error:
NHibernate.HibernateException failed to lazily initialize a collection of role: SubTasks no session or session was closed
I'm new to nHibernate so not sure what piece of code I'm missing.
Do I need to start a Factory session in my web service before calling the dll? If so, how do I do that?
EDIT: Added the web service code and the CreateContainer() method code. This code gets called just prior to calling the dll
[WebMethod]
public byte[] GetTaskSubtask (string subtaskId)
{
var container = CreateContainer(windsorPath);
IoC.Initialize(container);
//DLL CALL
byte[] theDoc = CommonExport.GetSubtaskDocument(subtaskId);
return theDoc;
}
/// <summary>
/// Register the IoC container.
/// </summary>
/// <param name="aWindsorConfig">The path to the windsor configuration
/// file.</param>
/// <returns>An initialized container.</returns>
protected override IWindsorContainer CreateContainer(
string aWindsorConfig)
{
//This method is a workaround. This method should not be overridden.
//This method is overridden because the CreateContainer(string) method
//in UnitOfWorkApplication instantiates a RhinoContainer instance that
//has a dependency on Binsor. At the time of writing this the Mammoth
//application did not have the libraries needed to resolve the Binsor
//dependency.
IWindsorContainer container = new RhinoContainer();
container.Register(
Component.For<IUnitOfWorkFactory>().ImplementedBy
<NHibernateUnitOfWorkFactory>());
return container;
}
EDIT: Adding DLL code and repository code...
DLL Code
public static byte[] GetSubtaskDocument(string subtaskId)
{
BOESubtask task = taskRepo.FindBOESubtaskById(Guid.Parse(subtaskId));
foreach(subtask st in task.Subtasks) <--this is the line that throws the error
{
//do some work
}
}
Repository for task
/// <summary>
/// Queries the database for the Subtasks whose ID matches the
/// passed in ID.
/// </summary>
/// <param name="aTaskId">The ID to find matching Subtasks
/// for.</param>
/// <returns>The Subtasks whose ID matches the passed in
/// ID (or null).</returns>
public Task FindTaskById(Guid aTaskId)
{
var task = new Task();
using (UnitOfWork.Start())
{
task = FindOne(DetachedCriteria.For<Task>()
.Add(Restrictions.Eq("Id", aTaskId)));
UnitOfWork.Current.Flush();
}
return task;
}
Repository for subtask
/// <summary>
/// Queries the database for the Subtasks whose ID matches the
/// passed in ID.
/// </summary>
/// <param name="aBOESubtaskId">The ID to find matching Subtasks
/// for.</param>
/// <returns>The Subtasks whose ID matches the passed in
/// ID (or null).</returns>
public Subtask FindBOESubtaskById(Guid aSubtaskId)
{
var subtask = new Subtask();
using (UnitOfWork.Start())
{
subtask = FindOne(DetachedCriteria.For<Subtask>()
.Add(Restrictions.Eq("Id", aSubtaskId)));
UnitOfWork.Current.Flush();
}
return subtask;
}
You have apparently mapped a collection in one of your NHibernate data classes with lazy loading enabled (or better: not disabled, as it is the default behavior). NHibernate loads the entity and creates a proxy for the mapped collections. As soon as they are accessed, NHibernate attempts to load the items for that collection. But if you close your NHibernate session before that happens, the error you received will occur. You are probably exposing your data object through your web service to the web service client. During the serialization process, the XmlSerializer tries to serialize the collection which prompts NHibernate to populate it. As the session is closed, the error occurs.
Two ways to prevent this:
close the session after the response has been sent
or
disable lazy loading for your collections so that they are loaded instantly
Addition after the above edits:
in your repository, you start UnitsOfWork within a using-statement. They are being disposed as soon as the code is completed. I don't know the implementation of UnitOfWork but i assume it controls the lifetime of the NHibernate session. By disposing the UnitOfWork, your are probalby closing the NHibernate session. As your mapping initializes collections lazy loaded, these collections are not yet populated and the error occurs. NHibernate needs the exact instance of the session that loaded an entity to populate lazily initialized collections.
You will run into problems like this if you use lazy loading and have a repository that closes the session before the response is complete. One option would be to initialize the UnitOfWork at the start of the request and close it after the response is complete (for instance in Application_BeginRequest, Application_EndRequest in Global.asax.cs). That would of course mean a close integration of your repository into the web service.
In any case, creating a Session for a single request in combination with lazy loading is a bad idea and is very likely to create similar problems in the future. If you can't change the repository implementation you might probably have to disable lazy loading.
Using Garland's feedback I resolved the issue. I removed the UnitOfWork(s) code from the repository in the DLL and wrapped the Web Service call to the DLL in a UnitOfWork See code mods below:
Web Service
[WebMethod]
public byte[] GetSubtaskDocument (string subtaskId)
{
var container = CreateContainer(windsorString);
IoC.Initialize(container);
byte[] theDoc;
using (UnitOfWork.Start())
{
//DLL call
theDoc = CommonExport.GetSubtaskDocument(subtaskId);
UnitOfWork.Current.Flush();
}
return theDoc;
}
Repository call in the DLL
public Subtask FindSubtaskById(Guid aSubtaskId)
{
return FindOne(DetachedCriteria.For<Subtask>()
.Add(Restrictions.Eq("Id", aSubtaskId)));
}

How to get full intellisense tooltip comments working?

I've got some C++/CLI software which is all nice and documented in a C#'ish kind of way which means DOxygen is able to pull it out into some nice html. Is there any way I can get that same information to appear in the intellisense tool tips the way that the .net framework does?
For example, lets say this is my header file (MyApp.h):
/*************** MyApp.h ***************/
/// My namespace containing all my funky classes
namespace MyNamespace
{
using namespace System;
ref class WorldHunger;
/// A truly elegent class which solves all the worlds problems
public ref class MyClass
{
public:
/// Constructs a MyClass
MyClass()
{
}
/// <summary>Attempts to fix world hunger</summary>
/// <param name="problem">The problem to try and fix</param>
/// <returns>Whether or not the problem was solved</param>
bool FixWorldHunger( WorldHunger^ problem );
};
}
...and this it's corresponding implementation:
/*************** MyApp.cpp ***************/
#include "MyApp.h"
using namespace MyNamespace;
MyClass::MyClass()
{
}
bool MyClass::FixWorldHunger( WorldHunger^ problem )
{
bool result = false;
/// TODO: implement something clever
return result;
}
Here's what intellisense does for built in functions when I'm typing:
http://www.geekops.co.uk/photos/0000-00-02%20%28Forum%20images%29/BrokenIntellisense1.jpg
Here's what intellisense does for my own functions when I type:
http://www.geekops.co.uk/photos/0000-00-02%20%28Forum%20images%29/BrokenIntellisense2.jpg
Surely there's a way to do this?
Just to summarise, for this to work you need your comments in a compatible form:
/// <summary>
/// Retrieves the widget at the specified index
/// </summary>
/// <param name="widgetIndex">Index of the widget to retrieve.</param>
/// <returns>The widget at the specified index</returns>
Widget* GetWidget(int widgetIndex);
Then you simply right-click on the project in Visual Studio and go to properties > configuration properties > C/C++ > Output Files and change Generate XML Documentation Files to Yes.
When you rebuild your project ad import it somewhere else, you should see fully documented tooltips appear.