Skip to content
Browse files

StyleCop formatting for SharpArch.Web assembly.

  • Loading branch information...
1 parent 420de7e commit 85e288615d1c73d706e0eb8682f7cfc2fd119a94 jongeorge1 committed Jul 10, 2010
View
1 Common/CommonAssemblyInfo.cs
@@ -9,4 +9,5 @@
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
+
[assembly: ComVisible(false)]
View
57 Solutions/SharpArch/SharpArch.Web/Areas/AreaViewEngine.cs
@@ -1,46 +1,37 @@
-using System.Web.Mvc;
-
-namespace SharpArch.Web.Areas
+namespace SharpArch.Web.Areas
{
+ using System.Web.Mvc;
+
/// <summary>
- /// Replacement view engine to support the organization of views into areas. Taken from the
- /// sample provided by Phil Haack at http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx.
- /// It's been modified to allow area views to sit within subfolders under /Views
+ /// Replacement view engine to support the organization of views into areas. Taken from the
+ /// sample provided by Phil Haack at http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx.
+ /// It's been modified to allow area views to sit within subfolders under /Views
/// </summary>
public class AreaViewEngine : WebFormViewEngine
{
public AreaViewEngine()
{
- MasterLocationFormats = new[] {
- "~/{0}.master",
- "~/Shared/{0}.master",
- "~/Views/{1}/{0}.master",
- "~/Views/Shared/{0}.master",
- };
+ this.MasterLocationFormats = new[]
+ {
+ "~/{0}.master", "~/Shared/{0}.master", "~/Views/{1}/{0}.master", "~/Views/Shared/{0}.master",
+ };
- AreaMasterLocationFormats = new[] {
- "~/Views/{2}/{1}/{0}.master",
- "~/Views/{2}/Shared/{0}.master",
- };
+ this.AreaMasterLocationFormats = new[] { "~/Views/{2}/{1}/{0}.master", "~/Views/{2}/Shared/{0}.master", };
- ViewLocationFormats = new[] {
- "~/{0}.aspx",
- "~/{0}.ascx",
- "~/Views/{1}/{0}.aspx",
- "~/Views/{1}/{0}.ascx",
- "~/Views/Shared/{0}.aspx",
- "~/Views/Shared/{0}.ascx",
- };
+ this.ViewLocationFormats = new[]
+ {
+ "~/{0}.aspx", "~/{0}.ascx", "~/Views/{1}/{0}.aspx", "~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.aspx",
+ "~/Views/Shared/{0}.ascx",
+ };
- AreaViewLocationFormats = new[] {
- "~/Views/{2}/{1}/{0}.aspx",
- "~/Views/{2}/{1}/{0}.ascx",
- "~/Views/{2}/Shared/{0}.aspx",
- "~/Views/{2}/Shared/{0}.ascx",
- };
+ this.AreaViewLocationFormats = new[]
+ {
+ "~/Views/{2}/{1}/{0}.aspx", "~/Views/{2}/{1}/{0}.ascx", "~/Views/{2}/Shared/{0}.aspx",
+ "~/Views/{2}/Shared/{0}.ascx",
+ };
- PartialViewLocationFormats = ViewLocationFormats;
- AreaPartialViewLocationFormats = AreaViewLocationFormats;
+ this.PartialViewLocationFormats = this.ViewLocationFormats;
+ this.AreaPartialViewLocationFormats = this.AreaViewLocationFormats;
}
}
-}
+}
View
192 Solutions/SharpArch/SharpArch.Web/Areas/LinkForAreasExtensions.cs
@@ -1,122 +1,136 @@
-using System.Web.Mvc;
-using System.Linq.Expressions;
-using System;
-using System.Web.Mvc.Html;
-using System.Web.Routing;
-using ExpressionHelper = Microsoft.Web.Mvc.Internal.ExpressionHelper;
-
-namespace SharpArch.Web.Areas
+namespace SharpArch.Web.Areas
{
+ using System;
+ using System.Linq.Expressions;
+ using System.Web.Mvc;
+
+ using ExpressionHelper = Microsoft.Web.Mvc.Internal.ExpressionHelper;
+
public static class LinkForAreasExtensions
{
/// <summary>
- /// Creates an anchor tag based on the passed in controller type and method,
- /// taking into account the area of the controller, as reflected in its namespace
+ /// Length of the string ".dll"
+ /// </summary>
+ private const int LengthOfDotDll = 4;
+
+ /// <summary>
+ /// Template to be used for the creation of area-supported links
/// </summary>
- /// <typeparam name="TController">The Controller Type</typeparam>
- /// <param name="action">The Method to route to</param>
- /// <param name="linkText">The linked text to appear on the page</param>
+ private const string LinkTemplate = "<a href=\"{0}{1}{2}{3}\">{4}</a>";
+
+ /// <summary>
+ /// Creates an anchor tag based on the passed in controller type and method,
+ /// taking into account the area of the controller, as reflected in its namespace
+ /// </summary>
+ /// <typeparam name = "TController">The Controller Type</typeparam>
+ /// <param name="helper">The HtmlHelper that the extension method applies to.</param>
+ /// <param name = "action">The Method to route to</param>
+ /// <param name = "linkText">The linked text to appear on the page</param>
/// <returns>System.String</returns>
- public static string ActionLinkForAreas<TController>(this HtmlHelper helper,
- Expression<Action<TController>> action, string linkText) where TController : Controller {
-
- Type controllerType = typeof(TController);
- string controllerUrlName = GetUrlNameEquivalentOf(controllerType);
- string areaUrl = ConvertNamespaceIntoAreaUrl(controllerType);
-
- MethodCallExpression methodCall = GetMethodCall(action);
- string actionName = methodCall.Method.Name;
- string arguments = GetQueryStringArguments(helper, action, linkText, controllerUrlName, actionName);
-
- return string.Format(linkTemplate,
- helper.ViewContext.HttpContext.Request.ApplicationPath == "/"
- ? helper.ViewContext.HttpContext.Request.ApplicationPath
- : helper.ViewContext.HttpContext.Request.ApplicationPath + "/",
- !string.IsNullOrEmpty(areaUrl)
- ? (areaUrl + "/" + controllerUrlName)
- : controllerUrlName,
- actionName == "Index" || actionName == ""
- ? ""
- : "/" + actionName,
- arguments,
+ public static string ActionLinkForAreas<TController>(
+ this HtmlHelper helper,
+ Expression<Action<TController>> action,
+ string linkText)
+ where TController : Controller
+ {
+ var controllerType = typeof(TController);
+ var controllerUrlName = GetUrlNameEquivalentOf(controllerType);
+ var areaUrl = ConvertNamespaceIntoAreaUrl(controllerType);
+
+ var methodCall = GetMethodCall(action);
+ var actionName = methodCall.Method.Name;
+ var arguments = GetQueryStringArguments(helper, action, controllerUrlName, actionName);
+
+ string path = helper.ViewContext.HttpContext.Request.ApplicationPath == "/"
+ ? helper.ViewContext.HttpContext.Request.ApplicationPath
+ : helper.ViewContext.HttpContext.Request.ApplicationPath + "/";
+
+ return string.Format(
+ LinkTemplate,
+ path,
+ !string.IsNullOrEmpty(areaUrl) ? (areaUrl + "/" + controllerUrlName) : controllerUrlName,
+ actionName == "Index" || actionName == string.Empty ? string.Empty : "/" + actionName,
+ arguments,
linkText);
}
- public static string BuildUrlFromExpressionForAreas<TController>(this HtmlHelper helper,
- Expression<Action<TController>> action) where TController : Controller {
-
- string actionLink = ActionLinkForAreas<TController>(helper, action, "-");
+ public static string BuildUrlFromExpressionForAreas<TController>(
+ this HtmlHelper helper, Expression<Action<TController>> action) where TController : Controller
+ {
+ var actionLink = ActionLinkForAreas(helper, action, "-");
return GetRoutePortionFrom(actionLink);
}
- private static string GetQueryStringArguments<TController>(HtmlHelper helper,
- Expression<Action<TController>> action, string linkText, string controllerUrlName, string actionName)
- where TController : Controller {
+ /// <summary>
+ /// Translates the namespace of a controller into an area URL taking into account that the
+ /// controller's assembly name should not be included as part of the URL
+ /// </summary>
+ private static string ConvertNamespaceIntoAreaUrl(Type controllerType)
+ {
+ return
+ controllerType.Namespace.Replace(
+ controllerType.Module.Name.Substring(0, controllerType.Module.Name.Length - LengthOfDotDll), string.Empty).
+ TrimStart('.').Replace('.', '/');
+ }
+
+ private static MethodCallExpression GetMethodCall<T>(Expression<Action<T>> action)
+ {
+ var body = action.Body as MethodCallExpression;
+
+ if (body == null)
+ {
+ throw new ArgumentException("Action must be a method call", "action");
+ }
+
+ return body;
+ }
- RouteValueDictionary routingValues = ExpressionHelper.GetRouteValuesFromExpression<TController>(action);
- string routePortion = helper.RouteCollection.GetVirtualPath(helper.ViewContext.RequestContext, routingValues).VirtualPath;
- string controllerAndActionUrlPortion = controllerUrlName + "/" + actionName;
+ private static string GetQueryStringArguments<TController>(
+ HtmlHelper helper,
+ Expression<Action<TController>> action,
+ string controllerUrlName,
+ string actionName) where TController : Controller
+ {
+ var routingValues = ExpressionHelper.GetRouteValuesFromExpression(action);
+ var routePortion =
+ helper.RouteCollection.GetVirtualPath(helper.ViewContext.RequestContext, routingValues).VirtualPath;
+ var controllerAndActionUrlPortion = controllerUrlName + "/" + actionName;
// If there's a "?" in the querystring, then take everything from the "?"
// and onwards as the parameters to the URL
- if (routePortion.IndexOf('?') > -1) {
+ if (routePortion.IndexOf('?') > -1)
+ {
return routePortion.Substring(routePortion.IndexOf('?'));
}
+
// If the controllerAndActionUrlPortion + "/" is found in the querystring, then it implies
// that there are parameters, so take everything after the controllerAndActionUrlPortion,
// including the "/"
- else if (routePortion.IndexOf(controllerAndActionUrlPortion + "/") > -1) {
- return routePortion.Substring(routePortion.IndexOf(controllerAndActionUrlPortion + "/") +
- controllerAndActionUrlPortion.Length);
- }
- else {
- return "";
+ if (routePortion.IndexOf(controllerAndActionUrlPortion + "/") > -1)
+ {
+ return
+ routePortion.Substring(
+ routePortion.IndexOf(controllerAndActionUrlPortion + "/") + controllerAndActionUrlPortion.Length);
}
+
+ return string.Empty;
}
- private static string GetRoutePortionFrom(string anchorLink) {
- int startOfRoutePortion = anchorLink.IndexOf("href=") + 6;
- int endOfRoutePortion = anchorLink.IndexOf("\"", startOfRoutePortion);
+ private static string GetRoutePortionFrom(string anchorLink)
+ {
+ var startOfRoutePortion = anchorLink.IndexOf("href=") + 6;
+ var endOfRoutePortion = anchorLink.IndexOf("\"", startOfRoutePortion);
- return
- anchorLink.Substring(startOfRoutePortion, endOfRoutePortion - startOfRoutePortion);
+ return anchorLink.Substring(startOfRoutePortion, endOfRoutePortion - startOfRoutePortion);
}
/// <summary>
- /// The URL name eqivalent of a controller is its name sans the word "Controller" at the end
+ /// The URL name eqivalent of a controller is its name sans the word "Controller" at the end
/// </summary>
- private static string GetUrlNameEquivalentOf(Type controllerType) {
+ private static string GetUrlNameEquivalentOf(Type controllerType)
+ {
return controllerType.Name.Substring(0, controllerType.Name.Length - "Controller".Length);
}
-
- /// <summary>
- /// Translates the namespace of a controller into an area URL taking into account that the
- /// controller's assembly name should not be included as part of the URL
- /// </summary>
- private static string ConvertNamespaceIntoAreaUrl(Type controllerType) {
- return controllerType.Namespace
- .Replace(controllerType.Module.Name.Substring(0, controllerType.Module.Name.Length - LENGTH_OF_DOT_DLL), "")
- .TrimStart('.').Replace('.', '/');
- }
-
- private static MethodCallExpression GetMethodCall<T>(Expression<Action<T>> action) {
- MethodCallExpression body = action.Body as MethodCallExpression;
-
- if (body == null)
- throw new ArgumentException("Action must be a method call", "action");
- else
- return body;
- }
-
- /// <summary>
- /// Template to be used for the creation of area-supported links
- /// </summary>
- private const string linkTemplate = "<a href=\"{0}{1}{2}{3}\">{4}</a>";
-
- /// <summary>
- /// Length of the string ".dll"
- /// </summary>
- private const int LENGTH_OF_DOT_DLL = 4;
}
-}
+}
View
74 Solutions/SharpArch/SharpArch.Web/CommonValidator/MvcValidationAdapter.cs
@@ -1,51 +1,63 @@
-using System.Web.Mvc;
-using SharpArch.Core;
-using System;
-using System.Collections.Generic;
-using SharpArch.Core.CommonValidator;
-using System.Globalization;
-
namespace SharpArch.Web.CommonValidator
{
+ using System.Collections.Generic;
+ using System.Globalization;
+ using System.Web.Mvc;
+
+ using SharpArch.Core;
+ using SharpArch.Core.CommonValidator;
+
public class MvcValidationAdapter
{
public static ModelStateDictionary TransferValidationMessagesTo(
- ModelStateDictionary modelStateDictionary,
- IEnumerable<IValidationResult> validationResults) {
-
+ ModelStateDictionary modelStateDictionary, IEnumerable<IValidationResult> validationResults)
+ {
return TransferValidationMessagesTo(null, modelStateDictionary, validationResults);
}
-
+
/// <summary>
- /// This acts as a more "manual" alternative to moving validation errors to the
- /// <see cref="ModelStateDictionary" /> if you care to bypass the use of
- /// <see cref="ValidatableModelBinder" />. This typically wouldn't be used in conjunction
- /// with <see cref="ValidatableModelBinder" /> but as an alternative to it.
+ /// This acts as a more "manual" alternative to moving validation errors to the
+ /// <see cref = "ModelStateDictionary" /> if you care to bypass the use of
+ /// <see cref = "ValidatableModelBinder" />. This typically wouldn't be used in conjunction
+ /// with <see cref = "ValidatableModelBinder" /> but as an alternative to it.
/// </summary>
- /// <param name="keyBase">If supplied, will be used as the model state prefix
- /// instead of the class name</param>
+ /// <param name = "keyBase">If supplied, will be used as the model state prefix instead of the class name</param>
+ /// <param name="modelStateDictionary">The model state dictionary that will be populated with the validation results.</param>
+ /// <param name="validationResults">The results to transfer.</param>
public static ModelStateDictionary TransferValidationMessagesTo(
- string keyBase, ModelStateDictionary modelStateDictionary,
- IEnumerable<IValidationResult> validationResults) {
-
+ string keyBase,
+ ModelStateDictionary modelStateDictionary,
+ IEnumerable<IValidationResult> validationResults)
+ {
Check.Require(modelStateDictionary != null, "modelStateDictionary may not be null");
Check.Require(validationResults != null, "invalidValues may not be null");
- foreach (IValidationResult validationResult in validationResults) {
- Check.Require(validationResult.ClassContext != null,
- "validationResult.ClassContext may not be null");
+ foreach (var validationResult in validationResults)
+ {
+ Check.Require(validationResult.ClassContext != null, "validationResult.ClassContext may not be null");
- string key = (keyBase ?? validationResult.ClassContext.Name) +
- (!string.IsNullOrEmpty(validationResult.PropertyName)
- ? "." + validationResult.PropertyName
- : "");
- key = key.Trim('.'); //fixes issue where key ends up as .PropertyName instead of object.PropertyName or just PropertyName
+ var key = (keyBase ?? validationResult.ClassContext.Name) +
+ (!string.IsNullOrEmpty(validationResult.PropertyName)
+ ? "." + validationResult.PropertyName
+ : string.Empty);
+ key = key.Trim('.');
+
+ // fixes issue where key ends up as .PropertyName instead of object.PropertyName or just PropertyName
modelStateDictionary.AddModelError(key, validationResult.Message);
- modelStateDictionary.SetModelValue(key, new ValueProviderResult(validationResult.AttemptedValue ?? "", (validationResult.AttemptedValue ?? "").ToString(), CultureInfo.CurrentCulture)); //Fixes problem where invalid fields get blanked out.
- //modelStateDictionary.SetModelValue(key, new ValueProviderResult(null, null, null));
+
+ var valueProviderResult = new ValueProviderResult(
+ validationResult.AttemptedValue ?? string.Empty,
+ (validationResult.AttemptedValue ?? string.Empty).ToString(),
+ CultureInfo.CurrentCulture);
+
+ modelStateDictionary.SetModelValue(
+ key,
+ valueProviderResult); // Fixes problem where invalid fields get blanked out.
+
+ // modelStateDictionary.SetModelValue(key, new ValueProviderResult(null, null, null));
}
return modelStateDictionary;
}
}
-}
+}
View
60 Solutions/SharpArch/SharpArch.Web/CommonValidator/ValidatableModelBinder.cs
@@ -1,45 +1,53 @@
-using System.Web.Mvc;
-using System.ComponentModel;
-using SharpArch.Core.CommonValidator;
-using System;
-
namespace SharpArch.Web.CommonValidator
{
+ using System;
+ using System.ComponentModel;
+ using System.Web.Mvc;
+
+ using SharpArch.Core.CommonValidator;
+
/// <summary>
- /// With ASP.NET MVC RC, Microsoft introduced IDataErrorInfo which allows one to enforce
- /// validation with the raising of exceptions to communicate information about the invalid state.
+ /// With ASP.NET MVC RC, Microsoft introduced IDataErrorInfo which allows one to enforce
+ /// validation with the raising of exceptions to communicate information about the invalid state.
///
- /// This model binder class provides an alternative to raising exceptions by tracking validation
- /// issues during the binding process itself. More information about this approach is described
- /// by David Hayden at http://codebetter.com/blogs/david.hayden/archive/2009/02/03/an-aha-moment-on-mvc-validation-extensibility-in-defaultmodelbinder-bye-to-idataerrorinfo.aspx.
+ /// This model binder class provides an alternative to raising exceptions by tracking validation
+ /// issues during the binding process itself. More information about this approach is described
+ /// by David Hayden at http://codebetter.com/blogs/david.hayden/archive/2009/02/03/an-aha-moment-on-mvc-validation-extensibility-in-defaultmodelbinder-bye-to-idataerrorinfo.aspx.
/// </summary>
- [Obsolete("This binder is very limited in nature. While it remains for backward compatibility, it " +
+ [Obsolete(
+ "This binder is very limited in nature. While it remains for backward compatibility, it " +
"is highly recommended to instead use SharpArch.Web.ModelBinder.SharpModelBinder which is much " +
"more seamlessly integrated with the SharpArch libraries and repository support.")]
public class ValidatableModelBinder : DefaultModelBinder
{
- protected override void OnModelUpdated(ControllerContext controllerContext,
- ModelBindingContext bindingContext) {
-
- IValidatable model = bindingContext.Model as IValidatable;
+ protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
+ {
+ var model = bindingContext.Model as IValidatable;
- if (model != null) {
- if (! model.IsValid()) {
- foreach (IValidationResult validationResult in model.ValidationResults()) {
- bindingContext.ModelState
- .AddModelError(validationResult.ClassContext.Name +
+ if (model != null)
+ {
+ if (! model.IsValid())
+ {
+ foreach (var validationResult in model.ValidationResults())
+ {
+ bindingContext.ModelState.AddModelError(
+ validationResult.ClassContext.Name +
(!string.IsNullOrEmpty(validationResult.PropertyName)
- ? "." + validationResult.PropertyName
- : ""),
- validationResult.Message);
+ ? "." + validationResult.PropertyName
+ : string.Empty),
+ validationResult.Message);
}
}
}
}
- protected override void OnPropertyValidated(ControllerContext controllerContext,
- ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) {
+ protected override void OnPropertyValidated(
+ ControllerContext controllerContext,
+ ModelBindingContext bindingContext,
+ PropertyDescriptor propertyDescriptor,
+ object value)
+ {
// Do nothing
}
}
-}
+}
View
129 Solutions/SharpArch/SharpArch.Web/JsonNet/JsonNetResult.cs
@@ -1,58 +1,75 @@
-using System.Web.Mvc;
-using System.Text;
-using System.Web;
-using Newtonsoft.Json;
-using System;
-
namespace SharpArch.Web.JsonNet
{
- /// <summary>
- /// An ActionResult to return JSON from ASP.NET MVC to the browser using Json.NET.
- /// Taken from http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
- /// </summary>
- public class JsonNetResult : ActionResult
- {
- public JsonNetResult() : this(null, null, null) { }
- public JsonNetResult(Object data) : this(data, null, null) { }
- public JsonNetResult(Object data, String contentType) : this(data, contentType, null) { }
-
- public JsonNetResult(Object data, String contentType, Encoding encoding) {
- SerializerSettings = new JsonSerializerSettings();
-
- Data = data;
- ContentType = contentType;
- ContentEncoding = encoding;
- }
-
- public override void ExecuteResult(ControllerContext context) {
- if (context == null)
- throw new ArgumentNullException("context");
-
- HttpResponseBase response = context.HttpContext.Response;
-
- response.ContentType = !string.IsNullOrEmpty(ContentType)
- ? ContentType
- : "application/json";
-
- if (ContentEncoding != null)
- response.ContentEncoding = ContentEncoding;
-
- if (Data != null) {
- JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
- JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
- serializer.Serialize(writer, Data);
- writer.Flush();
- }
- }
-
- public Encoding ContentEncoding { get; set; }
- public string ContentType { get; set; }
- public object Data { get; set; }
-
- [CLSCompliant(false)]
- public JsonSerializerSettings SerializerSettings { get; set; }
-
- [CLSCompliant(false)]
- public Formatting Formatting { get; set; }
- }
-}
+ using System;
+ using System.Text;
+ using System.Web.Mvc;
+
+ using Newtonsoft.Json;
+
+ /// <summary>
+ /// An ActionResult to return JSON from ASP.NET MVC to the browser using Json.NET.
+ /// Taken from http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
+ /// </summary>
+ public class JsonNetResult : ActionResult
+ {
+ public JsonNetResult()
+ : this(null, null, null)
+ {
+ }
+
+ public JsonNetResult(object data)
+ : this(data, null, null)
+ {
+ }
+
+ public JsonNetResult(object data, string contentType)
+ : this(data, contentType, null)
+ {
+ }
+
+ public JsonNetResult(object data, string contentType, Encoding encoding)
+ {
+ this.SerializerSettings = new JsonSerializerSettings();
+
+ this.Data = data;
+ this.ContentType = contentType;
+ this.ContentEncoding = encoding;
+ }
+
+ public Encoding ContentEncoding { get; set; }
+
+ public string ContentType { get; set; }
+
+ public object Data { get; set; }
+
+ [CLSCompliant(false)]
+ public Formatting Formatting { get; set; }
+ [CLSCompliant(false)]
+ public JsonSerializerSettings SerializerSettings { get; set; }
+
+ public override void ExecuteResult(ControllerContext context)
+ {
+ if (context == null)
+ {
+ throw new ArgumentNullException("context");
+ }
+
+ var response = context.HttpContext.Response;
+
+ response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json";
+
+ if (this.ContentEncoding != null)
+ {
+ response.ContentEncoding = this.ContentEncoding;
+ }
+
+ if (this.Data != null)
+ {
+ var writer = new JsonTextWriter(response.Output) { Formatting = this.Formatting };
+ var serializer = JsonSerializer.Create(this.SerializerSettings);
+ serializer.Serialize(writer, this.Data);
+ writer.Flush();
+ }
+ }
+ }
+}
View
66 Solutions/SharpArch/SharpArch.Web/ModelBinder/EntityCollectionValueBinder.cs
@@ -1,61 +1,63 @@
-using System;
-using System.Linq;
-using System.Web.Mvc;
-using SharpArch.Core.DomainModel;
-
namespace SharpArch.Web.ModelBinder
{
- class EntityCollectionValueBinder : DefaultModelBinder
- {
- #region Implementation of IModelBinder
+ using System;
+ using System.Linq;
+ using System.Web.Mvc;
+ using SharpArch.Core.DomainModel;
+
+ internal class EntityCollectionValueBinder : DefaultModelBinder
+ {
/// <summary>
- /// Binds the model to a value by using the specified controller context and binding context.
+ /// Binds the model to a value by using the specified controller context and binding context.
/// </summary>
/// <returns>
- /// The bound value.
+ /// The bound value.
/// </returns>
- /// <param name="controllerContext">The controller context.</param><param name="bindingContext">The binding context.</param>
+ /// <param name = "controllerContext">The controller context.</param>
+ /// <param name = "bindingContext">The binding context.</param>
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
- Type collectionType = bindingContext.ModelType;
- Type collectionEntityType = collectionType.GetGenericArguments().First();
+ var collectionType = bindingContext.ModelType;
+ var collectionEntityType = collectionType.GetGenericArguments().First();
- ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
+ var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult != null)
{
- int countOfEntityIds = (valueProviderResult.RawValue as string[]).Length;
- Array entities = Array.CreateInstance(collectionEntityType, countOfEntityIds);
+ var rawValue = valueProviderResult.RawValue as string[];
- Type entityInterfaceType = collectionEntityType.GetInterfaces()
- .First(interfaceType => interfaceType.IsGenericType
- && interfaceType.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
+ var countOfEntityIds = rawValue.Length;
+ var entities = Array.CreateInstance(collectionEntityType, countOfEntityIds);
- Type idType = entityInterfaceType.GetGenericArguments().First();
+ var entityInterfaceType =
+ collectionEntityType.GetInterfaces().First(
+ interfaceType =>
+ interfaceType.IsGenericType &&
+ interfaceType.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
- for ( int i = 0; i < countOfEntityIds; i++ )
+ var idType = entityInterfaceType.GetGenericArguments().First();
+
+ for (var i = 0; i < countOfEntityIds; i++)
{
- string rawId = (valueProviderResult.RawValue as string[])[i];
+ var rawId = rawValue[i];
- if ( string.IsNullOrEmpty(rawId) )
+ if (string.IsNullOrEmpty(rawId))
+ {
return null;
+ }
- object typedId =
- (idType == typeof(Guid))
- ? new Guid(rawId)
- : Convert.ChangeType(rawId, idType);
+ var typedId = (idType == typeof(Guid)) ? new Guid(rawId) : Convert.ChangeType(rawId, idType);
- object entity = ValueBinderHelper.GetEntityFor(collectionEntityType, typedId, idType);
+ var entity = ValueBinderHelper.GetEntityFor(collectionEntityType, typedId, idType);
entities.SetValue(entity, i);
}
- //base.BindModel(controllerContext, bindingContext);
+ // base.BindModel(controllerContext, bindingContext);
return entities;
}
+
return base.BindModel(controllerContext, bindingContext);
}
-
- #endregion
}
-}
+}
View
53 Solutions/SharpArch/SharpArch.Web/ModelBinder/EntityValueBinder.cs
@@ -1,58 +1,57 @@
-using System;
-using System.Linq;
-using System.Web.Mvc;
-using SharpArch.Core.DomainModel;
-
namespace SharpArch.Web.ModelBinder
{
- class EntityValueBinder : SharpModelBinder
- {
- #region Implementation of IModelBinder
+ using System;
+ using System.Linq;
+ using System.Web.Mvc;
+
+ using SharpArch.Core.DomainModel;
+ internal class EntityValueBinder : SharpModelBinder
+ {
/// <summary>
- /// Binds the model value to an entity by using the specified controller context and binding context.
+ /// Binds the model value to an entity by using the specified controller context and binding context.
/// </summary>
/// <returns>
- /// The bound value.
+ /// The bound value.
/// </returns>
- /// <param name="controllerContext">The controller context.</param><param name="bindingContext">The binding context.</param>
+ /// <param name = "controllerContext">The controller context.</param>
+ /// <param name = "bindingContext">The binding context.</param>
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
- Type modelType = bindingContext.ModelType;
+ var modelType = bindingContext.ModelType;
- ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
+ var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
- if ( valueProviderResult != null )
+ if (valueProviderResult != null)
{
- Type entityInterfaceType = modelType.GetInterfaces()
- .First(interfaceType => interfaceType.IsGenericType
- && interfaceType.GetGenericTypeDefinition() == typeof (IEntityWithTypedId<>));
+ var entityInterfaceType =
+ modelType.GetInterfaces().First(
+ interfaceType =>
+ interfaceType.IsGenericType &&
+ interfaceType.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
- Type idType = entityInterfaceType.GetGenericArguments().First();
- string rawId = (valueProviderResult.RawValue as string[]).First();
+ var idType = entityInterfaceType.GetGenericArguments().First();
+ var rawId = (valueProviderResult.RawValue as string[]).First();
if (string.IsNullOrEmpty(rawId))
+ {
return null;
+ }
try
{
- object typedId =
- (idType == typeof (Guid))
- ? new Guid(rawId)
- : Convert.ChangeType(rawId, idType);
+ var typedId = (idType == typeof(Guid)) ? new Guid(rawId) : Convert.ChangeType(rawId, idType);
return ValueBinderHelper.GetEntityFor(modelType, typedId, idType);
}
- // If the Id conversion failed for any reason, just return null
catch (Exception)
{
+ // If the Id conversion failed for any reason, just return null
return null;
}
}
return base.BindModel(controllerContext, bindingContext);
}
-
- #endregion
}
-}
+}
View
36 Solutions/SharpArch/SharpArch.Web/ModelBinder/GenericRepositoryFactory.cs
@@ -1,32 +1,38 @@
-using SharpArch.Core.PersistenceSupport;
-using System;
-using Microsoft.Practices.ServiceLocation;
-
namespace SharpArch.Web.ModelBinder
{
+ using System;
+
+ using Microsoft.Practices.ServiceLocation;
+
+ using SharpArch.Core.PersistenceSupport;
+
internal class GenericRepositoryFactory
{
- public static object CreateEntityRepositoryFor(Type entityType, Type idType) {
- Type genericRepositoryType = typeof(IRepositoryWithTypedId<,>);
- Type concreteRepositoryType =
- genericRepositoryType.MakeGenericType(new Type[] { entityType, idType });
+ public static object CreateEntityRepositoryFor(Type entityType, Type idType)
+ {
+ var genericRepositoryType = typeof(IRepositoryWithTypedId<,>);
+ var concreteRepositoryType = genericRepositoryType.MakeGenericType(new[] { entityType, idType });
object repository;
- try {
+ try
+ {
repository = ServiceLocator.Current.GetService(concreteRepositoryType);
}
- catch (NullReferenceException) {
- throw new NullReferenceException("ServiceLocator has not been initialized; " +
- "I was trying to retrieve " + concreteRepositoryType.ToString());
+ catch (NullReferenceException)
+ {
+ throw new NullReferenceException(
+ "ServiceLocator has not been initialized; " + "I was trying to retrieve " + concreteRepositoryType);
}
- catch (ActivationException) {
- throw new ActivationException("The needed dependency of type " + concreteRepositoryType.Name +
+ catch (ActivationException)
+ {
+ throw new ActivationException(
+ "The needed dependency of type " + concreteRepositoryType.Name +
" could not be located with the ServiceLocator. You'll need to register it with " +
"the Common Service Locator (CSL) via your IoC's CSL adapter.");
}
return repository;
}
}
-}
+}
View
365 Solutions/SharpArch/SharpArch.Web/ModelBinder/SharpModelBinder.cs
@@ -1,202 +1,167 @@
-using System.Web.Mvc;
-using System.ComponentModel;
-using System;
-using SharpArch.Core.DomainModel;
-using System.Linq;
-using System.Reflection;
-using System.Collections.Generic;
-using System.Collections;
-
namespace SharpArch.Web.ModelBinder
{
- public class SharpModelBinder : DefaultModelBinder
- {
- /// <summary>
- /// Called when the model is updating. We handle updating the Id property here because it gets filtered out
- /// of the normal MVC2 property binding.
- /// </summary>
- /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param>
- /// <param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param>
- /// <returns>
- /// true if the model is updating; otherwise, false.
- /// </returns>
- protected override bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext)
- {
- if ( IsEntityType(bindingContext.ModelType) )
- {
- //handle the Id property
- PropertyDescriptor idProperty =
- (from PropertyDescriptor property in TypeDescriptor.GetProperties(bindingContext.ModelType)
- where property.Name == ID_PROPERTY_NAME
- select property).SingleOrDefault();
-
- BindProperty(controllerContext, bindingContext, idProperty);
-
- }
- return base.OnModelUpdating(controllerContext, bindingContext);
- }
-
- protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
- {
- Type propertyType = propertyDescriptor.PropertyType;
-
- if ( IsEntityType(propertyType) )
- {
- //use the EntityValueBinder
- return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, new EntityValueBinder());
- }
-
- if ( IsSimpleGenericBindableEntityCollection(propertyType) )
- {
- //use the EntityValueCollectionBinder
- return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, new EntityCollectionValueBinder());
- }
-
- return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
- }
-
- protected override void SetProperty(ControllerContext controllerContext,
- ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
- {
- if ( propertyDescriptor.Name == ID_PROPERTY_NAME )
- {
- SetIdProperty(bindingContext, propertyDescriptor, value);
- }
- else if (value as IEnumerable != null && IsSimpleGenericBindableEntityCollection(propertyDescriptor.PropertyType))
- {
- SetEntityCollectionProperty(bindingContext, propertyDescriptor, value);
- }
- else
- {
- base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
- }
-
- }
-
- private static bool IsEntityType(Type propertyType)
- {
- bool isEntityType = propertyType.GetInterfaces()
- .Any(type => type.IsGenericType &&
- type.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
-
- return isEntityType;
- }
-
- private static bool IsSimpleGenericBindableEntityCollection(Type propertyType)
- {
- bool isSimpleGenericBindableCollection =
- propertyType.IsGenericType &&
- (propertyType.GetGenericTypeDefinition() == typeof(IList<>) ||
- propertyType.GetGenericTypeDefinition() == typeof(ICollection<>) ||
- propertyType.GetGenericTypeDefinition() == typeof(Iesi.Collections.Generic.ISet<>) ||
- propertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>));
-
- bool isSimpleGenericBindableEntityCollection =
- isSimpleGenericBindableCollection && IsEntityType(propertyType.GetGenericArguments().First());
-
- return isSimpleGenericBindableEntityCollection;
- }
-
- /// <summary>
- /// If the property being bound is an Id property, then use reflection to get past the
- /// protected visibility of the Id property, accordingly.
- /// </summary>
- private static void SetIdProperty(ModelBindingContext bindingContext,
- PropertyDescriptor propertyDescriptor, object value)
- {
- Type idType = propertyDescriptor.PropertyType;
- object typedId;
-
- if (value == null)
- {
- typedId = idType.IsValueType ? Activator.CreateInstance(idType) : null;
- }
- else
- {
- typedId = Convert.ChangeType(value, idType);
- }
-
- // First, look to see if there's an Id property declared on the entity itself;
- // e.g., using the new keyword
- PropertyInfo idProperty = bindingContext.ModelType
- .GetProperty(propertyDescriptor.Name,
- BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
-
- // If an Id property wasn't found on the entity, then grab the Id property from
- // the entity base class
- if ( idProperty == null )
- {
- idProperty = bindingContext.ModelType
- .GetProperty(propertyDescriptor.Name,
- BindingFlags.Public | BindingFlags.Instance);
- }
-
- // Set the value of the protected Id property
- idProperty.SetValue(bindingContext.Model, typedId, null);
- }
-
-
- /// <summary>
- /// If the property being bound is a simple, generic collection of entiy objects, then use
- /// reflection to get past the protected visibility of the collection property, if necessary.
- /// </summary>
- private static void SetEntityCollectionProperty(ModelBindingContext bindingContext,
- PropertyDescriptor propertyDescriptor, object value)
- {
- object entityCollection = propertyDescriptor.GetValue(bindingContext.Model);
- if (entityCollection != value)
- {
- Type entityCollectionType = entityCollection.GetType();
-
- foreach (object entity in (value as IEnumerable))
- {
- entityCollectionType.InvokeMember("Add",
- BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, entityCollection,
- new object[] { entity });
- }
- }
- }
-
- #region Overridable (but not yet overridden) Methods
-
- public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
- {
- return base.BindModel(controllerContext, bindingContext);
- }
-
- protected override object CreateModel(ControllerContext controllerContext,
- ModelBindingContext bindingContext, Type modelType)
- {
-
- return base.CreateModel(controllerContext, bindingContext, modelType);
- }
-
- protected override void BindProperty(ControllerContext controllerContext,
- ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
- {
- base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
- }
-
- protected override void OnPropertyValidated(ControllerContext controllerContext,
- ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
- {
- base.OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, value);
- }
-
- protected override bool OnPropertyValidating(ControllerContext controllerContext,
- ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
- {
-
- return base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
- }
-
- protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
- {
- base.OnModelUpdated(controllerContext, bindingContext);
- }
-
- #endregion
-
- private const string ID_PROPERTY_NAME = "Id";
- }
-}
+ using System;
+ using System.Collections;
+ using System.Collections.Generic;
+ using System.ComponentModel;
+ using System.Linq;
+ using System.Reflection;
+ using System.Web.Mvc;
+
+ using SharpArch.Core.DomainModel;
+
+ public class SharpModelBinder : DefaultModelBinder
+ {
+ private const string IdPropertyName = "Id";
+
+ protected override object GetPropertyValue(
+ ControllerContext controllerContext,
+ ModelBindingContext bindingContext,
+ PropertyDescriptor propertyDescriptor,
+ IModelBinder propertyBinder)
+ {
+ var propertyType = propertyDescriptor.PropertyType;
+
+ if (IsEntityType(propertyType))
+ {
+ // use the EntityValueBinder
+ return base.GetPropertyValue(
+ controllerContext, bindingContext, propertyDescriptor, new EntityValueBinder());
+ }
+
+ if (IsSimpleGenericBindableEntityCollection(propertyType))
+ {
+ // use the EntityValueCollectionBinder
+ return base.GetPropertyValue(
+ controllerContext, bindingContext, propertyDescriptor, new EntityCollectionValueBinder());
+ }
+
+ return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
+ }
+
+ /// <summary>
+ /// Called when the model is updating. We handle updating the Id property here because it gets filtered out
+ /// of the normal MVC2 property binding.
+ /// </summary>
+ /// <param name = "controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param>
+ /// <param name = "bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param>
+ /// <returns>
+ /// true if the model is updating; otherwise, false.
+ /// </returns>
+ protected override bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext)
+ {
+ if (IsEntityType(bindingContext.ModelType))
+ {
+ // handle the Id property
+ var idProperty =
+ (from PropertyDescriptor property in TypeDescriptor.GetProperties(bindingContext.ModelType)
+ where property.Name == IdPropertyName
+ select property).SingleOrDefault();
+
+ this.BindProperty(controllerContext, bindingContext, idProperty);
+ }
+
+ return base.OnModelUpdating(controllerContext, bindingContext);
+ }
+
+ protected override void SetProperty(
+ ControllerContext controllerContext,
+ ModelBindingContext bindingContext,
+ PropertyDescriptor propertyDescriptor,
+ object value)
+ {
+ if (propertyDescriptor.Name == IdPropertyName)
+ {
+ SetIdProperty(bindingContext, propertyDescriptor, value);
+ }
+ else if (value as IEnumerable != null &&
+ IsSimpleGenericBindableEntityCollection(propertyDescriptor.PropertyType))
+ {
+ SetEntityCollectionProperty(bindingContext, propertyDescriptor, value);
+ }
+ else
+ {
+ base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
+ }
+ }
+
+ private static bool IsEntityType(Type propertyType)
+ {
+ var isEntityType =
+ propertyType.GetInterfaces().Any(
+ type => type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
+
+ return isEntityType;
+ }
+
+ private static bool IsSimpleGenericBindableEntityCollection(Type propertyType)
+ {
+ var isSimpleGenericBindableCollection = propertyType.IsGenericType &&
+ (propertyType.GetGenericTypeDefinition() == typeof(IList<>) ||
+ propertyType.GetGenericTypeDefinition() == typeof(ICollection<>) ||
+ propertyType.GetGenericTypeDefinition() ==
+ typeof(Iesi.Collections.Generic.ISet<>) ||
+ propertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>));
+
+ var isSimpleGenericBindableEntityCollection = isSimpleGenericBindableCollection &&
+ IsEntityType(propertyType.GetGenericArguments().First());
+
+ return isSimpleGenericBindableEntityCollection;
+ }
+
+ /// <summary>
+ /// If the property being bound is a simple, generic collection of entiy objects, then use
+ /// reflection to get past the protected visibility of the collection property, if necessary.
+ /// </summary>
+ private static void SetEntityCollectionProperty(
+ ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
+ {
+ var entityCollection = propertyDescriptor.GetValue(bindingContext.Model);
+ if (entityCollection != value)
+ {
+ var entityCollectionType = entityCollection.GetType();
+
+ foreach (var entity in value as IEnumerable)
+ {
+ entityCollectionType.InvokeMember(
+ "Add",
+ BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
+ null,
+ entityCollection,
+ new[] { entity });
+ }
+ }
+ }
+
+ /// <summary>
+ /// If the property being bound is an Id property, then use reflection to get past the
+ /// protected visibility of the Id property, accordingly.
+ /// </summary>
+ private static void SetIdProperty(
+ ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
+ {
+ var idType = propertyDescriptor.PropertyType;
+ object typedId;
+
+ if (value == null)
+ {
+ typedId = idType.IsValueType ? Activator.CreateInstance(idType) : null;
+ }
+ else
+ {
+ typedId = Convert.ChangeType(value, idType);
+ }
+
+ // First, look to see if there's an Id property declared on the entity itself;
+ // e.g., using the new keyword
+ var idProperty = bindingContext.ModelType.GetProperty(propertyDescriptor.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
+ ?? bindingContext.ModelType.GetProperty(propertyDescriptor.Name, BindingFlags.Public | BindingFlags.Instance);
+
+ // If an Id property wasn't found on the entity, then grab the Id property from
+ // the entity base class
+
+ // Set the value of the protected Id property
+ idProperty.SetValue(bindingContext.Model, typedId, null);
+ }
+ }
+}
View
14 Solutions/SharpArch/SharpArch.Web/ModelBinder/ValueBinderHelper.cs
@@ -1,16 +1,16 @@
-using System;
-using System.Reflection;
-
namespace SharpArch.Web.ModelBinder
{
+ using System;
+ using System.Reflection;
+
internal static class ValueBinderHelper
{
internal static object GetEntityFor(Type collectionEntityType, object typedId, Type idType)
{
- object entityRepository = GenericRepositoryFactory.CreateEntityRepositoryFor(collectionEntityType, idType);
+ var entityRepository = GenericRepositoryFactory.CreateEntityRepositoryFor(collectionEntityType, idType);
- return entityRepository.GetType()
- .InvokeMember("Get", BindingFlags.InvokeMethod, null, entityRepository, new[] { typedId });
+ return entityRepository.GetType().InvokeMember(
+ "Get", BindingFlags.InvokeMethod, null, entityRepository, new[] { typedId });
}
}
-}
+}
View
90 Solutions/SharpArch/SharpArch.Web/NHibernate/TransactionAttribute.cs
@@ -1,56 +1,68 @@
-using System.Web.Mvc;
-using SharpArch.Data.NHibernate;
-using System;
-using NHibernate;
-
namespace SharpArch.Web.NHibernate
{
- public class TransactionAttribute : ActionFilterAttribute
- {
+ using System;
+ using System.Web.Mvc;
+
+ using SharpArch.Data.NHibernate;
+
+ public class TransactionAttribute : ActionFilterAttribute
+ {
/// <summary>
- /// When used, assumes the <see cref="factoryKey" /> to be NHibernateSession.DefaultFactoryKey
+ /// Optionally holds the factory key to be used when beginning/committing a transaction
/// </summary>
- public TransactionAttribute() { }
+ private readonly string factoryKey;
- public bool RollbackOnModelStateError { get; set; }
+ /// <summary>
+ /// When used, assumes the <see cref = "factoryKey" /> to be NHibernateSession.DefaultFactoryKey
+ /// </summary>
+ public TransactionAttribute()
+ {
+ }
/// <summary>
- /// Overrides the default <see cref="factoryKey" /> with a specific factory key
+ /// Overrides the default <see cref = "factoryKey" /> with a specific factory key
/// </summary>
- public TransactionAttribute(string factoryKey) {
+ public TransactionAttribute(string factoryKey)
+ {
this.factoryKey = factoryKey;
- }
+ }
- public override void OnActionExecuting(ActionExecutingContext filterContext) {
- NHibernateSession.CurrentFor(GetEffectiveFactoryKey()).BeginTransaction();
- }
+ public bool RollbackOnModelStateError { get; set; }
+
+ public override void OnActionExecuted(ActionExecutedContext filterContext)
+ {
+ var effectiveFactoryKey = this.GetEffectiveFactoryKey();
- public override void OnActionExecuted(ActionExecutedContext filterContext) {
- string effectiveFactoryKey = GetEffectiveFactoryKey();
+ var currentTransaction = NHibernateSession.CurrentFor(effectiveFactoryKey).Transaction;
- ITransaction currentTransaction =
- NHibernateSession.CurrentFor(effectiveFactoryKey).Transaction;
-
- if (currentTransaction.IsActive) {
- if (((filterContext.Exception != null) && (filterContext.ExceptionHandled)) || ShouldRollback(filterContext))
+ if (currentTransaction.IsActive)
+ {
+ if (((filterContext.Exception != null) && filterContext.ExceptionHandled) ||
+ this.ShouldRollback(filterContext))
{
currentTransaction.Rollback();
}
}
}
- public override void OnResultExecuted(ResultExecutedContext filterContext)
+ public override void OnActionExecuting(ActionExecutingContext filterContext)
{
- string effectiveFactoryKey = GetEffectiveFactoryKey();
+ NHibernateSession.CurrentFor(this.GetEffectiveFactoryKey()).BeginTransaction();
+ }
+
+ public override void OnResultExecuted(ResultExecutedContext filterContext)
+ {
+ var effectiveFactoryKey = this.GetEffectiveFactoryKey();
+
+ var currentTransaction = NHibernateSession.CurrentFor(effectiveFactoryKey).Transaction;
- ITransaction currentTransaction =
- NHibernateSession.CurrentFor(effectiveFactoryKey).Transaction;
-
base.OnResultExecuted(filterContext);
try
{
- if (currentTransaction.IsActive) {
- if (((filterContext.Exception != null) && (!filterContext.ExceptionHandled)) || ShouldRollback(filterContext))
+ if (currentTransaction.IsActive)
+ {
+ if (((filterContext.Exception != null) && (!filterContext.ExceptionHandled)) ||
+ this.ShouldRollback(filterContext))
{
currentTransaction.Rollback();
}
@@ -66,20 +78,14 @@ public override void OnResultExecuted(ResultExecutedContext filterContext)
}
}
- private string GetEffectiveFactoryKey() {
- return String.IsNullOrEmpty(factoryKey)
- ? NHibernateSession.DefaultFactoryKey
- : factoryKey;
+ private string GetEffectiveFactoryKey()
+ {
+ return String.IsNullOrEmpty(this.factoryKey) ? NHibernateSession.DefaultFactoryKey : this.factoryKey;
}
private bool ShouldRollback(ControllerContext filterContext)
{
- return RollbackOnModelStateError && !filterContext.Controller.ViewData.ModelState.IsValid;
+ return this.RollbackOnModelStateError && !filterContext.Controller.ViewData.ModelState.IsValid;
}
-
- /// <summary>
- /// Optionally holds the factory key to be used when beginning/committing a transaction
- /// </summary>
- private string factoryKey;
- }
-}
+ }
+}
View
111 Solutions/SharpArch/SharpArch.Web/NHibernate/WebSessionStorage.cs
@@ -1,56 +1,59 @@
-using System;
-using System.Web;
-using NHibernate;
-using SharpArch.Data;
-using SharpArch.Data.NHibernate;
-
namespace SharpArch.Web.NHibernate
{
- public class WebSessionStorage : ISessionStorage
- {
- public WebSessionStorage(HttpApplication app)
- {
- app.EndRequest += Application_EndRequest;
- }
-
- public ISession GetSessionForKey(string factoryKey)
- {
- SimpleSessionStorage storage = GetSimpleSessionStorage();
- return storage.GetSessionForKey(factoryKey);
- }
-
- public void SetSessionForKey(string factoryKey, ISession session)
- {
- SimpleSessionStorage storage = GetSimpleSessionStorage();
- storage.SetSessionForKey(factoryKey, session);
- }
-
- public System.Collections.Generic.IEnumerable<ISession> GetAllSessions()
- {
- SimpleSessionStorage storage = GetSimpleSessionStorage();
- return storage.GetAllSessions();
- }
-
- private SimpleSessionStorage GetSimpleSessionStorage()
- {
- HttpContext context = HttpContext.Current;
- SimpleSessionStorage storage = context.Items[HttpContextSessionStorageKey] as SimpleSessionStorage;
- if (storage == null)
- {
- storage = new SimpleSessionStorage();
- context.Items[HttpContextSessionStorageKey] = storage;
- }
- return storage;
- }
-
- private static readonly string HttpContextSessionStorageKey = "HttpContextSessionStorageKey";
-
- private void Application_EndRequest(object sender, EventArgs e)
- {
- NHibernateSession.CloseAllSessions();
-
- HttpContext context = HttpContext.Current;
- context.Items.Remove(HttpContextSessionStorageKey);
- }
- }
-}
+ using System;
+ using System.Collections.Generic;
+ using System.Web;
+
+ using global::NHibernate;
+
+ using SharpArch.Data.NHibernate;
+
+ public class WebSessionStorage : ISessionStorage
+ {
+ private const string HttpContextSessionStorageKey = "HttpContextSessionStorageKey";
+
+ public WebSessionStorage(HttpApplication app)
+ {
+ app.EndRequest += Application_EndRequest;
+ }
+
+ public IEnumerable<ISession> GetAllSessions()
+ {
+ var storage = GetSimpleSessionStorage();
+ return storage.GetAllSessions();
+ }
+
+ public ISession GetSessionForKey(string factoryKey)
+ {
+ var storage = GetSimpleSessionStorage();
+ return storage.GetSessionForKey(factoryKey);
+ }
+
+ public void SetSessionForKey(string factoryKey, ISession session)
+ {
+ var storage = GetSimpleSessionStorage();
+ storage.SetSessionForKey(factoryKey, session);
+ }
+
+ private static void Application_EndRequest(object sender, EventArgs e)
+ {
+ NHibernateSession.CloseAllSessions();
+
+ var context = HttpContext.Current;
+ context.Items.Remove(HttpContextSessionStorageKey);
+ }
+
+ private static SimpleSessionStorage GetSimpleSessionStorage()
+ {
+ var context = HttpContext.Current;
+ var storage = context.Items[HttpContextSessionStorageKey] as SimpleSessionStorage;
+ if (storage == null)
+ {
+ storage = new SimpleSessionStorage();
+ context.Items[HttpContextSessionStorageKey] = storage;
+ }
+
+ return storage;
+ }
+ }
+}
View
2 Solutions/SharpArch/SharpArch.Web/Properties/AssemblyInfo.cs
@@ -1,5 +1,5 @@
-using System.Reflection;
using System;
+using System.Reflection;
[assembly: AssemblyTitle("SharpArch.Web")]
[assembly: AssemblyDescription("")]

0 comments on commit 85e2886

Please sign in to comment.
Something went wrong with that request. Please try again.