Permalink
Browse files

getting postsharp code samples ready for Richmond

  • Loading branch information...
mgroves
mgroves committed May 19, 2011
1 parent 64cd208 commit 4be49f3f9823a18560f298281b7395f8be167900

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.
@@ -2,7 +2,7 @@
using System.Windows.Forms;
using PostSharp.Aspects;
-namespace WindowsFormsApplication1
+namespace LazyLoadingDependencies
{
public partial class ProductForm : Form
{
@@ -24,6 +24,33 @@ public ProductForm()
}
}
+ [Serializable]
+ public sealed class LoadDependencyAttribute : LocationInterceptionAspect
+ {
+ public override void OnGetValue(LocationInterceptionArgs args)
+ {
+ var form = (ProductForm)args.Instance; // this form is only used here to write to a listbox for demonstration
+
+ args.ProceedGetValue(); // this actually fetches the field and populates the args.Value
+ if (args.Value == null)
+ {
+ form.LogListBox.Items.Add("Instantiating ProductService");
+ var locationType = args.Location.LocationType;
+ var instantiation = ObjectFactory.GetInstance(locationType);
+
+ if (instantiation != null)
+ {
+ args.SetNewValue(instantiation);
+ }
+ args.ProceedGetValue();
+ }
+ else
+ {
+ form.LogListBox.Items.Add("Using a ProductService that has already been instantiated");
+ }
+ }
+ }
+
// this is just a "dummy" objectfactory
// use the IoC service locator of your choice (like StructureMap) instead
internal static class ObjectFactory
@@ -51,31 +78,4 @@ public string GetProductDescription(string productName)
return "Product: " + productName;
}
}
-
- [Serializable]
- public sealed class LoadDependencyAttribute : LocationInterceptionAspect
- {
- public override void OnGetValue(LocationInterceptionArgs args)
- {
- var form = (ProductForm) args.Instance; // this form is only used here to write to a listbox for demonstration
-
- args.ProceedGetValue(); // this actually fetches the field and populates the args.Value
- if (args.Value == null)
- {
- form.LogListBox.Items.Add("Instantiating ProductService");
- var locationType = args.Location.LocationType;
- var instantiation = ObjectFactory.GetInstance(locationType);
-
- if (instantiation != null)
- {
- args.SetNewValue(instantiation);
- }
- args.ProceedGetValue();
- }
- else
- {
- form.LogListBox.Items.Add("Using a ProductService that has already been instantiated");
- }
- }
- }
}
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
+using LazyLoadingDependencies;
namespace WindowsFormsApplication1
{
@@ -1,19 +1,25 @@
using System;
-using System.Collections.Generic;
+using System.Collections;
using System.Windows.Forms;
using PostSharp.Aspects;
using PostSharp.Extensibility;
+using PostSharp.Reflection;
using Message = PostSharp.Extensibility.Message;
namespace LazyLoading_CompileTimeInitialize
{
public partial class UserForm : Form
{
- [LazyLoad]
- private IUserService _userService;
+ [LoadDependency] private IUserService _userService;
+
+ // a non-interface
+ //[LoadDependency] DateTime invalidDependency1;
+
+ // an interface with no defined mapping
+ //[LoadDependency] IEnumerable invalidDependency2;
// I'm making this a public property only so that
- // the LazyLoadAttribute can write to it for demonstration purposes
+ // the LoadDependency can write to it for demonstration purposes
public ListBox LogListBox { get { return _logListBox; } }
public UserForm()
@@ -28,36 +34,20 @@ public UserForm()
}
}
- // another "dummy" interface and service
- // plug in your own real services/interfaces
- public interface IUserService
- {
- string AuthenticateUser(string username, string password);
- }
-
- public class UserService : IUserService
- {
- public string AuthenticateUser(string username, string password)
- {
- var r = new Random(DateTime.Now.Millisecond);
- return username + " was logged in: " + (r.NextDouble() < 0.5);
- }
- }
-
[Serializable]
- public sealed class LazyLoadAttribute : LocationInterceptionAspect
+ public sealed class LoadDependency : LocationInterceptionAspect
{
private Type _type;
- public override bool CompileTimeValidate(PostSharp.Reflection.LocationInfo locationInfo)
+ public override bool CompileTimeValidate(LocationInfo locationInfo)
{
if (!locationInfo.LocationType.IsInterface)
{
- Message.Write(SeverityType.Error, "001", "LazyLoad can only be used on Interfaces in {0}.{1}", locationInfo.DeclaringType, locationInfo.Name);
+ Message.Write(SeverityType.Error, "001", "LoadDependency can only be used on Interfaces in {0}.{1}", locationInfo.DeclaringType, locationInfo.Name);
return false;
}
- _type = DependencyMap.GetConcreteType(locationInfo.LocationType);
+ _type = ObjectFactory.GetInstanceType(locationInfo.LocationType);
if (_type == null)
{
Message.Write(SeverityType.Error, "002", "A concrete type was not found for {0}.{1}", locationInfo.DeclaringType, locationInfo.Name);
@@ -84,21 +74,42 @@ public override void OnGetValue(LocationInterceptionArgs args)
}
}
- // this DependencyMap only contains one interface<->dependency mapping
- // but more can be easily added
- public static class DependencyMap
+ // this is just a "dummy" objectfactory
+ // use the IoC service locator of your choice (like StructureMap) instead
+ internal static class ObjectFactory
{
- public static Type GetConcreteType(Type locationType)
+ public static Type GetInstanceType(Type locationType)
{
- var dict = new Dictionary<Type, Type>();
- // dict.Add(interface type, dependency type)
- dict.Add(typeof(IUserService), typeof(UserService));
-
- if (dict.ContainsKey(locationType))
+ // note that this is a very silly service locator
+ // since it returns a ProductRepository no matter
+ // what Type is passed in
+ if (locationType == typeof(IUserService))
{
- return dict[locationType];
+ return typeof(UserService);
}
return null;
}
}
+
+ // another "dummy" interface and service
+ // plug in your own real services/interfaces
+ public interface IUserService
+ {
+ string AuthenticateUser(string username, string password);
+ }
+
+ public class UserService : IUserService
+ {
+ private readonly Random _rand;
+
+ public UserService()
+ {
+ _rand = new Random(DateTime.Now.Millisecond);
+ }
+
+ public string AuthenticateUser(string username, string password)
+ {
+ return username + " was logged in: " + (_rand.NextDouble() < 0.5);
+ }
+ }
}
View
@@ -11,7 +11,8 @@ public string GetCurrentUsername()
public bool CurrentUserHasPermission(GovtForm singleForm, Permission permission)
{
- return singleForm.UserName == GetCurrentUsername();
+ var currentUser = GetCurrentUsername();
+ return singleForm.UserName == currentUser;
}
}
}
@@ -23,9 +23,9 @@ public override void OnSuccess(MethodExecutionArgs args)
var singleForm = args.ReturnValue as GovtForm;
if (singleForm != null)
{
- if(Auth.CurrentUserHasPermission(singleForm, Permission.Read))
+ if(!Auth.CurrentUserHasPermission(singleForm, Permission.Read))
{
- MessageBox.Show("You are not authorized to view the details of that form", "Authorization Denied!");
+ MessageBox.Show("You are not authorized to view the details of that form.", "Authorization Denied!");
args.ReturnValue = null;
}
return;
@@ -15,6 +15,7 @@ public GovtFormService()
_govtFormsDatabase.Add(new GovtForm { FormInformation = "steve smith's form details", UserName = "ssmith"});
_govtFormsDatabase.Add(new GovtForm { FormInformation = "text of Susie Q's form information and details", UserName = "susieq"});
_govtFormsDatabase.Add(new GovtForm { FormInformation = "Walter Mathau's form information details", UserName = "wmathau" });
+ _govtFormsDatabase.Add(new GovtForm { FormInformation = "Ali Groves's form information details", UserName = "agroves" });
}
public void SubmitForm(GovtForm form)
@@ -29,7 +30,7 @@ public IEnumerable<GovtForm> GetAllForms()
return _govtFormsDatabase;
}
- [AuthorizeReturnValue]
+ //[AuthorizeReturnValue]
public GovtForm GetFormById(Guid guid)
{
return _govtFormsDatabase.FirstOrDefault(form => form.FormId == guid);
@@ -15,6 +15,13 @@ public MainGovernmentForm()
InitializeComponent();
RefreshGovtForms();
+
+ PutCurrentUserNameInTitleBar();
+ }
+
+ void PutCurrentUserNameInTitleBar()
+ {
+ this.Text = "You are logged in as: " + Auth.GetCurrentUsername();
}
private void RefreshGovtForms()
@@ -19,7 +19,6 @@ private void depositButton_Click(object sender, EventArgs e)
RefreshBalance();
}
- [TransactionAudit]
private void withdrawlButton_Click(object sender, EventArgs e)
{
BankAccount.Withdrawl(decimal.Parse(this.amountTextbox.Text));
@@ -12,17 +12,6 @@ public class TransactionAuditAttribute : OnMethodBoundaryAspect
private Type _className;
private int _amountParameterIndex = -1;
- public override bool CompileTimeValidate(MethodBase method)
- {
- if(_amountParameterIndex == -1)
- {
- Message.Write(SeverityType.Warning, "999",
- "TransactionAudit was unable to find an 'amount' to audit in {0}.{1}", _className, _methodName);
- return false;
- }
- return true;
- }
-
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
_methodName = method.Name;
@@ -38,6 +27,17 @@ public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectI
}
}
+ public override bool CompileTimeValidate(MethodBase method)
+ {
+ if (_amountParameterIndex == -1)
+ {
+ Message.Write(SeverityType.Warning, "999",
+ "TransactionAudit was unable to find an 'amount' to audit in {0}.{1}", _className, _methodName);
+ return false;
+ }
+ return true;
+ }
+
public override void OnEntry(MethodExecutionArgs args)
{
if (_amountParameterIndex != -1)
@@ -27,11 +27,6 @@ static CacheAttribute()
}
}
- public override void RuntimeInitialize(MethodBase method)
- {
- syncRoot = new object();
- }
-
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
_methodName = method.Name;
@@ -55,15 +50,9 @@ public override bool CompileTimeValidate(MethodBase method)
return true;
}
- private static readonly IList<Type> DisallowedTypes = new List<Type>
- {
- typeof (Stream),
- typeof (IEnumerable),
- typeof (IQueryable)
- };
- private static bool IsDisallowedCacheReturnType(Type returnType)
+ public override void RuntimeInitialize(MethodBase method)
{
- return DisallowedTypes.Any(t => t.IsAssignableFrom(returnType));
+ syncRoot = new object();
}
public override void OnInvoke(MethodInterceptionArgs args)
@@ -101,5 +90,16 @@ private string BuildCacheKey(Arguments arguments)
}
return sb.ToString();
}
+
+ private static readonly IList<Type> DisallowedTypes = new List<Type>
+ {
+ typeof (Stream),
+ typeof (IEnumerable),
+ typeof (IQueryable)
+ };
+ private static bool IsDisallowedCacheReturnType(Type returnType)
+ {
+ return DisallowedTypes.Any(t => t.IsAssignableFrom(returnType));
+ }
}
}
@@ -63,7 +63,6 @@
<Compile Include="LogService.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="TransactionBoundaryScopeAttribute.cs" />
<Compile Include="TransactionScopeAttribute.cs" />
<EmbeddedResource Include="CharityManager.resx">
<DependentUpon>CharityManager.cs</DependentUpon>
@@ -9,11 +9,13 @@ public class CharityService : ICharityService
{
private ILogService _logService;
private readonly IList<Charity> _charityDatabase;
+ private Random _rand;
public CharityService()
{
_charityDatabase = PreprogrammedCharities.ToList();
_logService = new LogService();
+ _rand = new Random(DateTime.Now.Millisecond);
}
// since we're not hooked up to a real data layer, these are just standins for demonstration
@@ -46,9 +48,9 @@ public void UpdateACharity()
_charityDatabase[0].Name = PreprogrammedCharities.First().Name + " " + DateTime.Now.Millisecond;
}
- private static void SimulateUnreliableService()
+ private void SimulateUnreliableService()
{
- var rand = (new Random(DateTime.Now.Millisecond)).Next(0, 50);
+ var rand = (_rand.Next(0, 50));
if (rand == 2)
{
throw new Exception("Some unknown exception");
Oops, something went wrong.

0 comments on commit 4be49f3

Please sign in to comment.