what would make the "this" clause different? - c#

I have the following code:
CustomerService service;
public CustomerService Service
{
get
{
if (this.service == null)
{
this.service = new CustomerService();
}
return this.service;
}
}
public DataTable GetCustomers()
{
return this.Service.GetCustomers();
}
Now the question is: if I wrote the above method as follow (without "this"), it's giving me an error : instance is not reference to an object.
public DataTable GetCustomers()
{
return Service.GetCustomers(); // this will spell the error "instance is not reference to an object"
}
Does anyone know? also it only happens while running via IIS and not from casini web server (VS 2010).

The presence or absence of this cannot explain the error you are witnessing. In this situation they mean exactly the same thing and will compile to the same IL code. Check the assembly using .NET Reflector to verify this if you wish. The error is occurring at random, probably due to a race condition.
One thing I can immediately see is that if you are running this code from multiple threads then it looks like you have a race condition here:
if (this.service == null)
{
this.service = new CustomerService();
}
return this.service;
In the multithreaded case you would need to lock otherwise you could get two CustomerService objects. I'm not sure if this explains your error, but it certainly could create confusion. Race conditions can occur in one environment but not in another as the frequency of the error can depend on the type of the hardware and on what other processes are running on the server.
You may also have other race conditions in the code you haven't posted. Don't use this lazy initialization technique without locking unless you are sure that you have only one thread.

You probably have a name conflict with another 'Service' (class or namespace). The use of this solves it.
I'm a bit skeptical about the difference between Cassinin and IIS, have you carefully checked that?

Something like this should be in a singleton. Which would resolve many issues like threading if implemented correctly and would make the implementation and readability of the code much better.
Thanks
-Blake Niemyjski (.netTiers team member)

I fiddled a bit with your code in Visual Studio and I couldn’t even get a name conflict to produce the error message you described. I can’t think of any case in which “this.X” can ever be different from “X” except when “X” is a local variable or a method parameter.

Would the CustomerService class derive from a base class called Service? If so, then that's the problem.

Related

Knowing in what part the method returned

Is it possible to get run-time information about where a method has returned?
I mean, if the method returned after running all its lines of code, or because of an earlier
return statement that occurred due to some condition.
The scenario is using interceptor for creating UnitOfWork that should exists in method scope.
For example, lets consider this code:
[UnitOfWork]
public void Foo()
{
// insert some values to the database, using repositories interfaces...
DoSomeChangesInTheDataBaseUsingRepositories();
var result = DoSomethingElse();
if (!result) return;
DoMoreLogicBecuseTheResultWasTrue();
}
I have interceptor class that opens thread static unit of work for methods that are flagged with [UnitOfWork] and when the scope of the method ends it run commit on the UoW and dispose it.
This is fine, but lets consider the scenario above, where for some reason a programmer decided to return in the middle of the method due to some condition, and in that scenario the changes made by the repositories should not be persisted.
I know that this can indicate wrong design of the method, but be aware that it is a possible scenario to be written by a programmer and I want to defend my database from these kind of scenarios.
Also, I don't want to add code to the method itself that will tell me where it ended. I want to infer by the method info somehow its returned point, and if it is not at the end of its scope the interceptor will know not to commit.
The simple answer is use BREAKPOINTS and Debugging.
Edit:- As mentioned by Mels in the comments. This could be a useful suggestion.
If your application is very timing-sensitive, set conditional breakpoints such that they never actually stop the flow of execution. They do keep track of Hit Count, which you can use to backtrace the flow of execution.
Just for your attention. From the microsoft site:-
For those out there who have experience debugging native C++ or VB6
code, you may have used a feature where function return values are
provided for you in the Autos window. Unfortunately, this
functionality does not exist for managed code. While you can work
around this issue by assigning the return values to a local variable,
this is not as convenient because it requires modifying your code. In
managed code, it’s a lot trickier to determine what the return value
of a function you’ve stepped over. We realized that we couldn’t do the
right thing consistently here and so we removed the feature rather
than give you incorrect results in the debugger. However, we want to
bring this back for you and our CLR and Debugger teams are looking at
a number potential solutions to this problem. Unfortunately this is
will not be part of Visual Studio 11.
There are a couple ways that normally indicate that a method exited early for some reason, one is to use the actual return value, if the value is a valid result that then your method probably finished correctly, if its another value then probably not, this is the pattern that most TryXXX methods follow
int i;
//returns false as wasn't able to complete
bool passed = int.TryParse("woo", out i);
the other is to catch/trhow an exception, if an exception is found, then the method did not complete as you'd expect
try
{
Method();
}
catch(Exception e)
{
//Something went wrong (e.StackTrace)
}
Note: Catching Exception is a bad idea, the correct exceptions should be caught, i.e NullReferenceException
EDIT:
In answer to your update, if your code is dependant on the success of your method you should change the return type to a boolean or otherwise, return false if unsuccessful
Generally you should use trace logs to watch you code flow if you cant debug it.
You could always do something like this:
private Tuple<int, MyClass> MyMethod()
{
if (condition)
{
return new Tuple<int, MyClass>(0,new MyClass());
}
else if(condition)
{
return new Tuple<int, MyClass>(1, new MyClass());
}
return new Tuple<int, MyClass>(2,new MyClass());
}
This way you´ll have an index of which return was returning your MyClass object. All depends on what you are trying to accomplish and why - which is at best unclear. As someone else mentioned - that is what return values are for.
I am curios to know what you are trying to do...

Sync Lock issue in Parallel.Foreach

I have worked with c# code for past 4 years, but recently I went through a scenario which I never pass through. I got a damn project to troubleshoot the "Index out of range error". The code looks crazy and all the unnecessary things were there but it's been in production for past 3 years I just need to fix this issue. Coming to the problem.
class FilterCondition
{
.....
public string DataSetName {get; set;}
public bool IsFilterMatch()
{
//somecode here
Dataset dsDataSet = FilterDataSources.GetDataSource(DataSetName); // Static class and Static collection
var filter = "columnname filtername"
//some code here
ds.defaultview.filter= filter;
var isvalid = ds.defaultView.rowcount > 0? true : false;
return isValid;
}
}
// from a out side function they put this in a parallel loop
Parallel.ForEach()
{
// at some point its calling
item.IsFiltermatch();
}
When I debug, dsDataSet I saw that dsDataSet is modified my multiple threads. That's why race condition happens and it failed to apply the filter and fails with index out of Range.
My question here is, my method is Non-static and thread safe, then how this race condition happening since dsDataset is a local variable inside my member function. Strange, I suspect something to do with Parallel.Foreach.
And when I put a normal lock over there issue got resolved, for that also I have no answer. Why should I put lock on a non-static member function?
Can anyone give me an answer for this. I am new to the group. if I am missing anything in the question please let me know. I can't copy the whole code since client restrictions there. Thanks for reading.
Because it's not thread safe.
You're accessing a static collection from multiple threads.
You have a misconception about local variables. Although the variable is local, it's pointing at an object which is not.
What you should do is add a lock around the places where you read and write to the static collection.
Problem: the problem lies within this call
FilterDataSources.GetDataSource(DataSetName);
Inside this method you are writing to a resource that is shared.
Solution:
You need to know which field is being written here and need to implement locking on it.
Note: If you could post your code for the above method we would be in a better position to help you.
I believe this is because of specific (not-stateless, not thread safe, etc) implementation of FilterDataSources.GetDataSource(DataSetName), even by a method call it seems this is a static method. This method can do different things even return cached DataSet instance, intercept calls to a data set items, return a DataSet wrapper so you are working with a wrapper not a data set, so a lot of stuff can be there. If you want to fine let's say "exact line of code" which causes this please show us implementation of GetDataSource() method and all underlying static context of FilterDataSource class (static fields, constructor, other static methods which are being called by GetDataSource() if such exists...)

Tell FxCop another method is calling dispose

Typically when you dispose a private member, you might do the following:
public void Dispose() {
var localInst = this.privateMember;
if (localInst != null) {
localInst.Dispose();
}
}
The purpose of the local assignment is to avoid a race condition where another thread might assign the private member to be null after the null check. In this case, I don't care if Dispose is called twice on the instance.
I use this pattern all the time so I wrote an extension method to do this:
public static void SafeDispose(this IDisposable disposable)
{
if (disposable != null)
{
// We also know disposable cannot be null here,
// even if the original reference is null.
disposable.Dispose();
}
}
And now in my class, I can just do this:
public void Dispose() {
this.privateMember.SafeDispose();
}
Problem is, FxCop has no idea I'm doing this and it gives me the CA2000: Dispose objects before losing scope warning in every case.
I don't want to turn off this rule and I don't want to suppress every case. Is there a way to hint to FxCop that this method is equivalent to Dispose as far as it's concerned?
The short answer is: there's no way to hint that the object is being disposed elsewhere.
A little bit of Reflector-ing (or dotPeek-ing, or whatever) explains why.
FxCop is in C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop. (Adjust accordingly for your OS/VS version combo.) Rules are in the Rules subdirectory.
In the main FxCop folder, open
Microsoft.VisualStudio.CodeAnalysis.dll
Microsoft.VisualStudio.CodeAnalysis.Phoenix.dll
phx.dll
In the Rules folder, open DataflowRules.dll.
In DataflowRules.dll find Phoenix.CodeAnalysis.DataflowRules.DisposeObjectsBeforeLosingScope. That's the actual class that does the evaluation.
Looking at the code in there, you can see two things of interest with respect to your question.
It uses a shared service called SharedNeedsDisposedAnalysis.
It derives from FunctionBodyRule.
The first item is interesting because SharedNeedsDisposedAnalysis is what determines which symbols need Dispose() called. It's pretty thorough, doing a "walk" through the code to determine what needs to be disposed and what actually gets disposed. It then keeps a table of those things for later use.
The second item is interesting because FunctionBodyRule rules evaluate the body of a single function. There are other rule types, like FunctionCallRule that evaluate things like function call members (e.g., ProvideCorrectArgumentsToFormattingMethods).
The point is, between the potential "miss" in that SharedNeedsDisposedAnalysis service where it may not be recursing through your method to see that things actually are getting disposed and the limitation of FunctionBodyRule not going beyond the function body, it's just not catching your extension.
This is the same reason "guard functions" like Guard.Against<ArgumentNullException>(arg) never get seen as validating the argument before you use it - FxCop will still tell you to check the argument for null even though that's what the "guard function" is doing.
You have basically two options.
Exclude issues or turn off the rule. There's no way it's going to do what you want.
Create a custom/derived rule that will understand extension methods. Use your custom rule in place of the default rule.
After having written custom FxCop rules myself, I'll let you know I found it... non-trivial. If you do go down that road, while the recommendation out in the world is to use the new Phoenix engine rule style (that's what the current DisposeObjectsBeforeLosingScope uses), I found it easier to understand the older/standard FxCop SDK rules (see FxCopSdk.dll in the main FxCop folder). Reflector will be a huge help in figuring out how to do that since there's pretty much zero doc on it. Look in the other assemblies in the Rules folder to see examples of those.
I am by no means an FxCop expert at all, but does this question about using SuppressMessage answer it? I don't know if decorating your SafeDispose method with the SuppressMessage attribute would cause FxCop to suppress that message on its analysis of the methods that call it, but seems like it's worth a shot.
Don't trust the syntax below, but something like:
[SuppressMessage("Microsoft.Design", "CA2000:Dispose objects before losing scope", Justification = "We just log the exception and return an HTTP code")]
public static void SafeDispose(this IDisposable disposable)
This code analysis rule is a problematic one, for all the reasons Travis outlined. It seems to queue off any "new" operation, and unless the dispose call is close, CA2000 triggers.
Instead of using new, call a method with this in the body:
MyDisposableClass result;
MyDisposableClass temp = null;
try
{
temp = new MyDisposableClass();
//do any initialization here
result = temp;
temp = null;
}
finally
{
if (temp != null) temp.Dispose();
}
return result;
What this does is remove any possibility of the initialization causing the object to be unreachable for disposal. In your case, when you "new up" privatemember, you would do it within a method that looks like the above method. After using this pattern, you are of course still responsible for correct disposal, and your extension method is a great way to generalize that null check.
I've found that you can avoid CA2000 while still passing IDisposables around and doing what you want with them - as long as you new them up correctly within a method like the above. Give it a try and let me know if it works for you. Good luck, and good question!
Other fixes for this rule (including this one) are outlined here: CA2000: Dispose objects before losing scope (Microsoft)

MonoTouch mysteriously not aot-compiling methods and properties?

I have a strange problem where MonoTouch seems to be either not compiling methods or not able to find a compiled method it is instructed to call, and only on the device in the Release configuration - Debug builds are fine. I've tried reproducing it with a simpler code sample with no luck, so I doubt you will be able to see the behavior with the code below. But this is essentially what I'm doing:
using System;
using MonoTouch.UIKit;
public class MyClass
{
private UINavigationController _navController;
private UIViewControler _viewController;
public UINavigationController NavController
{
get
{
if (_navController == null)
{
if (_viewController == null)
{
_viewController = new UIViewController();
}
_navController = new UINavigationController(_viewController);
}
return _navController;
}
}
}
Then, in some other method...
public void SomeMethod()
{
MyClass myClass = new MyClass();
var navController = myClass.NavController; // <-- This is where it throws
}
The exception I get is the standard JIT compile message, saying that it attempted to JIT get_NavController(). I find this very strange, because there's no virtual generics, no LINQ, the linker is off, and nothing else that normally causes JITs seems to be involved. I've also verified that it will throw for other methods and properties defined on MyClass, but not the constructor or System.Object inherited methods. Reflection reveals that myClass.GetType().GetMembers() has a MemberInfo for everything I would expect. Yet, only for Release|iPhone, I can't access these methods or properties. The only logical conclusion I can come to is that the aot compilation step is missing them, and I don't know why that would happen at all, let alone only in the Release configuration.
My question is, what could be causing such a situation, and what is the next step to fixing it? I'm not even sure where to go from here on debugging this, or what to file a bug about, because I can't reproduce it out of the context of our (much) larger project.
Update: The exact exception text was requested.
System.ExecutionException: Attempting to JIT compile method
'MyNamespace.MyClass.get_NavController ()' while running with --aot-only
This doesn't look like something that can be solved here.
I suggest filing a bug, and attach the entire project if you're unable to make a smaller test case. You can file private bugs only Xamarin employees have access to if you don't want your project to be publicly visible.
Could you try to explicitly declare the variable
UINavigationController navController = myClass.NavController;
Alternatively, I wonder if this is at all associated with needing to wait for the UIViewController.ViewDidLoad method to be called as the internals of the class may not yet have been initialized?
Just shots in the dark here, I can't think of a reason why your code wouldn't work.

How to enforce the use of a method's return value in C#?

I have a piece of software written with fluent syntax. The method chain has a definitive "ending", before which nothing useful is actually done in the code (think NBuilder, or Linq-to-SQL's query generation not actually hitting the database until we iterate over our objects with, say, ToList()).
The problem I am having is there is confusion among other developers about proper usage of the code. They are neglecting to call the "ending" method (thus never actually "doing anything")!
I am interested in enforcing the usage of the return value of some of my methods so that we can never "end the chain" without calling that "Finalize()" or "Save()" method that actually does the work.
Consider the following code:
//The "factory" class the user will be dealing with
public class FluentClass
{
//The entry point for this software
public IntermediateClass<T> Init<T>()
{
return new IntermediateClass<T>();
}
}
//The class that actually does the work
public class IntermediateClass<T>
{
private List<T> _values;
//The user cannot call this constructor
internal IntermediateClass<T>()
{
_values = new List<T>();
}
//Once generated, they can call "setup" methods such as this
public IntermediateClass<T> With(T value)
{
var instance = new IntermediateClass<T>() { _values = _values };
instance._values.Add(value);
return instance;
}
//Picture "lazy loading" - you have to call this method to
//actually do anything worthwhile
public void Save()
{
var itemCount = _values.Count();
. . . //save to database, write a log, do some real work
}
}
As you can see, proper usage of this code would be something like:
new FluentClass().Init<int>().With(-1).With(300).With(42).Save();
The problem is that people are using it this way (thinking it achieves the same as the above):
new FluentClass().Init<int>().With(-1).With(300).With(42);
So pervasive is this problem that, with entirely good intentions, another developer once actually changed the name of the "Init" method to indicate that THAT method was doing the "real work" of the software.
Logic errors like these are very difficult to spot, and, of course, it compiles, because it is perfectly acceptable to call a method with a return value and just "pretend" it returns void. Visual Studio doesn't care if you do this; your software will still compile and run (although in some cases I believe it throws a warning). This is a great feature to have, of course. Imagine a simple "InsertToDatabase" method that returns the ID of the new row as an integer - it is easy to see that there are some cases where we need that ID, and some cases where we could do without it.
In the case of this piece of software, there is definitively never any reason to eschew that "Save" function at the end of the method chain. It is a very specialized utility, and the only gain comes from the final step.
I want somebody's software to fail at the compiler level if they call "With()" and not "Save()".
It seems like an impossible task by traditional means - but that's why I come to you guys. Is there an Attribute I can use to prevent a method from being "cast to void" or some such?
Note: The alternate way of achieving this goal that has already been suggested to me is writing a suite of unit tests to enforce this rule, and using something like http://www.testdriven.net to bind them to the compiler. This is an acceptable solution, but I am hoping for something more elegant.
I don't know of a way to enforce this at a compiler level. It's often requested for objects which implement IDisposable as well, but isn't really enforceable.
One potential option which can help, however, is to set up your class, in DEBUG only, to have a finalizer that logs/throws/etc. if Save() was never called. This can help you discover these runtime problems while debugging instead of relying on searching the code, etc.
However, make sure that, in release mode, this is not used, as it will incur a performance overhead since the addition of an unnecessary finalizer is very bad on GC performance.
You could require specific methods to use a callback like so:
new FluentClass().Init<int>(x =>
{
x.Save(y =>
{
y.With(-1),
y.With(300)
});
});
The with method returns some specific object, and the only way to get that object is by calling x.Save(), which itself has a callback that lets you set up your indeterminate number of with statements. So the init takes something like this:
public T Init<T>(Func<MyInitInputType, MySaveResultType> initSetup)
I can think of three a few solutions, not ideal.
AIUI what you want is a function which is called when the temporary variable goes out of scope (as in, when it becomes available for garbage collection, but will probably not be garbage collected for some time yet). (See: The difference between a destructor and a finalizer?) This hypothetical function would say "if you've constructed a query in this object but not called save, produce an error". C++/CLI calls this RAII, and in C++/CLI there is a concept of a "destructor" when the object isn't used any more, and a "finaliser" which is called when it's finally garbage collected. Very confusingly, C# has only a so-called destructor, but this is only called by the garbage collector (it would be valid for the framework to call it earlier, as if it were partially cleaning the object immediately, but AFAIK it doesn't do anything like that). So what you would like is a C++/CLI destructor. Unfortunately, AIUI this maps onto the concept of IDisposable, which exposes a dispose() method which can be called when a C++/CLI destructor would be called, or when the C# destructor is called -- but AIUI you still have to call "dispose" manually, which defeats the point?
Refactor the interface slightly to convey the concept more accurately. Call the init function something like "prepareQuery" or "AAA" or "initRememberToCallSaveOrThisWontDoAnything". (The last is an exaggeration, but it might be necessary to make the point).
This is more of a social problem than a technical problem. The interface should make it easy to do the right thing, but programmers do have to know how to use code! Get all the programmers together. Explain simply once-and-for-all this simple fact. If necessary have them all sign a piece of paper saying they understand, and if they wilfully continue to write code which doesn't do anythign they're worse than useless to the company and will be fired.
Fiddle with the way the operators are chained, eg. have each of the intermediateClass functions assemble an aggregate intermediateclass object containing all of the parameters (you mostly do it this was already (?)) but require an init-like function of the original class to take that as an argument, rather than have them chained after it, and then you can have save and the other functions return two different class types (with essentially the same contents), and have init only accept a class of the correct type.
The fact that it's still a problem suggests that either your coworkers need a helpful reminder, or they're rather sub-par, or the interface wasn't very clear (perhaps its perfectly good, but the author didn't realise it wouldn't be clear if you only used it in passing rather than getting to know it), or you yourself have misunderstood the situation. A technical solution would be good, but you should probably think about why the problem occurred and how to communicate more clearly, probably asking someone senior's input.
After great deliberation and trial and error, it turns out that throwing an exception from the Finalize() method was not going to work for me. Apparently, you simply can't do that; the exception gets eaten up, because garbage collection operates non-deterministically. I was unable to get the software to call Dispose() automatically from the destructor either. Jack V.'s comment explains this well; here was the link he posted, for redundancy/emphasis:
The difference between a destructor and a finalizer?
Changing the syntax to use a callback was a clever way to make the behavior foolproof, but the agreed-upon syntax was fixed, and I had to work with it. Our company is all about fluent method chains. I was also a fan of the "out parameter" solution to be honest, but again, the bottom line is the method signatures simply could not change.
Helpful information about my particular problem includes the fact that my software is only ever to be run as part of a suite of unit tests - so efficiency is not a problem.
What I ended up doing was use Mono.Cecil to Reflect upon the Calling Assembly (the code calling into my software). Note that System.Reflection was insufficient for my purposes, because it cannot pinpoint method references, but I still needed(?) to use it to get the "calling assembly" itself (Mono.Cecil remains underdocumented, so it's possible I just need to get more familiar with it in order to do away with System.Reflection altogether; that remains to be seen....)
I placed the Mono.Cecil code in the Init() method, and the structure now looks something like:
public IntermediateClass<T> Init<T>()
{
ValidateUsage(Assembly.GetCallingAssembly());
return new IntermediateClass<T>();
}
void ValidateUsage(Assembly assembly)
{
// 1) Use Mono.Cecil to inspect the codebase inside the assembly
var assemblyLocation = assembly.CodeBase.Replace("file:///", "");
var monoCecilAssembly = AssemblyFactory.GetAssembly(assemblyLocation);
// 2) Retrieve the list of Instructions in the calling method
var methods = monoCecilAssembly.Modules...Types...Methods...Instructions
// (It's a little more complicated than that...
// if anybody would like more specific information on how I got this,
// let me know... I just didn't want to clutter up this post)
// 3) Those instructions refer to OpCodes and Operands....
// Defining "invalid method" as a method that calls "Init" but not "Save"
var methodCallingInit = method.Body.Instructions.Any
(instruction => instruction.OpCode.Name.Equals("callvirt")
&& instruction.Operand is IMethodReference
&& instruction.Operand.ToString.Equals(INITMETHODSIGNATURE);
var methodNotCallingSave = !method.Body.Instructions.Any
(instruction => instruction.OpCode.Name.Equals("callvirt")
&& instruction.Operand is IMethodReference
&& instruction.Operand.ToString.Equals(SAVEMETHODSIGNATURE);
var methodInvalid = methodCallingInit && methodNotCallingSave;
// Note: this is partially pseudocode;
// It doesn't 100% faithfully represent either Mono.Cecil's syntax or my own
// There are actually a lot of annoying casts involved, omitted for sanity
// 4) Obviously, if the method is invalid, throw
if (methodInvalid)
{
throw new Exception(String.Format("Bad developer! BAD! {0}", method.Name));
}
}
Trust me, the actual code is even uglier looking than my pseudocode.... :-)
But Mono.Cecil just might be my new favorite toy.
I now have a method that refuses to be run its main body unless the calling code "promises" to also call a second method afterwards. It's like a strange kind of code contract. I'm actually thinking about making this generic and reusable. Would any of you have a use for such a thing? Say, if it were an attribute?
What if you made it so Init and With don't return objects of type FluentClass? Have them return, e.g., UninitializedFluentClass which wraps a FluentClass object. Then calling .Save(0 on the UnitializedFluentClass object calls it on the wrapped FluentClass object and returns it. If they don't call Save they don't get a FluentClass object.
In Debug mode beside implementing IDisposable you can setup a timer that will throw a exception after 1 second if the resultmethod has not been called.
Use an out parameter! All the outs must be used.
Edit: I am not sure of it will help, tho...
It would break the fluent syntax.

Categories