I'm having a little bit of trouble understanding what the problem is here. I have a bit of code that pulls records from a database using LINQ and puts them into an object which is cast into an interface. It looks a bit like this:
public IEnumerable<ISomeObject> query()
{
return from a in dc.SomeTable
select new SomeObject
{
//Assign various members here
} as ISomeObject;
}
When I test this, I put the returned IEnumerable into a variable called results and run this line:
Assert.AreEqual(EXPECTED_COUNT, results.Count());
When this is run, I get a System.Security.VerificationException: "Operation could destabilize the runtime."
I found the solution here, which is this:
var results = from a in dc.SomeTable
select new SomeObject
{
//Assign various members here
} as ISomeTable;
return results.OfType<ISomeObject>();
This works, but I'm having trouble understanding what's happening here. Why did I get the exception in the first place and how did the lines of code above fix it? The MSDN documentation seems to suggest that this is an issue of type safety, but I'm not seeing where the previous code was type-unsafe.
UPDATE
A little bit more information I found out. The first example works if I make the return type IQueryable. This sheds a little bit more light on what was going wrong, but I'm still confused about the why. Why didn't the compiler force me to cast the IEnumerable into an IQueryable?
I believe it is an issue of covariance or contravariance as noted by this forum post.
See Covariance and Contravariance in C#, Part Two: Array Covariance and the rest of the Covariance and Contravariance series at Eric Lippert's blog.
Although he is dealing with Arrays in the article I linked, I believe a similar problem presents itself here. With your first example, you are returning an IEnumerable that could contain objects that implement an interface that is larger than ISomeTable (i.e. - you could put a Turtle into an Animals IEnumerable when that IEnumerable can only contain Giraffes). I think the reason it works when you return IQueryable is because that is larger/wider than anything you could return, so you're guaranteed that what you return you will be able to handle(?).
In the second example, OfType is ensuring that what gets returned is an object that stores all the information necessary to return only those elements that can be cast to Giraffe.
I'm pretty sure it has something to do with the issues of type safety outlined above, but as Eric Lippert says Higher Order Functions Hurt My Brain and I am having trouble expressing precisely why this is a co/contravariant issue.
I found this entry while looking for my own solution to "operation could destabilize the runtime". While the covariance/contra-variance advice above looks very interesting, in the end I found that I get the same error message by running my unit tests with code coverage turned on and the AllowPartiallyTrustedCallers assembly attribute set.
Removing the AllowPartiallyTrustedCallers attribute caused my tests to run fine. I could also turn off code coverage to make them run but that was not an acceptable solution.
Hopefully this helps someone else who makes it to this page trying to find a solution to this issue.
Just a guess, but the as operator may return a null - so it may have to do with the actual implementation of the new SomeObject { ... } code, since it's syntactic sugar. The return results.OfType<ISomeTable>(); filters based on type, so your method's return statement will only return that type (ensuring type safety). I've run into a similar issue with returning generic types.
P.S. I love the "Operation could destabilize the runtime." exception. That's almost like the "You might blow up the internet" exception.
I came across this error with similar code;
IEnumerable<Table> records = (from t in db.Tables
where t.Id.Equals(1)
select t).ToList();
This seemingly harmless code was part of a UserControl method which was called from a Page. No problem in a .NET4 development environment, however, when the site was PreCompiled and deployed to the server on .NET3.5 I got this error.
I suspect this has something to do with the fact that the control was being compiled into a separate DLL combined with the security changes between the frameworks as described in this .NET security blog
My solution: run the live site on .NET4
`I have added to web.config file in section then System.Security.VerificationException: "Operation could destabilize the runtime." not coming for me.
<system.Web>
<trust level="Full"/>
Does it still fail if you change this:
select new SomeObject { ... } as ISomeTable;
to this:
select (ISomeTable) new SomeObject { ... };
?
If so (as I see you've confirmed), perhaps this has to do with the fact that an interface implementation could be either a class or a struct? Does the problem still appear if you cast to an abstract class rather than an interface?
I found that OfType had some nasty side effects when using linq to sql. For example, parts of the linq that were previously evaluated after the query was run against the db were instead translated to SQL. This failed as those sections had no SQL equivalent. I ended up using .Cast instead which seems to solve the problem as well.
In my case i had wrongly declared the Storage property in the Column attribute of a Linq2SQL class
[Column(Storage = "_Alias", DbType = "NVarChar(50)")]
public string UserAlias
I had same problem, but with inheritance
I defined a class in assembly A and a subclass in Assembly B
after I added below attribute to assembly A, problem solved:
[assembly: SecurityRules(SecurityRuleSet.Level1, SkipVerificationInFullTrust = true)]
I ran into this error while using the "Dynamic data access framework" Passive library. The source of the error was line 100 in the DynamicDatabase.cs file.
databaseDetectors = (databaseDetectors ?? Enumerable.Empty<DatabaseDetector>()).DefaultIfEmpty(new DatabaseDetector());
I changed that line of code to:
databaseDetectors = (databaseDetectors ?? Enumerable.Empty<DatabaseDetector>()).DefaultIfEmpty(new DatabaseDetector()).OfType<IDatabaseDetector>();
Doing so resolved the problem. I went ahead and forked the project and submitted the change to the original author.
Thank you, Jason Baker, for pointing out the solution in your original question.
On a side note, the original library ran fine on my local machine and on a Rackspace VPS, but when I pushed the same code to a shared hosting environment (GoDaddy and Rackspace's Cloud Sites), I began getting the "Operation could destabilize the runtime" error.
I guess, Linq to Sql may not support casting when translate to sql statement.
Related
Today i tried an old project, in my company and got an error which makes me curious. The issue line looks something like this:
if((dynamic)com_list.GetIntValue() != (dynamic)container.GetEnumValue())
The exception shows clearly that you can't compare Int32 with an Enum.
But i wonder, could this have ever worked, in some circumstance?
Are there changes in the dynamic Keyword which don't allow this anymore?
BTW, he also build this in the code like this:
if((dynamic)com_list.GetIntValue() != (dynamic)container.GetBooleanValue())
I'm still confused, why somebody would put this kind of comparing into productiv code.
No. The dynamic specification hasn't changed and I am pretty sure the evaluation in the compiler of such a trivial comparison didn't change overnight in one release to another. Most likely that code never worked.
Without additional cast from enum to int (or the other way around) it won't work.
When working with C#, MS Visual Studio has a tendency when faced with code it doesn't like to give an error message that reads "the best overloaded method match for <method signature> has some invalid arguments". This message is unfortunately low on detail as to what's actually wrong, and consequently being faced with it can prove frustrating. Searching this site or the web at large for the phrase throws up a great many examples of questions, forum threads etc. where people have asked what is wrong in their specific situation where they have encountered this error. I'd like to know what general steps one might take to determine the nature of the underlying problem when faced with this error message.
Note that this question was prompted by an instance of seeing this error message in Visual Studio, but I'm deliberately not posting my code because I want generic troubleshooting advice (related to this error message), not specific help with whatever error is present in my code at this moment (which is likely to be quite pedestrian).
Check each parameter's type to make sure it's what you expect?
The tooltip displays the signature right there.
If you don't know the parameter type you can just make a var variable there set to the same value and then hover over var to see what type it is.
Mostly, check the Type of each argument along with the order in which they are needed to be passed..
Mostly, user do mistakes in parameter DataType.
For Example :
Void Test(Int16 num)
{
.....
}
While calling this method you miss the datatype like bellow eg in the sense you will face this issue
int a = 0;
Test(a);
Make sure the variable declaration or use the var declaration
var a=0;
Here is a piece of code:
IUser user = managerUser.GetUserById(UserId);
if ( user==null )
throw new Exception(...);
Quote quote = new Quote(user.FullName, user.Email);
Everything is fine here. But if I replace "if" line with the following one:
ComponentException<MyUserManagerException>.FailIfTrue(user == null, "Can't find user with Id=" + UserId);
where function implementation is following:
public abstract class ComponentException<T> : ComponentException
where T : ComponentException, new()
{
public static void FailIfTrue(bool expression, string message)
{
if (expression)
{
T t = new T();
t.SetErrorMessage(message);
throw t;
}
}
//...
}
Then ReSharper generates me a warning: Possible 'System.NullReferenceException' pointing on 1st usage of 'user' object.
Q1. Why it generates such exception? As far as I see if user==null then exception will be generated and execution will never reach the usage point.
Q2. How to remove that warning? Please note:
1. I don't want to suppress this warning with comments (I will have a lot of similar pieces and don't want to transform my source code in 'commented garbage);
2. I don't want to changes ReSharper settings to change this problem from warning to 'suggestion' of 'hint'.
Thanks.
Any thoughts are welcome!
P.S. I am using resharper 5.1, MVSV 2008, C#
Resharper only looks at the current method for its analysis, and does not recursively analyse other methods you call.
You can however direct Resharper a bit and give it meta-information about certain methods. It knows for example about "Assert.IsNotNull(a)", and will take that information into account for the analysis. It is possible to make an external annotations file for Resharper and give it extra information about a certain library to make its analysis better. Maybe this might offer a way to solve your problem.
More information can be found here.
An example showing how it's used for the library Microsoft.Contracts can be found here.
A new answer in old post...
Here a little sample of my code regarding how to use CodeContract via ContractAnnotation with Resharper:
[ContractAnnotation("value:null=>true")]
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
It is very simple...if u find the breadcrumb in the wood. You can check other cases too.
Have a nice day
Q1: Because Resharper doesn't do path analysing. It just sees a possible null reference and flags that.
Q2: You can't without doing either of what you provided already.
You do know (or expect) that this code will throw an exception if there is a null reference:
ComponentException<MyUserManagerException>.FailIfTrue([...]);
However, since there is no contract specifying this, ReSharper has to assume that this is just a normal method call which may return without throwing any exception in any case.
Make this method implement the ReSharper contract, or as a simple workaround (which only affects debug mode, therefore no performance penalty for release mode), just after the FailIfTrue call:
Debug.Assert(user != null);
That will get rid of the warning, and as an added bonus do a runtime check in debug mode to ensure that the condition assumed by you after calling FailIfTrue is indeed met.
This is caused by the Resharper engine. These "possible NullReferenceException" happen because someone (probably at Resharper) has declared/configured somewhere an annotation on the method.
Here is how it works: ReSharper NullReferenceException Analysis and Its Contracts
Unfortunately, sometimes, these useful annotation are just wrong.
When you detect an error, you should report it to JetBrains and they will update the annotations on the next release. They're used to this.
Meanwhile, you can try to fix it by yourself. Read the article for more :)
Please check if you have any user==null if check above the given code. If there is, then ReSharper thinks that the variable "can be null" so recommends you to use a check/assert before referencing it. In some cases, that's the only way ReSharper can guess whether a variable can or cannot be null.
I'm looking at the MSDN docs about List.GetEnumerator.
They say the C# method signature is:
public List<(Of <(<'T>)>)>..::..Enumerator GetEnumerator()
I was expecting this much simpler signature:
public List<T>.Enumerator GetEnumerator()
What does their signature mean, with all the punctuation and the "Of" keyword?
Edit: Well, I guess if no one has seen that syntax, then the MSDN docs are just a bit buggy, and that's all.
MSDN uses some code generation to supply that signature for all of the different languages, and this looks like a bug in that code which forgets to take the actual language into account and just outputs all of the syntax - everythign in there can be matched to the expected syntax for such a return type in some language (although, admittedly, I'm not entirely sure where the apostrophe is from).
The same problem can be seen on other pages, such as the very similar HashSet.GetEnumerator, but not on others, like Queryable.AsQueryable, so it seems likely that they don't generate everything at once, and the bug was introduced/removed between the generation of those two pages. (Since we don't know how new each of those are, we can't guess if it's already been fixed.)
I don't know if they have automatic re-generation running every now and then, but if they do, it will probably fix itself soon. If not, you could leave a comment about it in the Community Content section.
Looks like a mistake in MSDN. Take a look at how Queue is defined: http://msdn.microsoft.com/en-us/library/7977ey2c(v=VS.90).aspx
First of all, I'd like to say that this site is great!
My question is, what are the reasons for the following 2 error messages?
1) In VB.NET (I know this is a C# forum but my next question is from C# experience), property evaluation failed (I do this when putting a watch on an exception variable).
2) In C#, method or class (Can't remember which) does not have a constructor. I think I got this with HttpContext or HttpApplication, which is a class if I remember correctly? Pretty sure it is as it has its own properties and methods.
Thanks
1) Could be any number of reasons. Some properties just don't work nicely in a debugger. (Imagine watching DateTime.Now for changes!)
2) You're trying to create an instance of a class which doesn't have an appropriate accessible constructor. Usually either the class only has static members, or there's a static member you're meant to use to get an instance. (Having said that, both the classes you've mentioned have public constructors.)
More precise error messages and situation descriptions would be helpful.
I'd probably want to see code snippets to give you real answers, but my psychic detection powers are telling me that #2 is most likely that you are trying to do something like:
HttpContext context = new HttpContext;
This isn't the way you'd approach that. Instead, you would use its built-in factory method to access the current one:
HttpContext context = HttpContext.Current;
(Ditto for HttpApplication.)
I can't help with #1 without seeing some representative code. And don't worry, this isn't a C#-specific forum, it's for all programming languages and platforms. :)
First of all, apologies for making a duplicate thread (couldn't see this one so made another).
1) That makes sense. Watching datetime.now for changes will just display the time # the time of adding a watch, cache that value, and then get the new value (Time) when checking again.
2) John Rudy: you are spot on. That is what I was doing. So HttpContext.Current gives me back the httpcontext object to work with, I see.