public class CommentsBlogModule : IHttpModule
{
private static bool _communityStarted;
private static readonly Object _lockObject = new Object();
internal const string COMMENTS_BLOG_ATTRIBUTE_NAME =
"CommentsBlog";
public void Init(HttpApplication context)
{
context.EndRequest += EndRequest;
}
private static void EndRequest(object sender, EventArgs e)
{
if (_communityStarted)
return;
lock (_lockObject)
{
if (_communityStarted)
return;
EnsureAllEntitiesHaveAttribute();
FrameworkFactoryBase.EntityAdded +=
FrameworkFactoryBase_EntityAdded;
_communityStarted = true;
}
}
private static void EnsureAllEntitiesHaveAttribute()
{
Assembly[] assemblies =
AppDomain.CurrentDomain.GetAssemblies();
foreach(Assembly assembly in assemblies)
{
EnsureEntityTypesInAssemblyHasAttribute(assembly);
}
}
private static void EnsureEntityTypesInAssemblyHasAttribute(
Assembly assembly)
{
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
if(type.IsAbstract)
continue;
Type attributeExtendableType =
typeof (IAttributeExtendableEntity);
if(attributeExtendableType.IsAssignableFrom(type))
EnsureTypeHasAttribute(type);
}
}
private static void EnsureTypeHasAttribute(Type type)
{
IAttribute commentsBlogAttribute =
AttributeHandler.GetAttributes(type).FirstOrDefault(
attribute => attribute.Name ==
COMMENTS_BLOG_ATTRIBUTE_NAME);
if (commentsBlogAttribute == null)
{
commentsBlogAttribute =
new Attribute(COMMENTS_BLOG_ATTRIBUTE_NAME,
type, typeof(Blog), false);
AttributeHandler.AddAttribute(commentsBlogAttribute);
}
}
static void FrameworkFactoryBase_EntityAdded(
IEntityEventArgs args)
{
Type extendableType = typeof (IAttributeExtendableEntity);
Type addedEntityType = args.Entity.GetType();
if (!extendableType.IsAssignableFrom(addedEntityType))
return;
IAttributeExtendableEntity entity =
(IAttributeExtendableEntity)args.Entity;
string name = string.Format(
"Comments blog for {0} with ID {1}",
entity.GetType().Name, entity.ID);
Blog commentsBlog = new Blog(name);
commentsBlog = BlogHandler.AddBlog(commentsBlog);
entity = (IAttributeExtendableEntity)entity.Clone();
entity.SetAttributeValue(COMMENTS_BLOG_ATTRIBUTE_NAME,
commentsBlog);
FrameworkFactoryBase.UpdateEntity(entity);
}
public void Dispose() {}
}