"Operation is not valid" error at Xamarin.iOS project with HttpClient - xamarin.ios

I create HttpClient and call GetStringAsync method right at the button click handler:
var client = new HttpClient();
var response = await client.GetStringAsync("http://google.com");
Debug.WriteLine("Response received: {0}", response);
And every time I get the following error:
System.InvalidOperationException: Operation is not valid due to the current state of the object
2014-05-10 01:26:36.657 HelloWorld3[490:60b] Unhandled managed exception: Operation is not valid due to the current state of the object (System.InvalidOperationException)
at System.Lightup.Call[HttpWebRequest,Int64] (System.Delegate& storage, System.Net.HttpWebRequest instance, System.String methodName, Int64 parameter) [0x00000] in <filename unknown>:0
at System.Lightup.Set[HttpWebRequest,Int64] (System.Delegate& storage, System.Net.HttpWebRequest instance, System.String propertyName, Int64 value) [0x00000] in <filename unknown>:0
at System.Net.HttpWebRequestLightup.SetContentLength (System.Net.HttpWebRequest instance, Int64 value) [0x00000] in <filename unknown>:0
at System.Net.Http.HttpWebRequest.set_ContentLength (Int64 value) [0x00000] in <filename unknown>:0
at System.Net.Http.HttpClientHandler.StartRequest (System.Object obj) [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispat
chInfo.Throw () [0x0000b] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:62
at System.Runtime.CompilerServices.TaskAwaiter`1[System.String].GetResult () [0x00000] in <filename unknown>:0
at HelloWorld3.MyViewController+<<ViewDidLoad>b__0>d__1.MoveNext () [0x00029] in c:\Sources\Local\HelloWorld3\HelloWorld3\MyViewController.cs:41
Debugging session ended.
The program 'Mono' has exited with code 0 (0x0).
I'm not using portable libs, nugets, etc. Just plain project created from a template.
How to solve this issue?
test project with reproduced issue here:
https://dl.dropboxusercontent.com/u/19503836/HelloWorld3.zip

In general this happens when you're building your application using PCL assemblies and from Windows.
I'm not using portable libs,
Ok, still you're likely falling into the same situation. You have the wrong (MS not XI) version of System.Http.Net.dll being copied (and compiled) on the Mac. E.g.
at System.Lightup....
Is not part of the assembly being shipped with Xamarin.iOS. Having this in your stack trace is an indication that the wrong assembly is being used.
This is a known issue that is being fixed (at least for the PCL part). In the mean time the general workaround is using a redirect file (see James blog) or build from the Mac.
In your specific case you might just need to ensure the right assembly is being referenced.

i had the same problem!
resolve with FlorianZimmermann solution.
on this link:
https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec
right-click on References directory for ios or android solution
select edit references
in packages tab , check System.Net.Http
build!
Hope it's help.

Another workaround would be to wrap up your web request in a service that gets injected into the PCL.
Not ideal but thats what Im doing for now.

Before getting into major complications with platform specific "simple" handlers and IoC magic, I suggest you validate a couple of things. After all the whole point of Xamarin and Mono are to avoid all these black santeria hacks to begin with.
If this doesn't work, I would then science the shit of it, and go ballistic... but start here first:
Make sure your platform specific project (MyProject.iOS, or MyProject.Android) HAVE the System.Net.Http referenced under references
Make sure your PCL is targeting the a Profile that is supported by your platform specific project targets (as of the time of this writing, I use "PCL 4.5 - Profile78" with iOS and Android projects)
Good luck!

Related

InvalidOperationException "get_MetadataToken() cannot be used on the current platform" when creating tables

This is an interesting problem for me. On my work machine, my code works perfectly fine, but on my home machine when starting with a new sqlite file I get an InvalidOperationException when db.Database.Migrate() is called.
According to Windows Update, both machines are up to date.
Visual Studio 2015 also shows as up to date on both machines.
I'm running EF7 rc1-final
The stacktrace isn't exactly deep:
System.InvalidOperationException occurred
HResult=-2146233079
Message=The API 'System.Reflection.MemberInfo.get_MetadataToken()' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information.
Source=mscorlib
StackTrace:
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
InnerException:
The provided link just goes to the MSDN main page. I'd personally prefer a 404.
There's Issue 190, but I don't see why it would only be a problem on one of my machines.
Is there a solution/workaround?

Running mono-service in linux as non-root

I need to run a .net C# application (developed on a Windows system) as a service/daemon on an embedded system with a minimal Ubuntu installation (no X, no servers except ssh, only relevant software). I created an /etc/init.d script containing the line
mono-service my-.net-app.exe service
and this worked well. There is also an option to start the application interactively (for debugging purposes) with
mono my-.net-app.exe interactive
The last argument is an argument for the .NET application telling it if it's running as service. This was implemented roughly this way:
private static void Main(string[] args){
if(args.Any() && args[0] != null && args[0] == "service"){
ServiceBase.Run(new[] {(ServiceBase) new MyService()});
}else{
try{
Console.Write("starting app");
if(StartWork()){
Console.Write("press any key to exit");
Console.ReadKey();
}else{
Console.WriteLine("starting app failed");
}
} // end try
finally{
StopWork();
Console.WriteLine("finished app");
}
} // end else
...
} // end Main
public class MyService : ServiceBase{
static private Thread _worker;
protected override void OnStart(string[] args){
_worker = new Thread(() => Program.StartWork(asService: true)); // this asService tells StartWork to not produce console output
_worker.Start();
}
protected override void OnStop(){
Program.StopWork();
_worker.Join(1000);
}
}
The purpose of this implementation was to allow the application to die gracefully (i.e. to execute StopWork()) upon sending SIGTERM on the linux machine.
For security reasons, I need to be able to run the service as non-root. I created a new user and made it owner of the directories where the application writes its log files and added it to various groups to give it access to required device files. Then, root would start the application as
sudo -u newuser mono-service my-.net-app.exe service
or
sudo -u newuser mono my-.net-app.exe interactive
The second option with mono works well, but the first one with mono-service doesn't (see error message below). Since it works with mono, I'm confident that the user newuser has appropriate rights to access all relevant files and devices. I wonder whether mono-service has been conceived as a root-only application.
I could also live with using the mono option and suppressing the console output, like this:
private static void Main(string[] args){
try{
Console.Write("starting app");
if(StartWork(consoleoutput)){ // true or false depending on whether the service argument was given
Console.Write("press any key to exit");
Console.ReadKey();
}else{
Console.WriteLine("starting app failed");
}
} // end try
finally{
StopWork();
Console.WriteLine("finished app");
}
...
} // end Main
but then, when I kill the service (i.e. send SIGTERM to the mono process), it stops the .net application immediately without allowing it to execute the finally block.
Finally, my question is whether someone has an idea why mono-service is failing when not started as root. The error message is the following and, as I mentioned before, it doesn't exist when I use mono instead of mono-service.
ERROR Program [4] [15:03:06.795 01/12/14] Error in Main!
FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
---> NHibernate.HibernateException: Could not create the driver from SAFEmine.DataStore.Database.MonoSqliteDriver, SAFEmine.DataStore, Version=1.3.0.6, Culture=neutral, PublicKeyToken=null. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> NHibernate.HibernateException: The IDbCommand and IDbConnection implementation in the assembly Mono.Data.Sqlite could not be found. Ensure that the assembly Mono.Data.Sqlite is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use <qualifyAssembly/> element in the application configuration file to specify the full name of the assembly.
at NHibernate.Driver.ReflectionBasedDriver..ctor (System.String providerInvariantName, System.String driverAssemblyName, System.String connectionTypeName, System.String commandTypeName) [0x00000] in <filename unknown>:0
at NHibernate.Driver.ReflectionBasedDriver..ctor (System.String driverAssemblyName, System.String connectionTypeName, System.String commandTypeName) [0x00000] in <filename unknown>:0
at SAFEmine.DataStore.Database.MonoSqliteDriver..ctor () [0x00000] in <filename unknown>:0
at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (System.Reflection.MonoCMethod,object,object[],System.Exception&)
at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj, System.Object[] parameters) [0x00000] in <filename unknown>:0
Alternatively, if I settle for mono instead of mono-service, is there a way to catch a SIGTERM from within the .net application and to die gracefully? I tried this: https://github.com/ServiceStack/ServiceStack/wiki/Run-ServiceStack-as-a-daemon-on-Linux , but the code wouldn't compile on Visual Studio saying that the using Mono.Unix; and using Mono.Unix.Native lines were invalid. I also installed Mono on Windows and tried to use the Mono compiler, but it complained about the same thing.
The mono-service.exe creates a new AppDomain with ApplicationBase being the current directory. This might influence assembly loading. Since you are seeing such an error, I would try to enable MONO_LOG_LEVEL=debug MONO_LOG_MASK=asm and/or strace -e file to see if they provide any hints.
Also note that you can pass -d switch to mono-service to have it change directory for you.

Mono WCF Client Exception: The requested feature is not implemented

I have developed a C# WCF client application using Visual Studio 2008 and it works fine. The client application uses the wcf wrapper class and consume the WCF service. But when I execute the same source code in Redhat Linux 6.5 using MonoDevelop IDE, I am getting the following exception while creating a wcf object. The WCF web service is running as a windows service.
{System.NotImplementedException: The requested feature is not implemented. at System.ServiceModel.Configuration.WSHttpBindingElement.OnApplyConfiguration (System.ServiceModel.Channels.Binding binding) [0x00000] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/WSHttpBindingElement.cs:101 at System.ServiceModel.Configuration.StandardBindingElement.ApplyConfiguration (System.ServiceModel.Channels.Binding binding) [0x00030] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/StandardBindingElement.cs:143 at System.ServiceModel.Configuration.ConfigUtil.CreateBinding (System.String binding, System.String bindingConfiguration) [0x00053] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ConfigUtil.cs:104 at System.ServiceModel.ChannelFactory.ApplyConfiguration (System.String endpointConfig) [0x000e9] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory.cs:156 at System.ServiceModel.ChannelFactory.InitializeEndpoint (System.String endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) [0x00024] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory.cs:309 at System.ServiceModel.ChannelFactory1[IMyMonitor]..ctor (System.String endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) [0x00017] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory_1.cs:73 at System.ServiceModel.ClientBase1[IMyMonitor].Initialize (System.ServiceModel.InstanceContext instance, System.String endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) [0x00000] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel/ClientBase.cs:159 at System.ServiceModel.ClientBase1[IMyMonitor]..ctor (System.ServiceModel.InstanceContext instance, System.String endpointConfigurationName) [0x00028] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel/ClientBase.cs:90 at System.ServiceModel.ClientBase1[IMyMonitor]..ctor (System.ServiceModel.InstanceContext instance) [0x00000] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel/ClientBase.cs:79 at System.ServiceModel.ClientBase`1[IMyMonitor]..ctor () [0x00000] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel/ClientBase.cs:54 at SenMonitorClient..ctor () [0x00000] in /mywork/myclient/wcfService.cs:1429 at myclient.start () [0x0079c] in /mywork/myclient/Program.cs:285 } System.NotImplementedException
Environment: MonoDevelop 4.2.3, mono 3.4.0
Thanks for your help.
WCF support is currently limited on Mono and as mentioned here - mono-project.com/WCF WSHttpBinding and its dependencies are components with no plan to support. May be you want to fall back on to basichttpbinding which should be supported since it shows WCF modules were in development till .NET 3.0 with silverlight 2.0 subset.

Creating Files in Sitefinity API for docs that already exist on Filesystem

I am working with Sitefinity as a solution in Visual Studio 2012. I'm on a 64bit machine. I just installed Windows Identity Manager as I was getting another error before that and it was related to not having that installed. Now I am receiving this error:
Found invalid data while decoding.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.InvalidDataException: Found invalid data while decoding.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidDataException: Found invalid data while decoding.]
System.IO.Compression.Inflater.DecodeDynamicBlockHeader() +6621162
System.IO.Compression.Inflater.Decode() +408
System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length) +150
System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count) +64
Microsoft.IdentityModel.Web.DeflateCookieTransform.Decode(Byte[] encoded) +396
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +217
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +1958
Telerik.Sitefinity.Security.Claims.SitefinitySessionTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +44
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +149
Telerik.Sitefinity.Security.Claims.SitefinitySessionAuthenticationModule.ReadToken(Byte[] sessionCookie) +520
Telerik.Sitefinity.Security.Claims.SitefinitySessionAuthenticationModule.TryReadFromCookie(SessionSecurityToken& sessionToken) +111
Telerik.Sitefinity.Security.Claims.SitefinitySessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +95
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
I also followed the advice before and after this post and it did not work for me:
http://www.sitefinity.com/developer-network/knowledge-base/getting-type-is-not-resolved-for-member-microsoft-identitymodel-claims-claimsprincipal-exception
which is what led me to installing the Microsoft identity Manager. I'm not sure how to get past this issue.
There are bugs in Microsoft's DeflateStream implementation prior to .Net 4.5.
See here:
.NET [4 and previous] users should not use the Microsoft-provided
GZipStream or DeflateStream classes under any circumstances, unless
Microsoft replaces them completely with something that works.
This bug was never fixed by Microsoft for earlier versions of the .NET framework than 4.5
As for the difference between Firefox and IE - they might be interacting differently with IIS while using gzip compression, Fiddler might be able to tell you more about the differences in your situation if you look at the raw HTTP requests and responses. Check if the request sequence looks the same between browsers. My gut feeling is that Firefox is falling back to no compression and IE isn't, but without a test bed I won't be able to help further.
You could try these three solutions in increasing order of desperation:
See if you can change the app pool in IIS for the SiteFinity application and your .NET framework target inside Visual Studio to target .NET 4.5 where their GZIP DeflateStream method was fixed.
Attempt to disable GZIP compression in IIS for this application. Follow the instructions found here in reverse. I would try this last because there will be a bandwidth penalty for your server and all users, affecting the user experience.
Install the DotNetZip Library, and override Microsoft's implementation of System.IO.Compression.DeflateStream to call a compatible method that doesn't have the same bug.

Debugging WCF Web Service Faults

I am trying to debug a web service exception. I have both the client and the service running in debug mode in Visual Studio 2010, C#, .net 4.0 framework.
When I run the client, and get it to call the web service, I get an exception:
Type: System.ServiceModel.FaultException`1[[System.ServiceModel.ExceptionDetail, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Error Message: The type initializer for 'myService.Service' threw an exception.
Source: mscorlib
However, the service shows no exceptions whatsoever.
The stack trace that I got seems to indicate that the call was made, and the reply was being handled (even if the reply was an exception):
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Can someone give pointers on what else I need to do to debug this?
I'm currently setting up the Service Trace Viewer tool to see if that will tell me anything more.
The error message suggests that your service class myService.Service has a static constructor or field initializer expression with a bug in it, causing an unhandled exception to escape the static ctor when the Service type is loaded.
In the service host process under the debugger, just put breakpoints on the static ctor and field initializer expressions, and step until the underlying exception occurs.
The Fusion (.NET class loader) Log will likely get you there also, if you know how to use that.
Error is likely a missing dependency on server side. Launch fuslogvw.exe, enable failure logging, reproduce the problem and look for related failure records.

Resources