How do i check for mono on runtime - mono

By default mono doesnt trust any SSL connections. So if running on mono i'd like to give a message rather then throwing an exception.
How do i check if i am running under mono at runtime? (since at compile time the CLI wont know)

I'll quote from the Mono site:
Having code that depends on the underlying runtime is considered to be bad coding style, but sometimes such code is necessary to work around runtime bugs
using System;
class Program {
static void Main ()
{
Type t = Type.GetType ("Mono.Runtime");
if (t != null)
Console.WriteLine ("You are running with the Mono VM");
else
Console.WriteLine ("You are running something else");
}
}

Couldn't you just catch the System.Net.WebException and pass your message up? This is approach #1 from the Mono site here: Using Trusted Roots Respectfully. There are a number of more (and a couple less) involved responses there if you'd like to do more, but catching the exception avoids the coding-to-runtime problem tobsen refers to.

Related

Is it really a limitation to use interfaces such as IList<T>.someMethod in AOT code?

In the mono project documentation this limitation is outlined:
Limitation: Generic Interface Instantiation
The following class of interface dispatch is not supported in FullAOT
mode:
interface IFoo<T> {
...
void SomeMethod ();
}
Since Mono has no way of determining from the static analysis what
method will implement IFoo.SomeMethod this particular pattern is
not supported.
We have been using code like this unbeknownst to this limitation, and are currently attempting to figure out if some stability issues and this are related. This seems to function as expected, and so we are skeptical this is an issue still. Our code compiles to AOT with no errors, and runs without throwing any errors. Is this just old documentation?
An added bonus question: If this isn't supposed to work...why does it work for the built-in C# classes such as IList without issue but it shouldn't work otherwise?

F# wsdl type provider error?

Although I love the idea of F# type providers my first serious attempt to use them crashed hard.
I was going to connect to a service (WCF) with WsdlService<"http://someurl/some.svc?wsdl">
It fails epicly with:
The type provider
'Microsoft.FSharp.Data.TypeProviders.DesignTime.DataProviders'
reported an error: tmp6E6C.cs(9409,26): error CS0644:
'System.ComponentModel.PropertyChangedEventHandler' cannot derive from
special class 'System.MulticastDelegate'
c:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll: (Location
of symbol related to previous error)
and a lot of other warnings which probably are not relevant:
tmp6E6C.cs(290,28): warning CS0436: The type
'System.Data.DataRowState' in
'c:\Users\someuser\AppData\Local\Temp\tmp6E6C.cs' conflicts with the
imported type 'System.Data.DataRowState' in
'c:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Data.dll'. Using
the type defined in 'c:\Users\someuser\AppData\Local\Temp\tmp6E6C.cs'.
tmp6E6C.cs(9427,17): (Location of symbol related to previous warning)
Is this a known feature ;-) or am I using it wrong?
I unfortunately cannot post the WSDL, and its rather large with a lot of types in it so I must admit I am somewhat lazy and have not trimmed it down either. OTOH if I did know what part of the WSDL was offending or creating this error I would of course have put it here.
To change the WSDL is not an option either, so I am mainly interested in knowing why F# WSDL type providers can not handle this (WCF) WSDL, or what I am doing wrong.
It works excellent when consumed by C# and svcutil.exe from VS2010.
I have tried all the params to the WsdlTypeProvider and they do give the same result (except ForceUpdate of course). Should I be consuming these services in another way with F#?
===============================================================================
Added info (since I am new and didnt want to answer. dont ask why :):
Thank you all answering/commenting.
I did go partly this way may self (manually using svcutil). As I tried to say above, I tried to use svcutil by hand, and it fails when compiling the generated C# code (in a library besides the F#).
That is, I did the following:
1) Create the contract by setting up a reference in VS 2010 GUI. This works as expected
2) Try to create it by using svcutil from cmd-line. Then the compile of that file fails with same error.
As it seems from my point of view what happens in svcutil from cmd-line and what happens when using svcutil (or what is used) from the GUI adding the same service does not generate the code with the same parameters. I guess this is partly controlled by the fact that what I try to consume is a WCF service and not a "clean" WSDL/webservice, and the type provider assumes that I try to use a "clean" webservice.
I did not manage to find any params for svcutil takeing care of this, or any possible combinations of params, not saying that I did try all permutations of combinations, but trying the ones probable based upon (trying to) deep reading the documentation of svcutil (and I am not entirley new at using it from cmd-line).
So far I have concluded that it is some "missing" params to svcutil which causes this, and that the F# type provider is not at fault. I would still very much like to solve it somehow, still using F# type providers, but a fallback is to generate the code by GUI in C# and then reference that part of code in F# again. That is not the elegant solution I was trying to achieve, since I do have a lot of services and I would very much like to create such a nice way of prototyping and testing those services.
Another fallback would of course also give up the whole F# part and just go with some unit-testing etc., but that again is defating the purpose of sneaking in F# and learning at same time ;-)
The WSDL type provider (and a few others) are using SvcUtil in the background to do the heavy lifting. If you open ProcExp of taskmgr or some similar tool, you can see the SvcUtil process getting spawned after pasting the TP code into Visual Studio. With ProcExp at least, you can see the full command line with arguments which was used.
So find out exactly what SvcUtil command line was invoked by the TP for your service, and check if it works outside of the F# environment.
The fact that SvcUtil works from C#/VS 2010 is interesting. I assume if you are using F# TPs you are on VS 2012 right now. If so, the version of SvcUtil itself might be different, which could be related.
The specific error would appear to be the same as explained here, so you might have some incomplete annotations in your service code.
I am not able to leave this issue ...
I have now done the following:
Run svcutil with plain vanilla setting: svcutil http://some.address/some/path.svc
Run with some more setting: svcutil /r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.dll" /r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.Data.dll" http://some.address/some/path.svc
This does generate the follwowing differences in the C# file (it is present in 1) and not present in 2) obviously):
namespace System.ComponentModel
{
using System;
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.SerializableAttribute()]
public partial class PropertyChangedEventHandler : System.MulticastDelegate
{
public PropertyChangedEventHandler(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) :
base(info, context)
{
}
}
}
namespace System.Data
{
using System;
using System.Runtime.Serialization;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.FlagsAttribute()]
[System.Runtime.Serialization.DataContractAttribute(Name="DataRowState", Namespace="http://schemas.datacontract.org/2004/07/System.Data")]
public enum DataRowState : int
{
[System.Runtime.Serialization.EnumMemberAttribute()]
Detached = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
Unchanged = 2,
[System.Runtime.Serialization.EnumMemberAttribute()]
Added = 4,
[System.Runtime.Serialization.EnumMemberAttribute()]
Deleted = 8,
[System.Runtime.Serialization.EnumMemberAttribute()]
Modified = 16,
}
}
Which again makes the file compile in 2) and is as expected otherwise.
The somewhat strange part then is: Why isnt System.dll used in F# wsdl providers when running svcutil? System.Data.dll I kind of understand, since that isnt default used when running svcutil (at least according to the documentation).
OTOH I think also that the documentations says that IF the assemblies are in the GAC it should use them. So how do I verify they are there, and/or load them to the assembly if not?
Running gacutil -i System.dll (on version 4.5 of the System.dll) gives:
Failure adding assembly to the cache: An attempt was made to load a
program with an incorrect format.
Is it some 64/32 bit issue? (Im on a 64 bit windows if that does have any relevance)
Or to rephrase the problem: How do I get System.dll and System.Data.dll to part of the references when running svcutil when I cannot add the references directly through the WsdlProvider-part?
Im pretty sure it does not use System.dll since if I add the collectiontype param to wsdlprovider:
WsdlService<"http://some.url/some/path.svc", "c:\\temp\\wsdl\\some.wsdlschema", true, ".", true, true, false, false, "System.Collections.Generic.List'1">
it also complains with the following:
The type provider
'Microsoft.FSharp.Data.TypeProviders.DesignTime.DataProviders'
reported an error: Error: No type could be loaded for the value
System.Collections.Generic.List'1 passed to the /collectionType
option. Ensure that the assembly this type belongs to is specified via
the /reference option.
which should have been available directly if System.dll was referenced (I think).
Any ideas to further investigate or solve this issue?

Validation in setters: What approach is better?

I have dispute with my friend.
He said me that this code:
method SetBalance(balance) {
if (balance > 0) {
this.balance = balance;
return true;
}
return false;
}
is better then this:
method SetBalance(balance) {
if (balance < 0) {
throw new InvalidArgumentException("Balance couldn't be negative")
}
this.balance = balance;
}
My question is: "Which approach is better for validation?" and why?
Thank you.
Ah. Return status versus exception.
I prefer throwing exceptions, because you can't really ignore an exception. The program either crashes, or you have to explicitly catch and handle it.
You can just ignore a return status.
Besides, isn't this the reason exceptions exist in modern programming? To deal with, well... exceptions (balance <= 0, something that shouldn't happen).
In case of setters, developers will never expect the return value from those methods since they feel that this will anyway will take care of setting the value.
In case, if there is an exception, then this will help then to understand that something is really wrong and look after the code again.
Instead of runtime exception, you better define your own exception like InvalidBalanceException and specify that this method will throw this exception in the signature itself. This avoids surprises at testing phase and decide the business logic in development phase itself.
Return value is easily ignored. Here you have clear coding bug, so crash loud. I would even halt/segfault/stop program - the exception may still be caught. We live in "ideal world", but imagine our less fortunate colleagues - they might well go for gagging error signalling facility being unable to deal with the root cause (insert here more complicated error scenario). Coding gets much easier when you dont give clients ways to do things wrong way.
Besides the answers given already, returning a boolean value in a function named "setFoo" is very misleading. If you translate a boolean value you come up with yes/no. So a function that returns booleans in oop should be readable as a question that gives yes/no as an answer, e.g. isBalanceSet.
In discussion with collegues we considered the only valid return-value for a normal setter is the class itself for fluent-interfaces.
Regarding your question throwing exceptions is the better solution if the class actually validates its properties itself ;)
My personal opinion: both approaches has its uses. It depends on why the situation arose, could it be prevented, what the client could have done to prevent it.
Server:
method SetBalance(int balance)
{
// do something only if balance >= 0
}
Client:
myServer.SetBalance(balance);
Case 1:
The situation arises only because of a bug somewhere (in server or client). Throw exception. Let the responsible party fix its code.
Case 2:
A bad input is received from some external dependency. The client could easily check the precondition. Throw exception, let the client fix its code if she is unhappy with that.
if(balance>0)
myServer.SetBalance(balance);
else
//take appropriate action.
Case 3:
A bad input is received from some external dependency. The client could not easily check the precondition. Example: it would require the client to parse a string, which is the server's job. Here, it makes sense that the server should return success:
bool succeeded = myServer.SetBalance(balance);
if(!succeeded)
//take appropriate action.
After writing my answer down, I noticed it all boils down to this: The client should not have to use try-catch to call the method SetBalance. (Either it's a bug so don't catch the exception, or check the precondition yourself, or inspect the return value)
Here is a good reading on a related subject: http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx
Edit:
Jojo makes a good point. Rename the method TrySetBalance() if there is a probability that it might fail.
Exceptions handling is the method of choice to handle errors in OOP, whether it is runtime error or logic error. One of the arguments to justify exception handling is that, if error code is used a client of a function may forget to check the error code leading to a potential bug which may not be easily found. Whereas, if exception handling is used, even if it is not caught, it will propagate until it is handled. So, OOP purists always advice using exception handling.

System.Collections.ObjectModel.ObservableCollection only partially implemented in Monotouch?

I'm consuming WCF services using the Silverlight 3 stubs and one parameter I need is a System.Collections.ObjectModel.ObservableCollection.
However the following code is throwing a NotImplementedException:
ItemType[] aItemTypes = ...;
ObservableCollection<ItemType> aTypes = null;
if(aItemTypes != null)
{
aTypes = new ObservableCollection<ItemType> (aItemTypes);
}
If I use a foreach loop to add all entries manually instead of using the constructor that takes an enumerable, it works. Is there a reason why the constructor is missing or was it just forgotten?
Is there a reason why the constructor is missing or was it just forgotten?
This sometimes occurs on Mono base class library source code when someone implement a type but does not need everything inside it. In such cases it's better to add stubs for the missing code since this:
allow compilation of existing code;
it avoid MissingMethodException at runtime, a NotImplementedException is easier to diagnose;
allow Mono's tooling, e.g. MoMA and Gendarme, to report the NotImplementedException on existing .NET code.
In this specific case I suspect that more tests were needed to see if the items being copied needed to trigger events (whgen adding them) or not.
The good news is that this method is implemented in Mono's GIT master. I'll look into backporting this into mono-2-10 branch so MonoTouch will get it in future releases.

How are try/catch blocks implemented?

If an exception occurs in a try block, how is execution transferred to the catch block? This is not a C#/Java/C++ question, I'm just wondering how it works internally.
this is not a c#/java/c++ question. How it works internally,how the line knows to go catch statement.
How this works internally makes this pretty much a c#/java/C++ question (because it will be implemented differently).
In Java, a try block installs itself into a special table (in the class file). When the JVM throws an exception, it looks at that table to see where the next catch or finally block to go to is.
When an exception occurs a special instruction is executed (usually called interrupt). This leads to executing a generic error handler that deduces which is the latest installed suitable exception handler. That handler is then executed.
There is a difference how exceptions are technically handled between natively compiled languages such as C++ and languages using byte-code being executed on a virtual machine such as Java or C#.
C++ compilers usually generate code that protocols the information needed for exception handling at runtime. A dedicated data structure is used to remember entrance/exit of try blocks and the associated exception handler. When an exception occurs, an interrupt is generated and control is passed to the OS which in turn inspects the call stack and determines which exception handler to call.
Further details are pretty well explained in the following article by Vishal Kochhar:
How a C++ compiler implements exception handling
In Java or .NET there is no need for the overhead of maintaining exception handling information as the runtime will be able to introspect the byte code to find the relevant exception handler. As a consequence, only exceptions that are actually thrown are causing an overhead.
It is basically parsing fundamentals of the language.
You can get all info at Here
it should work in all langues somewhat like this:
if (error_occured xy while doing things in try){
call_catch_part(error xy)
}
you could do the same in C even though there is no exception handling per se.
There you would use setjmp/longjmp unfortunately you then do not get the stack unwinding and have to handle all the nitty-gritty yourself.