Issue in implementing RabbitMQ client in MONO - mono

I have encountered a problem in implementing a very simple RabbitMQ client in C# under MONO. I'm using the following environment:
OS : Ubuntu 16.04
MonoDevelop : 5.10
.net Assembly : RabbitMQ.Client.dll version 3.6.5.0
I have a RabbitMQ server running on my pc. If I run the command
sudo rabbitmqctl status
I obtain the following result
Status of node 'rabbit#federico-pc' ...
[{pid,9948},
{running_applications,
[{rabbitmq_management,"RabbitMQ Management Console","3.6.5"},
{rabbitmq_web_dispatch,"RabbitMQ Web Dispatcher","3.6.5"},
{webmachine,"webmachine","1.10.3"},
{mochiweb,"MochiMedia Web Server","2.13.1"},
{ssl,"Erlang/OTP SSL application","7.3"},
{public_key,"Public key infrastructure","1.1.1"},
{crypto,"CRYPTO","3.6.3"},
{rabbitmq_management_agent,"RabbitMQ Management Agent","3.6.5"},
{asn1,"The Erlang ASN1 compiler version 4.0.2","4.0.2"},
{compiler,"ERTS CXC 138 10","6.0.3"},
{amqp_client,"RabbitMQ AMQP Client","3.6.5"},
{inets,"INETS CXC 138 49","6.2"},
{syntax_tools,"Syntax tools","1.7"},
{rabbit,"RabbitMQ","3.6.5"},
{mnesia,"MNESIA CXC 138 12","4.13.3"},
{os_mon,"CPO CXC 138 46","2.4"},
{rabbit_common,[],"3.6.5"},
{ranch,"Socket acceptor pool for TCP protocols.","1.2.1"},
{xmerl,"XML parser","1.3.10"},
{sasl,"SASL CXC 138 11","2.7"},
{stdlib,"ERTS CXC 138 10","2.8"},
{kernel,"ERTS CXC 138 10","4.2"}]},
{os,{unix,linux}},
{erlang_version,
"Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:2:2] [async-threads:64] [kernel-poll:true]\n"},
{memory,
[{total,55360120},
{connection_readers,0},
{connection_writers,0},
{connection_channels,0},
{connection_other,2712},
{queue_procs,2712},
{queue_slave_procs,0},
{plugins,389184},
{other_proc,18455960},
{mnesia,68360},
{mgmt_db,424248},
{msg_index,51504},
{other_ets,1445848},
{binary,98976},
{code,27797472},
{atom,1000601},
{other_system,5622543}]},
{alarms,[]},
{listeners,[{clustering,25672,"::"},{amqp,5672,"::"}]},
{vm_memory_high_watermark,0.4},
{vm_memory_limit,1549926400},
{disk_free_limit,50000000},
{disk_free,231269703680},
{file_descriptors,
[{total_limit,924},{total_used,2},{sockets_limit,829},{sockets_used,0}]},
{processes,[{limit,1048576},{used,229}]},
{run_queue,0},
{uptime,5890},
{kernel,{net_ticktime,60}}]
This is the C# code of the very simple client
using System;
using RabbitMQ.Client;
namespace provaRabbit
{
class MainClass
{
public static void Main (string[] args)
{
var factory = new ConnectionFactory ();
factory.HostName = "localhost";
factory.UserName = "test";
factory.Password = "test";
factory.VirtualHost = ConnectionFactory.DefaultVHost;
factory.Port = AmqpTcpEndpoint.UseDefaultPort;
using (var connection = factory.CreateConnection ())
using (var channel = connection.CreateModel ())
{
channel.QueueDeclare (queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
string message = "Hello World!";
var body = System.Text.Encoding.UTF8.GetBytes (message);
channel.BasicPublish (exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine (" [x] Sent {0}", message);
}
Console.WriteLine (" Press [enter] to exit.");
Console.ReadLine ();
}
}
}
Of course I have created a "test" user with relevant password and I gave him administrator privileges.
When I try to debug the program I obtain the following exception
RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable ---> System.MissingMethodException: Method 'IPAddress.MapToIPv6' not found.
at System.Linq.Enumerable+WhereSelectArrayIterator`2[TSource,TResult].MoveNext () [0x0004d] in <filename unknown>:0
at System.Linq.Buffer`1[TElement]..ctor (IEnumerable`1 source) [0x00087] in <filename unknown>:0
at System.Linq.Enumerable.ToArray[TSource] (IEnumerable`1 source) [0x00011] in <filename unknown>:0
at RabbitMQ.Client.TcpClientAdapter.BeginConnect (System.String host, Int32 port, System.AsyncCallback requestCallback, System.Object state) [0x00044] in <filename unknown>:0
at RabbitMQ.Client.Impl.SocketFrameHandler.Connect (ITcpClient socket, RabbitMQ.Client.AmqpTcpEndpoint endpoint, Int32 timeout) [0x0000f] in <filename unknown>:0
at RabbitMQ.Client.Impl.SocketFrameHandler..ctor (RabbitMQ.Client.AmqpTcpEndpoint endpoint, System.Func`2 socketFactory, Int32 connectionTimeout, Int32 readTimeout, Int32 writeTimeout) [0x0003f] in <filename unknown>:0
at RabbitMQ.Client.Framing.Impl.ProtocolBase.CreateFrameHandler (RabbitMQ.Client.AmqpTcpEndpoint endpoint, System.Func`2 socketFactory, Int32 connectionTimeout, Int32 readTimeout, Int32 writeTimeout) [0x00000] in <filename unknown>:0
at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler (RabbitMQ.Client.AmqpTcpEndpoint endpoint) [0x00005] in <filename unknown>:0
at RabbitMQ.Client.ConnectionFactory.CreateConnection (IList`1 endpoints, System.String clientProvidedName) [0x0007e] in <filename unknown>:0
--- End of inner exception stack trace ---
at RabbitMQ.Client.ConnectionFactory.CreateConnection (IList`1 endpoints, System.String clientProvidedName) [0x0009b] in <filename unknown>:0
at RabbitMQ.Client.ConnectionFactory.CreateConnection (IList`1 hostnames, System.String clientProvidedName) [0x0001d] in <filename unknown>:0
at RabbitMQ.Client.ConnectionFactory.CreateConnection () [0x00013] in <filename unknown>:0
at provaRabbit.MainClass.Main (System.String[] args) [0x00029] in /home/federico/Scrivania/rabbitMQ/provaRabbit/provaRabbit/Program.cs:16
Does anyone have any suggestion?
Regards
Federico

that error usually means RabbitMQ is not running, or is on a server that can't be reached at all.
try a couple of things to see if it is running, other than "status".
run sudo rabbitmqctl list_queues
and/or go to http://localhost:15672
if both of those work, rabbitmq is definitely running. at which point, i would wonder if you have a firewall or security setting preventing you from connecting to your own localhost on port 5672 (the RabbitMQ port).
you may also want to add a "connection timeout" to the connection configuration. Set it to something high, like 2 minutes.
(see https://www.rabbitmq.com/releases/rabbitmq-dotnet-client/v3.1.1/rabbitmq-dotnet-client-3.1.1-client-htmldoc/html/type-RabbitMQ.Client.ConnectionFactory.html - and the connectionFactory.RequestedConnectionTimeout setting)
It's possible your machine is just taking a while to make the connection and the C# code thinks it is not available because of that.

I found a solution to the problem.
The trick is using the built in libraries: System.Messaging, Mono.Messaging, Mono.Messaging.RabbitMQ, RabbitMQ.Client.
A very simple working code is
using System;
using System.Text;
using System.Messaging;
using Mono.Messaging;
using Mono.Messaging.RabbitMQ;
using RabbitMQ.Client;
namespace provaRabbitMQ
{
class MainClass
{
public static void Main (string[] args)
{
string message = "";
ConnectionFactory factory = new ConnectionFactory ();
factory.HostName = "localhost";
factory.Port = 5672;
factory.UserName = "guest";
factory.Password = "guest";
factory.RequestedHeartbeat = 60;
IConnection connection = factory.CreateConnection ();
IModel channel = connection.CreateModel ();
channel.QueueDeclare ("try", true);
message = "Hello World!";
byte[] body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "try",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
Federico

Related

Xamarin Forms FFImageLoading doesn't load images from a specific URL

I'm trying to load an image from this url to CachedImage
unfortunately nothing is displayed.
For example, the image from this url is loaded fine
I followed the necessary steps from the documentation so I have all the Init in MainActivity.cs, etc.
I tried every solution I found here.
It shouldn't be encoded in GZIP
Also, no error message is displayed and the image is displayed correctly in Xamarin.Forms.Image
XAML file:
<ffimageloading:CachedImage
Aspect="AspectFill"
HorizontalOptions="FillAndExpand"
Source="{Binding Attributes.Cover256Uri}" />
Edit:
Console output:
Image memory cache size: 63.11 MB, reuse pool size:D 63.11 MB
Retry download: https://uploads.mangadex.org//covers/fffbfac3-b7ad-41ee-9581-b4d90ecec941/3787d628-0387-43ea-b732-3b9015584c0b.jpg.256.jpg
Retry download: https://uploads.mangadex.org//covers/fffbfac3-b7ad-41ee-9581-b4d90ecec941/3787d628-0387-43ea-b732-3b9015584c0b.jpg.256.jpg
Retry download: https://uploads.mangadex.org//covers/fffbfac3-b7ad-41ee-9581-b4d90ecec941/3787d628-0387-43ea-b732-3b9015584c0b.jpg.256.jpg
Retry download: https://uploads.mangadex.org//covers/fffbfac3-b7ad-41ee-9581-b4d90ecec941/3787d628-0387-43ea-b732-3b9015584c0b.jpg.256.jpg
FFImageLoading.Exceptions.DownloadAggregateException: One or more errors occurred. (The SSL connection could not be established, see inner exception.) (The SSL connection could not be established, see inner exception.) (The SSL connection could not be established, see inner exception.) (The SSL connection could not be established, see inner exception.) ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception. ---> Mono.Btls.MonoBtlsException: Ssl error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED
at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/boringssl/ssl/handshake_client.c:1132
at Mono.Btls.MonoBtlsContext.ProcessHandshake () [0x00042] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System/Mono.Btls/MonoBtlsContext.cs:220
at Mono.Net.Security.MobileAuthenticatedStream.ProcessHandshake (Mono.Net.Security.AsyncOperationStatus status, System.Boolean renegotiate) [0x000da] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs:715
at (wrapper remoting-invoke-with-check) Mono.Net.Security.MobileAuthenticatedStream.ProcessHandshake(Mono.Net.Security.AsyncOperationStatus,bool)
at Mono.Net.Security.AsyncHandshakeRequest.Run (Mono.Net.Security.AsyncOperationStatus status) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System/Mono.Net.Security/AsyncProtocolRequest.cs:289
at Mono.Net.Security.AsyncProtocolRequest.ProcessOperation (System.Threading.CancellationToken cancellationToken) [0x000fc] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System/Mono.Net.Security/AsyncProtocolRequest.cs:223
--- End of inner exception stack trace ---
at Mono.Net.Security.MobileAuthenticatedStream.ProcessAuthentication (System.Boolean runSynchronously, Mono.Net.Security.MonoSslAuthenticationOptions options, System.Threading.CancellationToken cancellationToken) [0x0025c] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs:310
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore (System.IO.Stream stream, System.Net.Security.SslClientAuthenticationOptions sslOptions, System.Threading.CancellationToken cancellationToken) [0x0007b] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectHelper.cs:165
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore (System.IO.Stream stream, System.Net.Security.SslClientAuthenticationOptions sslOptions, System.Threading.CancellationToken cancellationToken) [0x000f6] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectHelper.cs:176
at System.Threading.Tasks.ValueTask`1[TResult].get_Result () [0x0001b] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/Threading/Tasks/ValueTask.cs:813
at System.Net.Http.HttpConnectionPool.CreateConnectionAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x002d8] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs:408
at System.Threading.Tasks.ValueTask`1[TResult].get_Result () [0x0001b] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/Threading/Tasks/ValueTask.cs:813
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync (System.Threading.Tasks.ValueTask`1[TResult] creationTask) [0x000a2] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs:543
at System.Threading.Tasks.ValueTask`1[TResult].get_Result () [0x0001b] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/Threading/Tasks/ValueTask.cs:813
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync (System.Net.Http.HttpRequestMessage request, System.Boolean doRequestAuth, System.Threading.CancellationToken cancellationToken) [0x0003f] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs:284
at System.Net.Http.RedirectHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00070] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs:32
at System.Net.Http.DecompressionHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00080] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/DecompressionHandler.cs:48
at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x000b3] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:531
at FFImageLoading.Cache.DownloadCache.DownloadAsync (System.String url, System.Threading.CancellationToken token, System.Net.Http.HttpClient client, FFImageLoading.Work.TaskParameter parameters, FFImageLoading.DownloadInformation downloadInformation) [0x00142] in C:\projects\ffimageloading\source\FFImageLoading.Common\Cache\DownloadCache.cs:107
at FFImageLoading.Cache.DownloadCache+<>c__DisplayClass15_0.<DownloadAndCacheIfNeededAsync>b__0 () [0x00050] in C:\projects\ffimageloading\source\FFImageLoading.Common\Cache\DownloadCache.cs:58
at FFImageLoading.Retry.DoAsync[T] (System.Func`1[TResult] action, System.TimeSpan retryInterval, System.Int32 retryCount, System.Action onRetry) [0x00047] in C:\projects\ffimageloading\source\FFImageLoading.Common\Helpers\Retry.cs:19
--- End of inner exception stack trace ---
at FFImageLoading.Retry.DoAsync[T] (System.Func`1[TResult] action, System.TimeSpan retryInterval, System.Int32 retryCount, System.Action onRetry) [0x0023b] in C:\projects\ffimageloading\source\FFImageLoading.Common\Helpers\Retry.cs:65
at FFImageLoading.Cache.DownloadCache.DownloadAndCacheIfNeededAsync (System.String url, FFImageLoading.Work.TaskParameter parameters, FFImageLoading.Config.Configuration configuration, System.Threading.CancellationToken token) [0x00401] in C:\projects\ffimageloading\source\FFImageLoading.Common\Cache\DownloadCache.cs:57
at FFImageLoading.DataResolvers.UrlDataResolver.Resolve (System.String identifier, FFImageLoading.Work.TaskParameter parameters, System.Threading.CancellationToken token) [0x00045] in C:\projects\ffimageloading\source\FFImageLoading.Common\DataResolvers\UrlDataResolver.cs:22
at FFImageLoading.DataResolvers.WrappedDataResolver.Resolve (System.String identifier, FFImageLoading.Work.TaskParameter parameters, System.Threading.CancellationToken token) [0x0004e] in C:\projects\ffimageloading\source\FFImageLoading.Common\DataResolvers\WrappedDataResolver.cs:21
at FFImageLoading.Work.ImageLoaderTask`3[TDecoderContainer,TImageContainer,TImageView].RunAsync () [0x00300] in C:\projects\ffimageloading\source\FFImageLoading.Common\Work\ImageLoaderTask.cs:618
So FFImageLoading is failing to load HTTPS images because the intermediate certificate issued by provider has expired.
So I provide my own instance of HttpClient (that has SSL bypass in its handler) on the MainPange.xaml.cs file by using ImageService.
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) => true;
_httpClient = new HttpClient(handler);
var config = new FFImageLoading.Config.Configuration()
{
...
HttpClient = _httpClient,
...
};
Source: https://github.com/luberda-molinet/FFImageLoading/issues/1448#issuecomment-941728729

Embedded mono + app.config

I have embedded mono in a c++ program and loaded a dll which requires an app.config. I am getting this kind of error, does someone have an idea on how to ship *.config with an embedded mono ?
The stack trace :
System.Configuration.ConfigurationErrorsException: Error Initializing the configuration system. ---> System.ArgumentException: The 'ExeConfigFilename' argument cannot be null.
at System.Configuration.ExeConfigurationHost.CheckFileMap (ConfigurationUserLevel level, System.Configuration.ExeConfigurationFileMap map) [0x00000] in <filename unknown>:0
at System.Configuration.ExeConfigurationHost.InitForConfiguration (System.String& locationSubPath, System.String& configPath, System.String& locationConfigPath, IInternalConfigRoot root, System.Object[] hostInitConfigurationParams) [0x00000] in <filename unknown>:0
at System.C[] hostInitConfigurationParams) [0x00000] in <filename unknown>:0
at System.Configuration.ConfigurationManager.OpenExeConfigurationInternal (ConfigurationUserLevel userLevel, System.Reflection.Assembly calling_assembly, System.String exePath) [0x00000] in <filename unknown>:0
at System.Configuration.ClientConfigurationSystem.get_Configuration () [0x00000] in <filename unknown>:0 onfiguration.InternalConfigurationSystem.InitForConfiguration (System.String& locationConfigPath, System.String& parentConfigPath, System.String& parentLocationConfigPath) [0x00000] in <filename unknown>:0
at System.Configuration.Configuration..ctor (System.Configuration.InternalConfigurationSystem system, System.String locationSubPath) [0x00000] in <filename unknown>:0
at System.Configuration.InternalConfigurationFactory.Create (System.Type typeConfigHost, System.Object
Self answer : you can't (as of 2013-04-30). To enable this behaviour, I had to change mono's framework sources mono/mcs/class/corlib/system/appdomain.cs :
public AppDomainSetup SetupInformation {
get {
return SetupInformationNoCopy; // newline
// AppDomainSetup setup = getSetup (); //old
// return new AppDomainSetup (setup); //old
}
}

RavenDB client onlinux connecting to windows server using mono http

I've just tried connecting to my RavenDB windows instance from linux using mono. I'm getting a bizarre error with it, that seems to be mono related rather than raven related.
Here is my recreate code (works on windows):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client.Document;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
try
{
var store = new DocumentStore()
{
ConnectionStringName = "RavenDB",
EnlistInDistributedTransactions = false
};
store.Initialize();
using (var session = store.OpenSession("system-events"))
{
session.Store(new { Name = "Test" });
session.SaveChanges();
}
Console.WriteLine("done");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}
and my mono version:
chris#x-ngx4:~/click/beta/Debug$ mono --version
Mono JIT compiler version 2.10.8.1 (Debian 2.10.8.1-1ubuntu2.2)
Copyright (C) 2002-2011 Novell, Inc, Xamarin, Inc and Contributors. www.mono-project.com
TLS: __thread
SIGSEGV: altstack
Notifications: epoll
Architecture: amd64
Disabled: none
Misc: softdebug
LLVM: supported, not enabled.
GC: Included Boehm (with typed GC and Parallel Mark)
and the error:
chris#x-ngx4:~/click/beta/Debug$ mono ConsoleApplication2.exe
System.IO.IOException: Internal error (no progress possible) Flush
at System.IO.Compression.DeflateStream.CheckResult (Int32 result, System.String where) [0x00000] in <filename unknown>:0
at System.IO.Compression.DeflateStream.Flush () [0x00000] in <filename unknown>:0
at System.IO.Compression.GZipStream.Flush () [0x00000] in <filename unknown>:0
at Raven.Abstractions.Connection.HttpRequestHelper.WriteDataToRequest (System.Net.HttpWebRequest req, System.String data, Boolean disableCompression) [0x00000] in <filename unknown>:0
at Raven.Client.Connection.HttpJsonRequest.Write (System.String data) [0x00000] in <filename unknown>:0
at Raven.Client.Connection.ServerClient.DirectBatch (IEnumerable`1 commandDatas, System.String operationUrl) [0x00000] in <filename unknown>:0
at Raven.Client.Connection.ServerClient+<>c__DisplayClass68.<Batch>b__67 (System.String u) [0x00000] in <filename unknown>:0
at Raven.Client.Connection.ReplicationInformer.TryOperation[BatchResult[]] (System.Func`2 operation, System.String operationUrl, Boolean avoidThrowing, Raven.Abstractions.Data.BatchResult[]& result) [0x00000] in <filename unknown>:0
I think I found it. DeflateStream has extern references to zlib. If you look at the zlib header file, you will find some comments:
deflate() returns Z_OK if some progress has been made (more input
processed or more output produced), Z_STREAM_END if all input has been
consumed and all output has been produced (only when flush is set to
Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for
example if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress
is possible (for example avail_in or avail_out was zero). Note that
Z_BUF_ERROR is not fatal, and deflate() can be called again with more
input and more output space to continue compressing.
The message Internal error (no progress possible) is what DeflateStream returns when getting a Z_BUF_ERROR - but it doesn't continue, it treats it as a hard stop. It should treat it as a warning and continue. At least, that's my interpretation.
Can you raise this with the mono support team? I'm not active in that group. Thanks.

Mono for Android External (SD card) File IO

I'm trying to create my first Mono for Android application, and have had permission errors trying to read or write from/to the sdcard. So I've switched to the SanityTests, xamarin-monodroid-samples-d76baf3.
Example_WorkingWithAudio RecordAudio.cs works successfully on internal storage. It also has the WRITE_EXTERNAL_STORAGE permission applied in the manifest; so I then uncommented the lines:
Java.IO.File sdDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMusic);
filePath = sdDir + "/" + "testAudio.mp3";
So that the code now reads:
Java.IO.File sdDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMusic);
filePath = sdDir + "/" + "testAudio.mp3";
Java.IO.File myFile = new Java.IO.File(filePath);
myFile.CreateNewFile();
I am executing this on a Sony Ericsson Xperia Mini Pro which runs Android 2.3.4.
When execution gets to the CreateNewFile() line, filePath has the value: "/mnt/sdcard/Music/testAudio.mp3".
This error is then thrown:
Java.IO.IOException: Exception of type 'Java.IO.IOException' was thrown.
at Android.Runtime.JNIEnv.CallBooleanMethod (IntPtr jobject, IntPtr jmethod) [0x00023] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.2.6-
branch/632e6ddf/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:156
at Java.IO.File.CreateNewFile () [0x0003e] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.2.6-
branch/632e6ddf/source/monodroid/src/Mono.Android/platforms/android-8/src/generated/Java.IO.File.cs:771
at Example_WorkingWithAudio.RecordAudio.StartRecorder () [0x00044] in c:\Users\Matt\Downloads\xamarin-monodroid-samples-d76baf3\xamarin-monodroid-samples-
d76baf3\Example_WorkingWithAudio\Example_WorkingWithAudio\RecordAudio.cs:35
--- End of managed exception stack trace ---
java.io.IOException: Permission denied
at java.io.File.createNewFileImpl(Native Method)
at java.io.File.createNewFile(File.java:1257)
at mono.android.view.View_OnClickListenerImplementor.n_onClick(Native Method)
at mono.android.view.View_OnClickListenerImplementor.onClick(View_OnClickListenerImplementor.java:29)
at android.view.View.performClick(View.java:2552)
at android.view.View$PerformClick.run(View.java:9229)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
What's the prob?
FYI, I also tried using the .Net classes:
FileStream fileStream = File.Create(filePath);
(where filePath is still "/mnt/sdcard/Music/testAudio.mp3")
But that line gives the exception:
System.IO.DirectoryNotFoundException: Could not find a part of the path "/mnt/sdcard/Music/testAudio.mp3".
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in <filename unknown>:0
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) [0x00000] in <filename unknown>:0
at System.IO.File.Create (System.String path, Int32 bufferSize) [0x00000] in <filename unknown>:0
at System.IO.File.Create (System.String path) [0x00000] in <filename unknown>:0
at Example_WorkingWithAudio.RecordAudio.StartRecorder () [0x0001d] in c:\Users\Matt\Downloads\xamarin-monodroid-samples-d76baf3\xamarin-monodroid-samples-d76baf3\Example_WorkingWithAudio\Example_WorkingWithAudio\RecordAudio.cs:33
This is how I have done this in Mono for Android.
var path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
path = Path.Combine(path, "testaudio.mp3");
I was running into the same exception and finally got it resolved by doing the following:
Create an sdcard file for the emulator. I wrote a post with a simple tutorial describing how to do this.
Using the code below (C#), I was able to write a file to the sdcard:
string pathToFile = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, _fileName);
using(var fileStream = new FileStream(pathToFile, FileMode.Append, FileAccess.Write, FileShare.None))
{
fileStream.Write(Encoding.ASCII.GetBytes(message), 0, Encoding.ASCII.GetByteCount(message));
}
if you are trying to downloading or get images from a server with xamarin forms you can use this:
File.WriteAllBytes("myimage.png",
new WebClient().DownloadData(http://www.dotnetperls.com/net.png));
Try this path:
String filePath = Environment.getExternalStorageDirectory() + "/testAudio.mp3";
File mFile = new File(filePath);

Hosting a WCF service in Mono console application on Mac Os X

When I try to host a WCF service, that works perfectly in Windows, in a mono console application I get the following error (*):
An element with the same key already exists in the dictionary.
I don't get at all why this is happening or where I need to look to fix this. Anyone who has experienced this or can point me in the right direction?
I am using Mono 2.10.8 on a Mac running Os X 10.6.8.
*Stacktrace:
at System.Collections.ObjectModel.KeyedCollection`2[System.Type,System.ServiceModel.Description.IOperationBehavior].InsertItem (Int32 index, IOperationBehavior item) [0x0003a] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/corlib/System.Collections.ObjectModel/KeyedCollection.cs:168
at System.Collections.Generic.KeyedByTypeCollection`1[System.ServiceModel.Description.IOperationBehavior].InsertItem (Int32 index, IOperationBehavior kind) [0x00000] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.Collections.Generic/KeyedByTypeCollection.cs:70
at System.Collections.ObjectModel.Collection`1[System.ServiceModel.Description.IOperationBehavior].Add (IOperationBehavior item) [0x0000c] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/corlib/System.Collections.ObjectModel/Collection.cs:74
at System.ServiceModel.Description.ContractDescriptionGenerator.GetOrCreateOperation (System.ServiceModel.Description.ContractDescription cd, System.Reflection.MethodInfo mi, System.Reflection.MethodInfo serviceMethod, System.ServiceModel.OperationContractAttribute oca, System.Type asyncReturnType, Boolean isCallback, System.Type givenServiceType) [0x00511] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs:350
at System.ServiceModel.Description.ContractDescriptionGenerator.FillOperationsForInterface (System.ServiceModel.Description.ContractDescription cd, System.Type exactContractType, System.Type givenServiceType, Boolean isCallback) [0x00131] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs:240
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContractInternal (System.Type givenContractType, System.Type givenServiceType, System.Type serviceTypeForCallback) [0x001ed] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs:190
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContract (System.Type givenContractType, System.Type givenServiceType, System.Type serviceTypeForCallback) [0x00000] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs:136
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContract (System.Type givenContractType, System.Type givenServiceType) [0x00000] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs:131
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContract (System.Type contractType) [0x00000] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs:101
at System.ServiceModel.Description.ContractDescription.GetContract (System.Type contractType) [0x00017] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescription.cs:66
at System.ServiceModel.ServiceHost.AddServiceEndpoint (System.Type implementedContract, System.ServiceModel.Channels.Binding binding, System.Uri address, System.Uri listenUri) [0x00022] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.ServiceModel/ServiceHost.cs:96
at System.ServiceModel.ServiceHost.AddServiceEndpoint (System.Type implementedContract, System.ServiceModel.Channels.Binding binding, System.Uri address) [0x00000] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.ServiceModel/System.ServiceModel/ServiceHost.cs:85
at ConsoleApplication3.Program.Main (System.String[] args) [0x0002b] in /Users/steven/Software/ABC Cloud/NooSphere/Mono.Host/Main.cs:16
This was a bug in Mono and has been fixed in mono-2.10.9 (Mac only updated) and Mono for Android 4.2.7