Related
Background
I am writing a WPF application using the MVVM pattern. I am using a Messenger to communicate between ViewModels as I learned in various tutorials. I am using the implementation of a Messenger class found in the Code section of this post (thanks to #Dalstroem WPF MVVM communication between View Model and Gill Cleeren at Pluralsight).
Due to the large number of Views/VMs needed by my app, each ViewModel is instantiated at the time a View is required and disposed subsequently (view-first, VM specified as DataContext of View).
Issue
The constructor of each ViewModel loads resources (Commands, Services, etc.) as necessary, and registers for messages of interest. Messages that were sent from a previously existing ViewModels are not picked up by new ViewModels.
Thus, I cannot communicate between ViewModels using my Messenger class.
Thoughts
Some examples I've seen use a ViewModelLocator that instantiates all ViewModels upfront. The Views, when created, simply pull the existing ViewModel from the VML. This approach means that Messages will always be received and available in every ViewModel. My concern is that with 30+ ViewModels that all load a substantial amount of data with use, my app will become slow with extended use as each View is used (no resources ever disposed).
I've considered finding a way to store Messages and subsequently resend all messages to any registered recipients. If implemented, this would allow me to call a Resend method of sorts after registering for messages in each ViewModel. I have a few concerns with this approach, including the accumulation of messages over time.
I'm not sure what I'm doing wrong or if there are approachs I just don't know about.
Code
public class Messenger
{
private static readonly object CreationLock = new object();
private static readonly ConcurrentDictionary<MessengerKey, object> Dictionary = new ConcurrentDictionary<MessengerKey, object>();
#region Default property
private static Messenger _instance;
/// <summary>
/// Gets the single instance of the Messenger.
/// </summary>
public static Messenger Default
{
get
{
if (_instance == null)
{
lock (CreationLock)
{
if (_instance == null)
{
_instance = new Messenger();
}
}
}
return _instance;
}
}
#endregion
/// <summary>
/// Initializes a new instance of the Messenger class.
/// </summary>
private Messenger()
{
}
/// <summary>
/// Registers a recipient for a type of message T. The action parameter will be executed
/// when a corresponding message is sent.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="recipient"></param>
/// <param name="action"></param>
public void Register<T>(object recipient, Action<T> action)
{
Register(recipient, action, null);
}
/// <summary>
/// Registers a recipient for a type of message T and a matching context. The action parameter will be executed
/// when a corresponding message is sent.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="recipient"></param>
/// <param name="action"></param>
/// <param name="context"></param>
public void Register<T>(object recipient, Action<T> action, object context)
{
var key = new MessengerKey(recipient, context);
Dictionary.TryAdd(key, action);
}
/// <summary>
/// Unregisters a messenger recipient completely. After this method is executed, the recipient will
/// no longer receive any messages.
/// </summary>
/// <param name="recipient"></param>
public void Unregister(object recipient)
{
Unregister(recipient, null);
}
/// <summary>
/// Unregisters a messenger recipient with a matching context completely. After this method is executed, the recipient will
/// no longer receive any messages.
/// </summary>
/// <param name="recipient"></param>
/// <param name="context"></param>
public void Unregister(object recipient, object context)
{
object action;
var key = new MessengerKey(recipient, context);
Dictionary.TryRemove(key, out action);
}
/// <summary>
/// Sends a message to registered recipients. The message will reach all recipients that are
/// registered for this message type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="message"></param>
public void Send<T>(T message)
{
Send(message, null);
}
/// <summary>
/// Sends a message to registered recipients. The message will reach all recipients that are
/// registered for this message type and matching context.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="message"></param>
/// <param name="context"></param>
public void Send<T>(T message, object context)
{
IEnumerable<KeyValuePair<MessengerKey, object>> result;
if (context == null)
{
// Get all recipients where the context is null.
result = from r in Dictionary where r.Key.Context == null select r;
}
else
{
// Get all recipients where the context is matching.
result = from r in Dictionary where r.Key.Context != null && r.Key.Context.Equals(context) select r;
}
foreach (var action in result.Select(x => x.Value).OfType<Action<T>>())
{
// Send the message to all recipients.
action(message);
}
}
protected class MessengerKey
{
public object Recipient { get; private set; }
public object Context { get; private set; }
/// <summary>
/// Initializes a new instance of the MessengerKey class.
/// </summary>
/// <param name="recipient"></param>
/// <param name="context"></param>
public MessengerKey(object recipient, object context)
{
Recipient = recipient;
Context = context;
}
/// <summary>
/// Determines whether the specified MessengerKey is equal to the current MessengerKey.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
protected bool Equals(MessengerKey other)
{
return Equals(Recipient, other.Recipient) && Equals(Context, other.Context);
}
/// <summary>
/// Determines whether the specified MessengerKey is equal to the current MessengerKey.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((MessengerKey)obj);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
unchecked
{
return ((Recipient != null ? Recipient.GetHashCode() : 0) * 397) ^ (Context != null ? Context.GetHashCode() : 0);
}
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Update
The way my application is architectured, there is a ViewModel used with my MainWindow, which serves as a sort of basic shell. It provides a primary layout with a few controls for navigation and login/logout, etc.
All subsequent Views are displayed inside a ContentControl inside the MainWindow (taking up most of the window real estate). The ContentControl is bound to a "CurrentView" property of my "MainWindowViewModel." The MainWindowViewModel instantiates a custom Navigation service I created for the purpose of selecting and returning the appropriate View to update my "CurrentView" property.
This architecture may be unorthodox, but I wasn't sure how navigation is typically accompished without using out-the-box things like TabControl.
Idea
Building on ideas from #axlj, I could keep an ApplicationState object as a property of my "MainWindowViewModel." Using my Messenger class, I could pub an ApplicationState message whenever injecting a new View in my MainWindow. The ViewModels for each View would, of course, sub this message and gain state immediately upon creation. If any ViewModels make changes to their copy of ApplicationState, they would pub a message. The MainWindowViewModel would then be updated via its subscription.
I would recommend against "storing messages" -- even if you work out a good pattern for recovering messages, you'll still end up with logic that is difficult to test. This is really a sign that your view models need to know too much about the application state.
In the case of view model locator -- a well designed view model locator will likely lazy-load the view models, which would leave you in the same place you are right now.
Option 1
Instead, consider using UserControls and DependencyProperties where possible.
Option 2
If your views are in fact really views, then consider a singleton context class that maintains the necessary state and inject that into your view models. The benefit of this method is that your context class can implement INotifyPropertyChanged and any changes will automatically be propagated to your consuming views.
Option 3
If you're navigating between views, you may want to implement a Navigation service similar to something described here.
interface INavigationService(string location, object parameter) {}
In this case, your parameter is considered your state object. The new view model receives the model data from the view you're navigating away from.
This blog post is helpful in explaining best practices around when to use view models and user controls.
...and registers for messages of interest. Messages that were sent from a previously existing ViewModels are not picked up by new ViewModels. Thus, I cannot communicate between ViewModels using my Messenger class.
Why exactly do your VMs need to be aware of historical messages?
Generally messaging should be pub/sub; messages are published ("pub") and anyone who might be interested in specific messages subscribes ("sub") to receive those. The publisher shouldn't care what is done with the message - that is up to the subscriber.
If you have some obscure business case that requires knowledge of previous messages then you should create your own message queue mechanism (i.e. store them in a database and retrieve them based on datetime).
***Just for learning purpose***
Recently I just knew the word cache and cache mechanism and generally understand that the cache mechanism is a good thing on system responding performance and reduce many interacting with database.
And based on the talking with someone else, they told me the general idea that we can create an independent library and cache the data retrieving from database and once we need it in our business layer, then we can retrieve it from the cache layer.
And they also shared something but not very detailed that the database can update the cache layer automatically when the data in database refreshed, like updating, adding and deleting.
So my questions comes, how does database know and update cache layer proactively and automatically? Can anybody share something with me? or are there any existing frameworks, open source solutions?
I would much appreciate for your kindly help. I'm looking forward to hearing from you my friend.
Try this third party cache: CacheCrow, it is a simple LFU based cache.
Install using powershell command in visual studio: Install-Package CacheCrow
Code Snippet:
// initialization of singleton class
ICacheCrow<string, string> cache = CacheCrow<string, string>.Initialize(1000);
// adding value to cache
cache.Add("#12","Jack");
// searching value in cache
var flag = cache.LookUp("#12");
if(flag)
{
Console.WriteLine("Found");
}
// removing value
var value = cache.Remove("#12");
For more information you can visit: https://github.com/RishabKumar/CacheCrow
Jacob,
Let me give you an example...
In the data layer when we are going to retrieve a list of objects that should be cached from the database we could to something like this.
if (!CacheHelper.Get("AllRoles", out entities))
{
var items = _context.Set<Roles>().ToList();
entities = items;
var cachableEntities = entities.ToList();
CacheHelper.Add(cachableEntities, "AllRoles");
}
return entities;
You'll notice that I have Cache helper that will search the cache for the key "AllRoles" if it finds the cache it will return the entities from the cache. If it cant find it it will get the data from the database and Create the cache with the key.
Additionally, every time we add/delete/or change an item in this table we could simple destroy this cache.
CacheHelper.Clear(CacheKey);
So answering the question, in this sample the database doesn't know when to recreate the cache, the application logic does.
Here a sample of a Cache Helpers you may use....
using System;
using System.Collections.Generic;
using System.Web;
namespace Core.Helpers
{
public static class CacheHelper
{
public static List<string> GetCacheKeys()
{
List<string> keys = new List<string>();
// retrieve application Cache enumerator
var enumerator = System.Web.HttpRuntime.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
keys.Add(enumerator.Key.ToString());
}
return keys;
}
/// <summary>
/// Insert value into the cache using
/// appropriate name/value pairs
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="o">Item to be cached</param>
/// <param name="key">Name of item</param>
public static void Add<T>(T o, string key)
{
// NOTE: Apply expiration parameters as you see fit.
// I typically pull from configuration file.
// In this example, I want an absolute
// timeout so changes will always be reflected
// at that time. Hence, the NoSlidingExpiration.
if (HttpContext.Current != null)
HttpContext.Current.Cache.Insert(
key,
o,
null,
DateTime.Now.AddMinutes(1440),
System.Web.Caching.Cache.NoSlidingExpiration);
}
/// <summary>
/// Remove item from cache
/// </summary>
/// <param name="key">Name of cached item</param>
public static void Clear(string key)
{
if (HttpContext.Current != null)
HttpContext.Current.Cache.Remove(key);
}
/// <summary>
/// Check for item in cache
/// </summary>
/// <param name="key">Name of cached item</param>
/// <returns></returns>
public static bool Exists(string key)
{
var exists= HttpContext.Current != null && HttpContext.Current.Cache[key] != null;
return exists;
}
/// <summary>
/// Retrieve cached item
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="key">Name of cached item</param>
/// <param name="value">Cached value. Default(T) if
/// item doesn't exist.</param>
/// <returns>Cached item as type</returns>
public static bool Get<T>(string key, out T value)
{
try
{
if (!Exists(key))
{
value = default(T);
return false;
}
value = (T)HttpContext.Current.Cache[key];
}
catch
{
value = default(T);
return false;
}
return true;
}
}
}
I'm developing Window Forms project with Entity Framework 6.0. I apply Database-first approach and create edmx file by using Visual Studio Wizards. Like all others, I also produce pre-generated view to improve performance. I used Entity Framework Power Tools. It works and produce my_EF.views.cs file.
But my first query still take long time.
I doubt that my project file structure might be the problem. In my solution explorer, I have two projects "MyApp.GUI" (Windows Form Project) and "MyApp.DataAccess" (Class Library Project). I add reference dll of "MyApp.DataAccess" to "MyApp.GUI".
My Entity Framework edmx file is located in "MyApp.DataAccess" project. I don't know where to put my pre-generated view file whether in "MyApp.DataAccess" class library or "MyApp.GUI" windows form project. Currently the pre-generated view file is in "MyApp.DataAccess" class library.
Does my problem associated with my project file structure ? Or, may be the pre-generated view file does not work (produced by Entity Framework Power Tools) ? This is my pre-generated view file. Please suggest me possible solutions.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Data.Entity.Infrastructure.MappingViews;
[assembly: DbMappingViewCacheTypeAttribute(
typeof(TheWayPointOfSale.DataAccess.TheWayPOSEntities),
typeof(Edm_EntityMappingGeneratedViews.ViewsForBaseEntitySetsa6f884d523752b7a79e1bab1a97ba058ffdac6b45a04cc850e30f503a4e1fc49))]
namespace Edm_EntityMappingGeneratedViews
{
using System;
using System.CodeDom.Compiler;
using System.Data.Entity.Core.Metadata.Edm;
/// <summary>
/// Implements a mapping view cache.
/// </summary>
[GeneratedCode("Entity Framework Power Tools", "0.9.0.0")]
internal sealed class ViewsForBaseEntitySetsa6f884d523752b7a79e1bab1a97ba058ffdac6b45a04cc850e30f503a4e1fc49 : DbMappingViewCache
{
/// <summary>
/// Gets a hash value computed over the mapping closure.
/// </summary>
public override string MappingHashValue
{
get { return "a6f884d523752b7a79e1bab1a97ba058ffdac6b45a04cc850e30f503a4e1fc49"; }
}
/// <summary>
/// Gets a view corresponding to the specified extent.
/// </summary>
/// <param name="extent">The extent.</param>
/// <returns>The mapping view, or null if the extent is not associated with a mapping view.</returns>
public override DbMappingView GetView(EntitySetBase extent)
{
if (extent == null)
{
throw new ArgumentNullException("extent");
}
var extentName = extent.EntityContainer.Name + "." + extent.Name;
if (extentName == "TheWayPOSModelStoreContainer.Products")
{
return GetView0();
}
if (extentName == "TheWayPOSModelStoreContainer.Um")
{
return GetView1();
}
if (extentName == "TheWayPOSModelStoreContainer.Products_Um")
{
return GetView2();
}
if (extentName == "TheWayPOSEntities.Products")
{
return GetView3();
}
if (extentName == "TheWayPOSEntities.Ums")
{
return GetView4();
}
if (extentName == "TheWayPOSEntities.Products_Um")
{
return GetView5();
}
return null;
}
/// <summary>
/// Gets the view for TheWayPOSModelStoreContainer.Products.
/// </summary>
/// <returns>The mapping view.</returns>
private static DbMappingView GetView0()
{
return new DbMappingView(#"
SELECT VALUE -- Constructing Products
[TheWayPOSModel.Store.Products](T1.[Products.product_code], T1.[Products.product_name], T1.[Products.buying_price], T1.[Products.discount_percentage], T1.[Products.retail_price], T1.[Products.wholesale_price], T1.Products_supplier, T1.[Products.created_at], T1.[Products.updated_at])
FROM (
SELECT
T.product_code AS [Products.product_code],
T.product_name AS [Products.product_name],
T.buying_price AS [Products.buying_price],
T.discount_percentage AS [Products.discount_percentage],
T.retail_price AS [Products.retail_price],
T.wholesale_price AS [Products.wholesale_price],
T.supplier AS Products_supplier,
T.created_at AS [Products.created_at],
T.updated_at AS [Products.updated_at],
True AS _from0
FROM TheWayPOSEntities.Products AS T
) AS T1");
}
/// <summary>
/// Gets the view for TheWayPOSModelStoreContainer.Um.
/// </summary>
/// <returns>The mapping view.</returns>
private static DbMappingView GetView1()
{
return new DbMappingView(#"
SELECT VALUE -- Constructing Um
[TheWayPOSModel.Store.Um](T1.[Um.um_code], T1.[Um.um_shortname], T1.[Um.um_fullname], T1.Um_disposable, T1.[Um.disposed_um_code], T1.[Um.disposed_um_qty], T1.[Um.depend_on_product], T1.[Um.created_at], T1.[Um.updated_at])
FROM (
SELECT
T.um_code AS [Um.um_code],
T.um_shortname AS [Um.um_shortname],
T.um_fullname AS [Um.um_fullname],
T.disposable AS Um_disposable,
T.disposed_um_code AS [Um.disposed_um_code],
T.disposed_um_qty AS [Um.disposed_um_qty],
T.depend_on_product AS [Um.depend_on_product],
T.created_at AS [Um.created_at],
T.updated_at AS [Um.updated_at],
True AS _from0
FROM TheWayPOSEntities.Ums AS T
) AS T1");
}
/// <summary>
/// Gets the view for TheWayPOSModelStoreContainer.Products_Um.
/// </summary>
/// <returns>The mapping view.</returns>
private static DbMappingView GetView2()
{
return new DbMappingView(#"
SELECT VALUE -- Constructing Products_Um
[TheWayPOSModel.Store.Products_Um](T1.[Products_Um.id], T1.[Products_Um.product_code], T1.[Products_Um.um_code], T1.[Products_Um.disposed_um_code], T1.[Products_Um.disposed_um_qty])
FROM (
SELECT
T.id AS [Products_Um.id],
T.product_code AS [Products_Um.product_code],
T.um_code AS [Products_Um.um_code],
T.disposed_um_code AS [Products_Um.disposed_um_code],
T.disposed_um_qty AS [Products_Um.disposed_um_qty],
True AS _from0
FROM TheWayPOSEntities.Products_Um AS T
) AS T1");
}
/// <summary>
/// Gets the view for TheWayPOSEntities.Products.
/// </summary>
/// <returns>The mapping view.</returns>
private static DbMappingView GetView3()
{
return new DbMappingView(#"
SELECT VALUE -- Constructing Products
[TheWayPOSModel.Product](T1.[Product.product_code], T1.[Product.product_name], T1.[Product.buying_price], T1.[Product.discount_percentage], T1.[Product.retail_price], T1.[Product.wholesale_price], T1.Product_supplier, T1.[Product.created_at], T1.[Product.updated_at])
FROM (
SELECT
T.product_code AS [Product.product_code],
T.product_name AS [Product.product_name],
T.buying_price AS [Product.buying_price],
T.discount_percentage AS [Product.discount_percentage],
T.retail_price AS [Product.retail_price],
T.wholesale_price AS [Product.wholesale_price],
T.supplier AS Product_supplier,
T.created_at AS [Product.created_at],
T.updated_at AS [Product.updated_at],
True AS _from0
FROM TheWayPOSModelStoreContainer.Products AS T
) AS T1");
}
/// <summary>
/// Gets the view for TheWayPOSEntities.Ums.
/// </summary>
/// <returns>The mapping view.</returns>
private static DbMappingView GetView4()
{
return new DbMappingView(#"
SELECT VALUE -- Constructing Ums
[TheWayPOSModel.Um](T1.[Um.um_code], T1.[Um.um_shortname], T1.[Um.um_fullname], T1.Um_disposable, T1.[Um.disposed_um_code], T1.[Um.disposed_um_qty], T1.[Um.depend_on_product], T1.[Um.created_at], T1.[Um.updated_at])
FROM (
SELECT
T.um_code AS [Um.um_code],
T.um_shortname AS [Um.um_shortname],
T.um_fullname AS [Um.um_fullname],
T.disposable AS Um_disposable,
T.disposed_um_code AS [Um.disposed_um_code],
T.disposed_um_qty AS [Um.disposed_um_qty],
T.depend_on_product AS [Um.depend_on_product],
T.created_at AS [Um.created_at],
T.updated_at AS [Um.updated_at],
True AS _from0
FROM TheWayPOSModelStoreContainer.Um AS T
) AS T1");
}
/// <summary>
/// Gets the view for TheWayPOSEntities.Products_Um.
/// </summary>
/// <returns>The mapping view.</returns>
private static DbMappingView GetView5()
{
return new DbMappingView(#"
SELECT VALUE -- Constructing Products_Um
[TheWayPOSModel.Products_Um](T1.[Products_Um.id], T1.[Products_Um.product_code], T1.[Products_Um.um_code], T1.[Products_Um.disposed_um_code], T1.[Products_Um.disposed_um_qty])
FROM (
SELECT
T.id AS [Products_Um.id],
T.product_code AS [Products_Um.product_code],
T.um_code AS [Products_Um.um_code],
T.disposed_um_code AS [Products_Um.disposed_um_code],
T.disposed_um_qty AS [Products_Um.disposed_um_qty],
True AS _from0
FROM TheWayPOSModelStoreContainer.Products_Um AS T
) AS T1");
}
}
}
I know this information is not worth to be an answer. But for other newbies like me, I would like to share my experience.
According to Maarten's comment, I have put breakpoints in each of the pre-generated view files. The pre-generated view in DataAccess class library is hit by the breakpoint. So, it can be generally assume to place the pre-generated view file in DataAccess class library where edmx file is located (in my kinds of situations).
This is the line that the error is showing on:
public IOAuth2ServiceProvider<IElance> ElanceServiceProvider { get; set; }
It's showing the error on the IElance Type on that line, but here's the interface:
public interface IElance : IApiBinding
{
/// <summary>
/// Search all jobs, list jobs associated with an employee or a freelancer, and retrieve information for a specific job.
/// </summary>
IJobOperations JobOperations { get; }
/// <summary>
/// Access all messages, users, messages, and Work View™ data associated with an Elance Workroom.
/// </summary>
IWorkRoomOperations WorkroomOperations { get; }
/// <summary>
/// View all of the information associated with an employee or a freelancer.
/// </summary>
IProfileOperations ProfileOperations { get; }
/// <summary>
/// View detailed information on freelancers, and retrieve a list of all freelancers employed by an employer.
/// </summary>
IFreelancerOperations FreelancerOperations { get; }
/// <summary>
/// List Elance groups, and retrieve lists of members and jobs belonging to a group.
/// </summary>
IGroupOperations GroupOperations { get; }
/// <summary>
/// Obtain ancillary Elance information, such as the current list of all job categories.
/// </summary>
IUtilityOperations UtilityOperations { get; }
}
I can't for the life of me figure out why it's telling me this. Am I missing something obvious? I would greatly appreciate any direction on this error.
This is probably caused by IApiBinding or one of its base interfaces not being public. Another possibility is that one of the types used by the interface members is not public.
What cool functionality and methods do you add to your ASP.net BasePage : System.Web.UI.Page classes?
Examples
Here's something I use for authentication, and I'd like to hear your opinions on this:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
// Authentication code omitted... Essentially same as below.
if (_RequiresAuthentication && !(IsAuthorized))
{
RespondForbidden("You do not have permissions to view this page.", UnauthorizedRedirect);
return;
}
}
// This function is overridden in each page subclass and fitted to each page's
// own authorization requirements.
// This also allows cascading authorization checks,
// e.g: User has permission to view page? No - base.IsAuthorized - Is user an admin?
protected virtual bool IsAuthorized
{
get { return true; }
}
My BasePage class contains an instance of this class:
public class StatusCodeResponse {
public StatusCodeResponse(HttpContext context) {
this._context = context;
}
/// <summary>
/// Responds with a specified status code, and if specified - transfers to a page.
/// </summary>
private void RespondStatusCode(HttpContext context, System.Net.HttpStatusCode status, string message, string transfer)
{
if (string.IsNullOrEmpty(transfer))
{
throw new HttpException((int)status, message);
}
context.Response.StatusCode = (int)status;
context.Response.StatusDescription = message;
context.Server.Transfer(transfer);
}
public void RespondForbidden(string message, string transfer)
{
RespondStatusCode(this._context, System.Net.HttpStatusCode.Forbidden, message, transfer);
}
// And a few more like these...
}
As a side note, this could be accomplished using extension methods for the HttpResponse object.
And another method I find quite handy for parsing querystring int arguments:
public bool ParseId(string field, out int result)
{
return (int.TryParse(Request.QueryString[field], out result) && result > 0);
}
Session related stuff, some complex object in the BasePage that maps to a session, and expose it as a property.
Doing stuff like filling a crumble pad object.
But most important: do not make your basepage into some helper class. Don't add stuff like ParseId(), that's just ridiculous.
Also, based on the first post: make stuff like IsAuthorized abstract. This way you don't create giant security holes if someone forgets that there is some virtual method.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace MySite
{
/// <summary>
/// Base class with properties for meta tags for content pages
/// http://www.codeproject.com/KB/aspnet/PageTags.aspx
/// http://weblogs.asp.net/scottgu/archive/2005/08/02/421405.aspx
/// </summary>
public partial class BasePage : System.Web.UI.Page
{
private string keywords;
private string description;
/// <SUMMARY>
/// Gets or sets the Meta Keywords tag for the page
/// </SUMMARY>
public string Meta_Keywords
{
get
{
return keywords;
}
set
{
// Strip out any excessive white-space, newlines and linefeeds
keywords = Regex.Replace(value, "\\s+", " ");
}
}
/// <SUMMARY>
/// Gets or sets the Meta Description tag for the page
/// </SUMMARY>
public string Meta_Description
{
get
{
return description;
}
set
{
// Strip out any excessive white-space, newlines and linefeeds
description = Regex.Replace(value, "\\s+", " ");
}
}
// Constructor
// Add an event handler to Init event for the control
// so we can execute code when a server control (page)
// that inherits from this base class is initialized.
public BasePage()
{
Init += new EventHandler(BasePage_Init);
}
// Whenever a page that uses this base class is initialized,
// add meta keywords and descriptions if available
void BasePage_Init(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(Meta_Keywords))
{
HtmlMeta tag = new HtmlMeta();
tag.Name = "keywords";
tag.Content = Meta_Keywords;
Header.Controls.Add(tag);
}
if (!String.IsNullOrEmpty(Meta_Description))
{
HtmlMeta tag = new HtmlMeta();
tag.Name = "description";
tag.Content = Meta_Description;
Header.Controls.Add(tag);
}
}
}
}
Along with the metadata already mentioned (mostly obsolete in ASP.NET 4.0 with the new Page.MetaDescription and Page.MetaKeywords properties), I've also had methods to add other header links to my page such as specific ones for adding page specific CSS, or things like cannonical links, RSS links, etc:
/// <overloads>
/// Adds a CSS link to the page. Useful when you don't have access to the
/// HeadContent ContentPlaceHolder. This method has 4 overloads.
/// </overloads>
/// <summary>
/// Adds a CSS link.
/// </summary>
/// <param name="pathToCss">The path to CSS file.</param>
public void AddCss(string pathToCss) {
AddCss(pathToCss, string.Empty);
}
/// <summary>
/// Adds a CSS link in a specific position.
/// </summary>
/// <param name="pathToCss">The path to CSS.</param>
/// <param name="position">The postion.</param>
public void AddCss(string pathToCss, int? position) {
AddCss(pathToCss, string.Empty, position);
}
/// <summary>
/// Adds a CSS link to the page with a specific media type.
/// </summary>
/// <param name="pathToCss">The path to CSS file.</param>
/// <param name="media">The media type this stylesheet relates to.</param>
public void AddCss(string pathToCss, string media) {
AddHeaderLink(pathToCss, "text/css", "Stylesheet", media, null);
}
/// <summary>
/// Adds a CSS link to the page with a specific media type in a specific
/// position.
/// </summary>
/// <param name="pathToCss">The path to CSS.</param>
/// <param name="media">The media.</param>
/// <param name="position">The postion.</param>
public void AddCss(string pathToCss, string media, int? position) {
AddHeaderLink(pathToCss, "text/css", "Stylesheet", media, position);
}
/// <overloads>
/// Adds a general header link. Useful when you don't have access to the
/// HeadContent ContentPlaceHolder. This method has 3 overloads.
/// </overloads>
/// <summary>
/// Adds a general header link.
/// </summary>
/// <param name="href">The path to the resource.</param>
/// <param name="type">The type of the resource.</param>
public void AddHeaderLink(string href, string type) {
AddHeaderLink(href, type, string.Empty, string.Empty, null);
}
/// <summary>
/// Adds a general header link.
/// </summary>
/// <param name="href">The path to the resource.</param>
/// <param name="type">The type of the resource.</param>
/// <param name="rel">The relation of the resource to the page.</param>
public void AddHeaderLink(string href, string type, string rel) {
AddHeaderLink(href, type, rel, string.Empty, null);
}
/// <summary>
/// Adds a general header link.
/// </summary>
/// <param name="href">The path to the resource.</param>
/// <param name="type">The type of the resource.</param>
/// <param name="rel">The relation of the resource to the page.</param>
/// <param name="media">The media target of the link.</param>
public void AddHeaderLink(string href, string type, string rel, string media)
{
AddHeaderLink(href, type, rel, media, null);
}
/// <summary>
/// Adds a general header link.
/// </summary>
/// <param name="href">The path to the resource.</param>
/// <param name="type">The type of the resource.</param>
/// <param name="rel">The relation of the resource to the page.</param>
/// <param name="media">The media target of the link.</param>
/// <param name="position">The postion in the control order - leave as null
/// to append to the end.</param>
public void AddHeaderLink(string href, string type, string rel, string media,
int? position) {
var link = new HtmlLink { Href = href };
if (0 != type.Length) {
link.Attributes.Add(HtmlTextWriterAttribute.Type.ToString().ToLower(),
type);
}
if (0 != rel.Length) {
link.Attributes.Add(HtmlTextWriterAttribute.Rel.ToString().ToLower(),
rel);
}
if (0 != media.Length) {
link.Attributes.Add("media", media);
}
if (null == position || -1 == position) {
Page.Header.Controls.Add(link);
}
else
{
Page.Header.Controls.AddAt((int)position, link);
}
}
Culture initialization by overriding InitializeCulture() method (set culture and ui culture from cookie or DB).
Some of my applications are brandable, then here I do some "branding" stuff too.
I use this methot and thanks for yours,
/// <summary>
/// Displays the alert.
/// </summary>
/// <param name="message">The message to display.</param>
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');", message.Replace("'", #"\'")),
true
);
}
/// <summary>
/// Finds the control recursive.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>control</returns>
protected virtual Control FindControlRecursive(string id)
{
return FindControlRecursive(id, this);
}
/// <summary>
/// Finds the control recursive.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="parent">The parent.</param>
/// <returns>control</returns>
protected virtual Control FindControlRecursive(string id, Control parent)
{
if (string.Compare(parent.ID, id, true) == 0)
return parent;
foreach (Control child in parent.Controls)
{
Control match = FindControlRecursive(id, child);
if (match != null)
return match;
}
return null;
}
Putting authorization code in a base page is generally not a good idea. The problem is, what happens if you forget to derive a page that needs authorization from the base page? You will have a security hole.
It's much better to use an HttpModule, so that you can intercept requests for all pages, and make sure users are authorized even before the HttpHandler has a chance to run.
Also, as others have said, and in keeping with OO principles, it's better to only have methods in your base page that actually relate to the Page itself. If they don't reference "this," they should probably be in a helper class -- or perhaps be extension methods.
I inherit from System.Web.UI.Page when I need certain properties and every page. This is good for aweb application that implements a login. In the membership pages I use my own base class to get access to Properties like UserID, UserName etc. These properties wrap Session Variables
Here are some examples (sans code) that I use a custom base class for:
Adding a page filter (e.g. replace "{theme}" with "~/App_Theme/[currentTheme]"),
Adding a Property and handling for Auto Titling pages based upon Site Map,
Registering specialized logging (could probably be redone via different means),
Adding methods for generalized input(Form/Querystring) validation, with blanket redirector: AddRequiredInput("WidgetID", PageInputType.QueryString, typeof(string)),
Site Map Helpers, allowing for things like changing a static "Edit Class" into something context related like "Edit Fall '10 Science 101"
ViewState Helpers, allowing me to register variable on the page to a name and have it automatically populate that variable from the viewstate or a default, and save the value back out to the viewstate at the end of the request.
Custom 404 Redirector, where I can pass an exception or message (or both) and it will go to a page I have predefined to nicely display and log it.
I personally like #5 the most because a) updating the SiteMap is ugly and I prefer not to have clutter the page, making it more readable, b) It makes the SiteMap much more user friendly.
,
Please refer Getting page specific info in ASP.Net Base Page
public abstract string AppSettingsRolesName { get; }
List<string> authorizedRoles = new List<string>((ConfigurationManager.AppSettings[AppSettingsRolesName]).Split(','))
if (!authorizedRoles.Contains(userRole))
{
Response.Redirect("UnauthorizedPage.aspx");
}
In derived Page
public override string AppSettingsRolesName
{
get { return "LogsScreenRoles"; }
}