i probably dont have the right words but i have tried my best.
say i have a function in c# such as DoWork and within that function i want to call another function such as CheckScore(). However, CheckScore() is a generic function that i want to call from multiple places.
So in my class when i create another function DoWork2, DoWork3 is there any way i can execure CheckScore() as the first line instead of typing those everytime?
For eg. can i avoid
string DoWork2(){
CheckScore()
}
Instead just have
string DoWork2(){}
but CheckScore() is executed anyways?
One potential, though still not foolproof, method is to abstract your security checks into Attributes. This way you can decorate your methods with something like:
[CheckToken]
public string DoWork() {
....
}
This isn't necessarily the best answer because it still requires you to attribute the method. You could instead create an attribute for your web service class, which would execute the [CheckToken] on any method call of the class.
[CheckToken]
public class MyWebService {
...
}
The only issue here is if you have some methods where you want to execute different security checks, or no security checks.
A C# web service framework that has pretty good security features baked into the framework is Service Stack. http://www.servicestack.net/ It has security attributes already built in that you can use, and it promotes clean separation of concerns.
Another very robust option involves intercepting method calls. C# has a class "ContextBoundObject" which can be used for this purpose. You'd need to have your class inherit from ContextBoundObject, and then you can start to dynamically intercept method calls and perform your security checking based upon the context of the method call being made and its parameters. ContextBoundObject does add some overhead to your calls, so you'll need to factor that into your decision. Method interception is great for things like security, performance monitoring, health checks, method retries, and other cross cutting concerns.
Here's a simple getting-started article on ContextBoundObject (and Aspect Oriented Programming). http://www.codeproject.com/Articles/8414/The-simplest-AOP-scenario-in-C
For J...
I wouldn't have the method code query the result. Since we're talking about a web service, there's a pipeline involved where a request is initiated by a client, that request is sent to the service, that service initializes its handlers, deserializes the request, routes the request to the appropriate method, executes the method, serializes the response, and returns the response to the client (this is a big simplification..). Most frameworks I've seen have some hooks for you to specify attributes on your service methods that get checked at the point prior to method execution and can be used to handle security (ie, return a 401 http code for a web service). I believe he said he's using WCF and while it's been a while since I've used WCF, I know this can be done - see http://msdn.microsoft.com/en-us/library/ms733071.aspx
So he could derive his custom security attribute from some WCF security attribute and create his own authentication logic based upon some token, which he'd most likely have to grab from the headers of the request. ServiceStack makes this super easy, I'd imagine it's not that hard using WCF either. Chances are someone's already done this for WCF and the code is out there somewhere.
This may not be exactly what you are looking for, but I would associate the "CheckScore" with the getter for the property when the score is accessed. That way, when using the property it feels like you are not writing out the CheckScore a lot, and also you don't have a CheckScore function being called every time any old method is invoked in your application.
private int _score;
public int Score
{
get
{
CheckScore();
return _score;
}
}
public void DoWork1()
{
if (Score > 10) {
// Case 1
}
}
public void DoWork2()
{
if (Score < 20) {
// Case 2
}
}
Putting CheckScore in a property will still result in it being called a lot.
You could use a private readonly field and set it in the constructor. This will minimise the number of calls to CheckScore.
public class MyClass
{
private readonly int _score;
public MyClass()
{
_score = CheckScore();
}
public int Score
{
get
{
return _score;
}
}
public void DoWork1()
{
if (Score > 10) {
// Case 1
}
}
public void DoWork2()
{
if (Score < 20) {
// Case 2
}
}
}
Given the additional information in comments, one solution to this problem is to create a small class to encapsulate methods which require authentication :
abstract class AuthenticateClass
{
private bool AuthenticateUser(){
return true; // do your authentication
}
public int Perform(){
if (!AuthenticateUser()){
return -1;
} else
return AuthenticatedMethod();
}
protected abstract int AuthenticatedMethod();
}
This gives you a class that performs the authentication and, if successful, performs your method. Implement it like :
class SomeAuthentMethod : AuthenticateClass
{
protected override int AuthenticatedMethod()
{
return 10; // whatever method...
}
}
and use it like :
SomeAuthentMethod myMethod = new SomeAuthentMethod();
if (myMethod.Perform() = -1){
// unable to authenticate user, please log in, etc
}
If the authentication passes this returns 10, otherwise it returns -1 (authentication failed). This lets you generate any number of methods which automatically include authentication.
Alternatively, you might use a static class to do the authentication -- for example :
static class Authenticate
{
public delegate int MethodDelegate();
private static bool AuthenticateUser(){
return true; // do your authentication
}
public static int Perform(MethodDelegate MyMethod){
if (!AuthenticateUser())
{
return -1;
}
else return MyMethod();
}
}
Where you could then have :
private int myMethod(){
return 10; //whatever method...
}
and then implement like :
if (Authenticate.Perform(myMethod) = -1){
// unable to authenticate user, please log in, etc
}
Obviously you can extend both of these patterns to handle whatver "not logged in" or "not authenticated" action within the abstract or static class itself. This should, at least, provide a few ideas of how to approach the problem.
Related
So say we have loaded a function F that take in/out a set of args and returns a result. How to check at runtime if this F does not act on anything other than args members and functions? Meaning no Console.Writeline, Singletons (or other stuff not presented in args). Is it possible with CodeContracts library or some other solution?
Say we know that [Pure] attribute was presented in the function definition. This sucks for many cases when we have a lambda, yet at least it would be something
Why I do not see how [Pure] can help - this code compiles:
class Test {
public struct Message {
public string Data;
}
public struct Package {
public int Size;
}
[Pure]
public static List<Package> Decomposse(Message m) {
Console.WriteLine("rrrr"); // This sould not happen
var mtu = 1400;
Package p = new Package{Size = mtu};
return Enumerable.Repeat(p, m.Data.Length / mtu).ToList();
}
}
And I want to eliminate (or at least detect that function calls stuff like Console.WriteLine("rrrr"))
It doesn't matter if the function has inputs or a result. Too many things can happen in a code body, e.g. instantiated object constructors. The problem is the modern language.
What about safe API calls which just retrieve data like DateTime.Now()? Are you going to build a list of API calls which mutate state and keep it updated for the rest of us over time, for all applications in your organization or on earth? Are you going to document what processes the compiler inlines? Then by reducing this approach to absurdity, can we accept it is not feasible?
My architecture models machines which should only change "Product" data points, but even I admit this is an unenforceable rule. I have other rules as well to try to enforce determinism. However, these modules must make API calls at some point to do the meaningful work already organized in APIs today. Otherwise we would rewrite them all.
class Machine1Product
{
public Cvar<int> Y { get; set; }
}
class Machine1 : Producer<Machine1Product>, IMachine
{
public Cvar<int> X { get; set; }
public void M()
{
// work which changes only product data points (Y)
}
}
Until a minimalist language is developed for functions, there is no observing or preventing side effects.
I have a class from a third-party assembly (so I can't edit it):
public class MyClass
{
private bool _loggedIn;
public void Login() {_loggedIn = true;}
public void Logout() {
if (!_loggedIn) throw new InvalidOperationException();
_loggedIn = false;
}
}
Now, suppose I have an instance of MyClass (for which I don't know _loggedIn), and I need call LogOut. Which of the following methods of avoiding a fatal exception will generally be faster? (any other method would be fine too):
To call LogOut, and if _loggedIn == false, just catch the exception
To use reflection to check that _loggedIn == true, and only call LogOut if so
It depends on the invariants you expect to see in your application.
1. If you expect to have a lot of MyClass having different state(logged in, logged off), then it is better to avoid overhead of exception (because exception is Exceptional situation) and use some specific public IsLoggedIn property (obviously to avoid Reflection) or some TryXxxxx-like methods.
And even if you can't modify the original code no one stops you from wrapping it:
public class MyWrappedClass
{
public Boolean IsLoggedIn {get; private set;}
private MyClass m_Log;
public MyWrappedClass ()
{
this.m_Log = new MyClass();
this.IsLoggedIn = false;
}
public void Log()
{
try
{
this.m_Log.LogIn();
this.IsLoggedIn = true;
}
catch
{
this.IsLoggedIn = false;
}
}
public void LogOut()
{
try
{
this.m_Log.LogOut();
this.IsLoggedIn = false;
}
catch
{
this.IsLoggedIn = true;
}
}
}
You could even go further and implement IDisposable interface with it to avoid manual LogIn-LogOut management:
public class MyWrappedClass
{
private class LogSessionToken : IDisposable
{
private MyWrappedClass parent;
public LogSessionToken (MyWrappedClass parent)
{
parent.LogIn();
}
public void Dispose()
{
parent.LogOut();
}
}
public IDisposable LogSession()
{
return new LogSessionToken (this);
}
// ...
}
And use it like
using (var logToken = wrappedInstance.LogSession)
{
// do the work.
} // No need to worry about manual LogOut
2. If you expect to use only few of MyClass in a proper fashion, then it would be a better idea to not handle exception at all - if something wrong happened then it is some programming error thus the program shall be terminated.
First, if your class doesn't expose at least a read-only property for LoggedIn, there sounds like a fairly large design flaw.
For speed, using reflection will generally be faster, particularly if you cache the FieldInfo or build a Func<bool> using System.Linq.Expressions. This is because Exceptions collect lots of debug information when thrown, including a StackTrace, which can be expensive.
As with anything, though, it is often best to test such operations, as there are sometime optimizations or other factors that may surprise you.
If the pattern if (CanFoo) Foo(); appears very much, that tends to imply very strongly that either:
A properly-written client would know when it can or cannot call Foo. The fact that a client doesn't know suggest that it's probably deficient in other ways.
The class exposing CanFoo and Foo should also expose a method which will Foo if possible and appropriate (the method should throw if unable to establish expected post-conditions, but should return silently if the post-conditions were established before the call)
In cases where a class one does not control should provide such a method but doesn't, the cleanest approach may be to write one's own wrapper method whose semantics mirror those the missing method should have had. If a later version of the class implements the missing method, changing one's code to use that implementation may be easier than refactoring lots of if (CanFoo) constructs.
BTW, I would suggest that a properly-designed class should allow calling code to indicate whether it is expecting a transition from logged-in state to logged-out state, or whether it wants to end up in logged-out state but it doesn't care how it gets there. Both kinds of semantics have perfectly legitimate uses; in cases where the first kind would be appropriate, having a LogOut method throw an exception if called on a closed session would be a good thing, but in cases where client code merely wants to ensure that it is logged out, having an EnsureLoggedOut method that could be invoked unconditionally would be cleaner than having to add extra client-side code for that purpose.
I have the following code which executes in sequence, method after another.
I load the request, perform a couple of checks like checking if a response already exists for this request, if not, I call the service and receive the response which I save to the DB.
I was looking for a design pattern I can use in such a case, I thought of posting this here and get some ideas.
public class Manager
{
public void PutRequest()
{
//Do Something
if (loadRequest())
{
callService();
//Do Something
saveResponse();
}
}
private bool loadRequest()
{
bool isExist = checkIfResponseExists();
if (!isExist)
{
// If false, load request from DB
}
return !isExist;
}
private bool checkIfDataExists()
{
//Check if a response already exists in the DB for this request
}
private void callService()
{
//Call the service and receive the response
}
private void saveResponse()
{
//Store the response in the DB
}
}
Patterns are used for solving some problems. What problem your current code have? I don't see any duplicated code, beside names of methods. There is no pattern, which fixes method naming problem.
Yes, your code need some refactoring, but not to patterns. Better class and method naming is a first step. Also, I'd removed field isExist.
public class Manager
{
public void PutRequest()
{
//Do Something
if (!CheckIfResponseExists()) // returns boolean value
LoadRequestFromDB()
CallService();
//Do Something
SaveResponse();
}
}
Check the design pattern called Strategy, it defines an interface common to all supported algorithms and each concrete strategy implements an algorithm
http://www.oodesign.com/strategy-pattern.html
It seems like it'd be more useful for several of these methods to be functions. So instead of having a method who's responsibility is to both check for a condition and do some other actions, you have a function that checks for a condition then the method that called it does some action depending on the result. (Kind of the SRP applied to methods...)
public void DoAllTheThings!() // Oops, Ruby syntax creeping in :P
{
if(!WeCanDoIt())
{
MakeItSo(); // So that we can do it...
}
NowWeCanDoAllTheThings();
}
private bool WeCanDoIt() {}
private void MakeItSo() {}
private void NowWeCanDoAllTheThings() {}
Command + Composite.
Some people consider the use of an if/then Command - in your case that would be in putRequest - in a Composite a kind of Chain Of Responsibility.
While selecting a pattern you should consider scalability of the application
One of the pattern you can apply is state pattern
There will be two states.
Response is already there
Need to process the new response
I have two Methods in a WCF Service say
Method1()
{
_currentValue = 10;
}
Method2()
{
return _currentValue;
}
I have a situation in which, i need to set a value in Method1() and read it in Method2().
I tried using static variable like public static int _currentValue, i could able to read the value set in Method1() in Method2().
But the issue is, i want this variable to react like separate instance variable for each request made. i.e., right now below is the problem
Browser 1 :
- Method1() is called
=> sets _currentValue = 10;
- Method2() is called
=> returns _currentValue = 10;
Browser 2:
- Method2() is called
=> returns _currentValue = 10;
Actually the value set is Browser 1 is static, so in Browser 2
the same value is retrieved.
What i am trying to implement is the variable should act like a new instance for each request made (when calling from each browser). What should i use in this case? a session?
You're going to need some mechanism for correlation because you have two completely different sessions calling into different methods. So I would recommend using a private key that both callers know.
It is a bit impossible for me to know what that key can be because I can't really gather anything from your question, so only you know that, but the simple fact is you're going to need correlation. Now, once you determine what they can use you can do something like this.
public class SessionState
{
private Dictionary<string, int> Cache { get; set; }
public SessionState()
{
this.Cache = new Dictionary<string, int>();
}
public void SetCachedValue(string key, int val)
{
if (!this.Cache.ContainsKey(key))
{
this.Cache.Add(key, val);
}
else
{
this.Cache[key] = val;
}
}
public int GetCachedValue(string key)
{
if (!this.Cache.ContainsKey(key))
{
return -1;
}
return this.Cache[key];
}
}
public class Service1
{
private static sessionState = new SessionState();
public void Method1(string privateKey)
{
sessionState.SetCachedValue(privateKey, {some integer value});
}
public int Method2(string privateKey)
{
return sessionState.GetCachedValue(privateKey);
}
}
It sounds like you may need to use the per session instance context mode for the WCF service. This will allow you to maintain state on a per session basis, so member variables in the service instance will persist between method calls from the same proxy instance. Because each user has their own session, the state of the service instance will vary by user.
Check out this article for more information: http://msdn.microsoft.com/en-us/magazine/cc163590.aspx#S2
You have made your variable static, and this is what's causing the problem. static means that every instance of your class shares the variable, but all you really need is a variable declared outside of your methods, like this:
private int _currentValue;
Method1()
{
_currentValue = 10;
}
Method2()
{
return _currentValue;
}
This variable will be reated separately for each instance of your class - preserving this value between requests for a given user is a separate problem. (A session is one possible solution.)
WCF has provided three ways by which you can control WCF service instances:
Per call
Persession
Single instance
You will find the best solution by reading this
Three ways to do WCF instance management
Seems like an old thread but in case somebody is still interested, this can be achieved by just asking WCF to run a single instance of your service. Add the following line (decorator) to the definition of your class
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
If you want the behavior only for the same session but not across clients then you can mark it as per session by the following service behavior
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
The other option is per call which is the default option.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
Consider this code.
public class Class1
{
public void ThisShouldNotCompileBecauseOrderWasVoilated()
{
Call2();
Call1();
}
public void ThisShouldCompileBecauseProperOrderIsPresent()
{
Call1();
Call2();
}
private void Call1()
{
// some code
}
private void Call2()
{
// some more code
}
}
What code (or attribute) should I add in Call1()/Call2() which ensures that compiler complains for 1st method and passes for 2nd method. There will be some rule list which compiler will have to refer if order is not correct. In this example the rule list can say "Call1 Call2", meaning call Call1() before Call2()
This is for C# language for .NET 4.0
Thanks!
There's nothing within normal C# that you can specify for this.
You may be able to use something like NDepend to detect this, but I'm not sure.
You can create your own attribute and mark your methods using it. Then create an FXCop rule. FXCop fully integrates with your build process, and as long as both calls are taking place within the same method, the rule should be fairly easy to flesh out.
the compiler can't enforce method call ordering, since in many cases it cannot determine statically what the call order is. For example:
public void whichOrder(boolean b)
{
if (b) call1();
if (!b) call2();
if (b) call2();
if (!b) call1();
}
If it's necessary that the methods are called in the correct order, you have a few choices:
document the call order, so that callers know what to do. This doesn't enforce the order, but at least makes coders aware of it.
add state to your object to remember which method was called last, and validate the current called method is allowed next. This enforces the method check at runtime.
Use a mock framework (e.g. Moq) to unit test your clients. This checks at build time that the order is correct.
Which approach you choose depends on how critical the correct ordering is, and the consequences of calling the methods in the wrong order.
An alternative is to rework your design so that method ordering doesn't become an issue. For example, wrap both methods up in a third, call3() that invokes call1() and call2() in the correct order. Or perhaps, have call2() invoke call1() if it has not already been executed, and have call1() check if it's already run, and return silently if it doesn't need to run. If clients invoke call2() then call1(), you still internally get the effect of call1() first (from call2()'s internal call to call1()) and the client's call to call1() results in a no op.
E.g.
public void call3()
{
call1();
call2();
}
or
public void call2()
{
call1();
// rest of call2's logic
}
private boolean call1Called = false;
pubic void call1()
{
if (!call1Called)
{
call1Called=true;
call1Impl();
}
}
This is not exactly what you are asking ... but you could introduce another class:
public class Another1
{
public Another2 Call1()
{
// some code
return new Another2();
// could pass 'this' to Another2 constructor so it has all state
}
}
public class Another2
{
public void Call2()
{
// some more code
}
}
Now, starting from an instance of Another1 you can only do obj.Call1().Call2() and never obj.Call2().Call1(). Better yet, this enforcement is in the IDE as you type. Take a look at 'fluent' patterns also.