Create custom validation attributes c# server side - c#

I'm trying to create Validation Attribute to enforce licensing in my solution.
The way I've tried to do it is using by LicenseValidationAttribute that inherits from ValidationAttribute.
The main goal is when CreateProject() method is called, if the customer already reached the limit of projects he is entitled for, that will lead to exception throwing. else, that will be OK flow.
I've write a small program but unfortunately it doesn't work, means it doesn't throws exception.
The program:
[AttributeUsage(AttributeTargets.Method)]
public class MyValidationAttribute : ValidationAttribute
{
public MyValidationAttribute()
{
}
public override bool IsValid(object value)
{
int id = (int)value;
if (id > 0)
return true;
throw new Exception("Error");
}
}
public class Service
{
[MyValidation]
public bool GetService(int id)
{
if (id > 100)
{
return true;
}
return false;
}
}
static void Main(string[] args)
{
try
{
Service service = new Service();
service.GetService(-8);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
}
Thanks!

After adding System.reflection's GetCustomAttributes method call it works:
static void Main(string[] args)
{
try
{
Service service = new Service();
service.GetService(-8);
service.GetType().GetCustomAttributes(false);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
}

Related

Refactoring a WCF Trusted Facade

I'm attempting to refactor a "trusted facade" which currently wraps over 50 service calls to the backend. All calls have different signatures, but everything else is being repeated. The issue with the existing calls was that there was no attempt made to manage the connections, resulting in ephemeral ports remaining in the "BOUND" state.
ORIGINAL CODE:
public class ReportWeb : IReportWeb
{
ReportService.ReportClient client = new ReportClient();
...
public string[] GetAccounts() => client.GetAccounts();
}
NEW CODE:
private ChannelFactory<IReportService> _factory = null;
private IReportService _proxy = null;
private void OpenProxy()
{
_factory = new ChannelFactory<IReportService>("NetTcpBinding_IReportService");
_proxy = _factory.CreateChannel();
}
private void CloseProxy()
{
((IClientChannel)_proxy).Close();
_factory.Close();
}
One of 50+ similar methods:
public string[] GetAccounts() // Different - name, params, and return type
{
string[] accounts = null; // Different
try
{
OpenProxy();
accounts = _proxy.GetAccounts(); // Different
CloseProxy();
}
catch (Exception exception)
{
bool faulted = _factory.State == CommunicationState.Faulted;
_factory.Abort();
if (faulted)
{
throw new ApplicationException(exception.Message);
}
else
{
throw;
}
}
return accounts;
}
Another similar method:
//Another method
public ContractsInfo[] GetContracts(int contractId) // Different -
// name, params, and return type
{
ContractsInfo[] contracts = null; // Different
try
{
OpenProxy();
contracts = _proxy.GetContracts(contractId); // Different
CloseProxy();
}
catch (Exception exception)
{
bool faulted = _factory.State == CommunicationState.Faulted;
_factory.Abort();
if (faulted)
{
throw new ApplicationException(exception.Message);
}
else
{
throw;
}
}
return contracts;
}
Calling code from Web Forms project:
public string[] GetAccounts()
{
ReportClient client = NewReportClient();
string[] results = null;
try
{
results = client.GetAccounts();
client.Close();
}
catch (Exception ex)
{
client.Abort();
throw ex;
}
return results;
}
There are over fifty other methods like GetData() with different signatures. They will all be identical except for the service call in each, which will vary in params and return type. I need a more abstract, or generic, way of coding this and thus adhere to the DRY principle. Would Func<T, TResult> Delegate be appropriate here? Either way, can someone suggest a best approach here with some stub code to illustrate?
I suppose that this is the case where Generic method with can be applied. It is
possible to read about Generics here
Let me show a code example:
public class Foo
{
public T GetDate<T, UArg>(UArg arg) where T : new()
{
return new T();
}
}

Does method overload work with exception types?

using System;
// Custom Exception types
class AException : Exception
{
}
class BException : Exception
{
}
class Test
{
public static void Main(string[] args)
{
try
{
throw new AException();
}
catch (Exception ex)
{
Callme(ex);
}
}
public static void Callme(AException aexception) {}
public static void Callme(BException bexception) {}
public static void Callme(Exception ex) {}
}
Callme(ex) will always call Callme(Exception ex) instead of Callme(AException ..) .. Is this an expected behavior. I read method overload resolution do work with inheritance relationships.
there is a more accepted way of doing this. try the following:
try
{
throw new AException();
}
catch (AException aex)
{
Callme(aex);
}
catch (BException bex)
{
Callme(bex);
}
catch (Exception ex)
{
Callme(ex);
}

Design pattern for handling if else with different implementations

I have the following two types of processors
public interface IDefaultProcessor1
{
void Process(IProcess p);
}
public interface IDefaultProcessor2
{
T Process<T>(IProcess p);
}
public class DefaultProcessor : IDefaultProcessor1
{
public void Process(IProcess p)
{
try
{
foreach ...
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
public class AnotherProcessor : IDefaultProcessor2
{
public T Process<T>(IProcess p)
{
try
{
foreach ...
return p.Result()...
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
Most of the implementation code is exactly the same (error checking etc) except one returns a value. Is there a pattern to clean this up?
Yes, there is.
Define both methods on the same interface:
public interface IDefaultProcessor
{
void Process(IProcess p);
TResult Process<TResult>(IProcess p);
}
And then:
public class DefaultProcessor : IDefaultProcessor
{
public void Process(IProcess p)
{
DoProcess(p);
}
public TResult Process<TResult>(IProcess p)
{
object result = DoProcess(p);
return (TResult)result;
}
private object DoProcess(IProcess p)
{
try
{
foreach ...
return p.Result();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
There are many ways you can do this. One thing you have to keep in mind is that there is no way you can have a method with a optional return. That been said, you can try one of the aproaches below:
Implement Template Pattern and return null to your process that don't return anything:
public abstract class AbstractProcess<T>
{
public abstract T DoProcess();
public T Process()
{
//do your common tasks
return DoProcess();
}
}
public class Process1 : AbstractProcess<Process1>
{
public override Process1 DoProcess()
{
return new Process1();
}
}
public class Process2 : AbstractProcess<Process2>
{
public override Process2 DoProcess()
{
return null;
}
}
Create an Interface with both methods, and then choose what is the best method to call (as pointed by Matias CĂ­cero)
public interface IProcessor
{
T Process<T>();
void Process();
}
public class Processor : IProcessor
{
public void Process()
{
DoWork();
}
public T Process<T>()
{
return (T)DoWork();
}
public object DoWork()
{
// do your common tasks
}
}
Create an Interface with a single method and decide if you will return something (or null) based on the type:
public interface IProcessor
{
T Process<T>() where T : class;
}
public class Processor : IProcessor
{
public T Process<T>() where T : class
{
var result = (T)DoWork();
if (typeof(T) == typeof(Process2))
return result;
return null;
}
public object DoWork()
{
// do your common tasks
}
}

Post sharp using instance member

I am attempting to create an aspect to manage security on a few properties of a class. However, the security aspect for one member relies on the data in another property of the class. I've read some tutorials on the IntroduceAspect, but I'm not sure it's what I need.
public class ClassWithThingsIWantToSecure
{
[SecurityAspectHere(inherits from LocationInterceptionAspect)]
public int ThingIWantToSecure;
public string ThingINeedToKnowAboutInSecurityAspect;
}
Can someone point me in the right direction for making the runtime value of ThingINeedToKnowAboutInSecurityAspect available in the SecurityAspect?
I have done something a bit like this before, I've knocked up a test on a machine with postsharp installed and just tried it out, here is the code...
class Program
{
static void Main(string[] args)
{
Baldrick baldrick = new Baldrick();
baldrick.ThingINeedToKnowAboutInSecurityAspect = "Bob";
Console.WriteLine("There are {0} beans", baldrick.ThingIWantToSecure);
baldrick.ThingINeedToKnowAboutInSecurityAspect = "Kate";
try
{
//This should fail
Console.WriteLine("There are {0} beans", baldrick.ThingIWantToSecure);
}
catch (Exception ex)
{
//Expect the message from my invalid operation exception to be written out (Use your own exception if you prefer)
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
[Serializable]
public class SecurityAspect : LocationInterceptionAspect
{
public override void OnGetValue(LocationInterceptionArgs args)
{
ISecurityProvider securityProvider = args.Instance as ISecurityProvider;
if (securityProvider != null && securityProvider.ThingINeedToKnowAboutInSecurityAspect != "Bob")
throw new InvalidOperationException("Access denied (or a better message would be nice!)");
base.OnGetValue(args);
}
}
public interface ISecurityProvider
{
string ThingINeedToKnowAboutInSecurityAspect { get; }
}
public class Baldrick : ISecurityProvider
{
public string ThingINeedToKnowAboutInSecurityAspect { get; set; }
[SecurityAspect]
public int ThingIWantToSecure{get { return 3; }}
}
So, the idea here is to interrogate the args.Instance property for the instace of the object that is being decorated.

How to do unit test a service which has wcf client called

public class RefDataProvider : IRefDataProvider
{
private const string REF_DATA_COUNTRIES = "CountryData";
public IEnumerable<CountryLookupDto> GetCountries()
{
//if in cache then get cached version
if (CacheManager.GetInstance.OCache.Contains(REF_DATA_COUNTRIES))
return CacheManager.GetInstance.GetTypedItem<IEnumerable<CountryLookupDto>>(REF_DATA_COUNTRIES);
//not in cache so get from dadtavase
using (var service = new CrmServiceClient())
{
try
{
IEnumerable<CountryLookupDto> countriesDto = service.LookupCountries("*");
bool addedToCache = CacheManager.GetInstance.AddItemWithExpiration(REF_DATA_COUNTRIES, countriesDto,
12);
if (!addedToCache) throw new Exception("Cannot add ref data to cache");
}
catch (Exception ex)
{
LoggingManager.GetInstance.Log("Error", ex, LoggingManager.LogLevel.Error);
throw;
}
finally
{
service.Close();
}
}
return CacheManager.GetInstance.GetTypedItem<IEnumerable<CountryLookupDto>>(REF_DATA_COUNTRIES);
}
}
Trying to do unit test onto the method. Having problem with wcf client call.
I am trying to verify CrmServiceClient() calls in unit test. Is there any way to test wcf calls in unit test. Please advise.
[TestFixture]
public class TestRefDataProvider
{
private IReferenceDataProvider _referenceDataProvider;
[SetUp]
public void SetUp()
{
_referenceDataProvider = new ReferenceDataProvider();
}
[Test]
public void Verify_GetCountries()
{
Assert.IsNotNull(_referenceDataProvider.GetCountries());
}
}
Thanks Ilya. After Ilya explains: I came out with this:
public class ReferenceDataProvider : IReferenceDataProvider
{
private const string REF_DATA_TITLE = "TitleData";
private const string REF_DATA_COUNTRIES = "CountryData";
private readonly ICrmService _crmService;
public ReferenceDataProvider(ICrmService crmService)
{
_crmService = crmService;
}
public IEnumerable<CountryLookupDto> GetCountries()
{
//if in cache then get cached version
if (CacheManager.GetInstance.OCache.Contains(REF_DATA_COUNTRIES))
return CacheManager.GetInstance.GetTypedItem<IEnumerable<CountryLookupDto>>(REF_DATA_COUNTRIES);
try
{
IEnumerable<CountryLookupDto> countriesDto = _crmService.LookupCountries("*");
bool addedToCache = CacheManager.GetInstance.AddItemWithExpiration(REF_DATA_COUNTRIES, countriesDto,
12);
if (!addedToCache) throw new Exception("Cannot add ref data to cache");
}
catch (Exception ex)
{
LoggingManager.GetInstance.Log("Error", ex, LoggingManager.LogLevel.Error);
throw;
}
return CacheManager.GetInstance.GetTypedItem<IEnumerable<CountryLookupDto>>(REF_DATA_COUNTRIES);
}
}
My question here is I had service.Close() before. Now I can't use it. Is that safe ?
If CrmServiceClient is your WCF service so you should have an interface ICrmServiceClient.
Therefore you should not create new instance of CrmServiceClient in your code. The only thing your need is a dependency on ICrmServiceClient (e.g. via constructor)
public class RefDataProvider : IRefDataProvider
{
private readonly ICrmServiceClient crmServiceClient;
public RefDataProvider(ICrmServiceClient crmServiceClient)
{
this.crmServiceClient = crmServiceClient;
}
public IEnumerable<CountryLookupDto> GetCountries()
{
/* your code */
}
}
In this case it is possible to inject mock ok ICrmServiceClient easily.
[TestFixture]
public class TestRefDataProvider
{
private Mock<ICrmServiceClient> crmServiceClientMock;
private IReferenceDataProvider _referenceDataProvider;
[SetUp]
public void SetUp()
{
crmServiceClientMock = new Mock<ICrmServiceClient>();
crmServiceClientMock
.Setuo(/* your code */)
.Returns(/* your code */);
_referenceDataProvider = new ReferenceDataProvider(
crmServiceClientMock.Object
);
}
}
MOQ framework is used in order to mock dependencies.

Categories