diff options
Diffstat (limited to 'csharp/src')
188 files changed, 15081 insertions, 18340 deletions
diff --git a/csharp/src/Glacier2/.depend.mak b/csharp/src/Glacier2/.depend.mak deleted file mode 100644 index a29c2fa8ecb..00000000000 --- a/csharp/src/Glacier2/.depend.mak +++ /dev/null @@ -1,29 +0,0 @@ - -Metrics.cs: \ - "$(slicedir)\Glacier2\Metrics.ice" \ - "$(slicedir)/Ice/Metrics.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -PermissionsVerifier.cs: \ - "$(slicedir)\Glacier2\PermissionsVerifier.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Router.cs: \ - "$(slicedir)\Glacier2\Router.ice" \ - "$(slicedir)/Ice/Router.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/Glacier2/PermissionsVerifier.ice" - -Session.cs: \ - "$(slicedir)\Glacier2\Session.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" - -SSLInfo.cs: \ - "$(slicedir)\Glacier2\SSLInfo.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" diff --git a/csharp/src/Glacier2/Application.cs b/csharp/src/Glacier2/Application.cs index c620a83238b..b241aff9e70 100644 --- a/csharp/src/Glacier2/Application.cs +++ b/csharp/src/Glacier2/Application.cs @@ -9,10 +9,6 @@ using System; using System.Diagnostics; -using System.Collections.Generic; -using System.Threading; - -#if !SILVERLIGHT namespace Glacier2 { @@ -32,7 +28,7 @@ public abstract class Application : Ice.Application /// <summary> /// This exception is raised if the session should be restarted. /// </summary> - public class RestartSessionException : System.Exception + public class RestartSessionException : Exception { } @@ -137,7 +133,7 @@ public abstract class Application : Ice.Application /// Returns the Glacier2 session proxy. /// </summary> /// <returns>The session proxy.</returns> - public static Glacier2.SessionPrx + public static SessionPrx session() { return _session; @@ -194,7 +190,7 @@ public abstract class Application : Ice.Application throw new SessionNotExistException(); } - lock(mutex__) + lock(iceMutex) { if(_adapter == null) { @@ -205,26 +201,6 @@ public abstract class Application : Ice.Application return _adapter; } - private class ConnectionCallbackI : Ice.ConnectionCallback - { - internal ConnectionCallbackI(Application application) - { - _application = application; - } - - public void heartbeat(Ice.Connection con) - { - - } - - public void closed(Ice.Connection con) - { - _application.sessionDestroyed(); - } - - private readonly Application _application; - } - protected override int doMain(string[] originArgs, Ice.InitializationData initData) { @@ -259,21 +235,21 @@ public abstract class Application : Ice.Application // Reset internal state variables from Ice.Application. The // remainder are reset at the end of this method. // - callbackInProgress__ = false; - destroyed__ = false; - interrupted__ = false; + iceCallbackInProgress = false; + iceDestroyed = false; + iceInterrupted = false; bool restart = false; status = 0; try { - communicator__ = Ice.Util.initialize(ref args, initData); + iceCommunicator = Ice.Util.initialize(ref args, initData); - _router = Glacier2.RouterPrxHelper.uncheckedCast(communicator().getDefaultRouter()); + _router = RouterPrxHelper.uncheckedCast(communicator().getDefaultRouter()); if(_router == null) { - Ice.Util.getProcessLogger().error(appName__ + ": no Glacier2 router configured"); + Ice.Util.getProcessLogger().error(iceAppName + ": no Glacier2 router configured"); status = 1; } else @@ -281,7 +257,7 @@ public abstract class Application : Ice.Application // // The default is to destroy when a signal is received. // - if(signalPolicy__ == Ice.SignalPolicy.HandleSignals) + if(iceSignalPolicy == Ice.SignalPolicy.HandleSignals) { destroyOnInterrupt(); } @@ -318,8 +294,8 @@ public abstract class Application : Ice.Application { Ice.Connection connection = _router.ice_getCachedConnection(); Debug.Assert(connection != null); - connection.setACM((int)acmTimeout, Ice.Util.None, Ice.ACMHeartbeat.HeartbeatAlways); - connection.setCallback(new ConnectionCallbackI(this)); + connection.setACM(acmTimeout, Ice.Util.None, Ice.ACMHeartbeat.HeartbeatAlways); + connection.setCloseCallback(_ => sessionDestroyed()); } _category = _router.getCategoryForClient(); status = runWithSession(args); @@ -366,7 +342,7 @@ public abstract class Application : Ice.Application Ice.Util.getProcessLogger().error(ex.ToString()); status = 1; } - catch(System.Exception ex) + catch(Exception ex) { Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString()); status = 1; @@ -377,28 +353,28 @@ public abstract class Application : Ice.Application // (post-run), it would not make sense to release a held // signal to run shutdown or destroy. // - if(signalPolicy__ == Ice.SignalPolicy.HandleSignals) + if(iceSignalPolicy == Ice.SignalPolicy.HandleSignals) { ignoreInterrupt(); } - lock(mutex__) + lock(iceMutex) { - while(callbackInProgress__) + while(iceCallbackInProgress) { - System.Threading.Monitor.Wait(mutex__); + System.Threading.Monitor.Wait(iceMutex); } - if(destroyed__) + if(iceDestroyed) { - communicator__ = null; + iceCommunicator = null; } else { - destroyed__ = true; + iceDestroyed = true; // - // And communicator__ != null, meaning will be - // destroyed next, destroyed__ = true also ensures that + // And iceCommunicator != null, meaning will be + // destroyed next, iceDestroyed = true also ensures that // any remaining callback won't do anything // } @@ -416,13 +392,13 @@ public abstract class Application : Ice.Application // Expected if another thread invoked on an object from the session concurrently. // } - catch(Glacier2.SessionNotExistException) + catch(SessionNotExistException) { // // This can also occur. // } - catch(System.Exception ex) + catch(Exception ex) { // // Not expected. @@ -433,28 +409,28 @@ public abstract class Application : Ice.Application _router = null; } - if(communicator__ != null) + if(iceCommunicator != null) { try { - communicator__.destroy(); + iceCommunicator.destroy(); } catch(Ice.LocalException ex) { Ice.Util.getProcessLogger().error(ex.ToString()); status = 1; } - catch(System.Exception ex) + catch(Exception ex) { Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString()); status = 1; } - communicator__ = null; + iceCommunicator = null; } // // Reset internal state. We cannot reset the Application state - // here, since destroyed__ must remain true until we re-run + // here, since iceDestroyed must remain true until we re-run // this method. // _adapter = null; @@ -467,11 +443,10 @@ public abstract class Application : Ice.Application } private static Ice.ObjectAdapter _adapter; - private static Glacier2.RouterPrx _router; - private static Glacier2.SessionPrx _session; + private static RouterPrx _router; + private static SessionPrx _session; private static bool _createdSession = false; private static string _category; } } -#endif diff --git a/csharp/src/Glacier2/AssemblyInfo.cs b/csharp/src/Glacier2/AssemblyInfo.cs index 297deeefeff..68aec72e5f9 100644 --- a/csharp/src/Glacier2/AssemblyInfo.cs +++ b/csharp/src/Glacier2/AssemblyInfo.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/Glacier2/Makefile b/csharp/src/Glacier2/Makefile deleted file mode 100644 index 64b0f432720..00000000000 --- a/csharp/src/Glacier2/Makefile +++ /dev/null @@ -1,54 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -PKG = Glacier2 -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)/$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = Application.cs \ - AssemblyInfo.cs \ - SessionCallback.cs \ - SessionFactoryHelper.cs \ - SessionHelper.cs - -SLICE_SRCS = $(SDIR)/Metrics.ice \ - $(SDIR)/PermissionsVerifier.ice \ - $(SDIR)/Router.ice \ - $(SDIR)/Session.ice \ - $(SDIR)/SSLInfo.ice - -SDIR = $(slicedir)/Glacier2 -GDIR = generated - -include $(top_srcdir)/config/Make.rules.cs - -MCSFLAGS := $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS := $(MCSFLAGS) -keyfile:$(KEYFILE) -MCSFLAGS := $(MCSFLAGS) /doc:$(assembliesdir)/$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS := $(SLICE2CSFLAGS) -I$(slicedir) --ice - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) $(call ref,Ice) $(subst /,$(DSEP),$^) - -install:: all - (cd $(assembliesdir); $(call installassembly,$(LIBNAME),$(PKG)); $(call installpolicy,$(POLICY)); \ - $(call installmdb,$(LIBNAME).mdb); \ - $(call installdata,$(PKG).xml,$(DESTDIR)$(install_assembliesdir))) - -ifeq ($(GACINSTALL),yes) -install:: all - $(call installdata,../../lib/pkgconfig/$(PKG).pc,$(DESTDIR)$(install_pkgconfigdir)) -endif - -clean:: - -rm -f $(assembliesdir)/$(PKG).xml diff --git a/csharp/src/Glacier2/Makefile.mak b/csharp/src/Glacier2/Makefile.mak deleted file mode 100755 index ea981d06632..00000000000 --- a/csharp/src/Glacier2/Makefile.mak +++ /dev/null @@ -1,61 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -PKG = Glacier2 -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)\$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = Application.cs \ - AssemblyInfo.cs \ - SessionCallback.cs \ - SessionFactoryHelper.cs \ - SessionHelper.cs - -GEN_SRCS = $(GDIR)\Metrics.cs \ - $(GDIR)\PermissionsVerifier.cs \ - $(GDIR)\Router.cs \ - $(GDIR)\Session.cs \ - $(GDIR)\SSLInfo.cs - -SDIR = $(slicedir)\Glacier2 -GDIR = generated - -!include $(top_srcdir)/config/Make.rules.mak.cs - -MCSFLAGS = $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS = $(MCSFLAGS) -keyfile:"$(KEYFILE)" -MCSFLAGS = $(MCSFLAGS) /doc:$(assembliesdir)\$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS = $(SLICE2CSFLAGS) -I$(slicedir) --ice - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) /baseaddress:0x22000000 $(MCSFLAGS) -r:$(refdir)\Ice.dll $(SRCS) $(GEN_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -!if "$(DEBUG)" == "yes" -clean:: - del /q $(assembliesdir)\$(PKG).pdb -!endif - -clean:: - del /q $(assembliesdir)\$(PKG).xml - -install:: all - copy $(assembliesdir)\$(LIBNAME) "$(install_assembliesdir)" - copy $(assembliesdir)\$(PKG).xml "$(install_assembliesdir)" -!if "$(generate_policies)" == "yes" - copy $(assembliesdir)\$(POLICY_TARGET) "$(install_assembliesdir)" -!endif -!if "$(DEBUG)" == "yes" - copy $(assembliesdir)\$(PKG).pdb "$(install_assembliesdir)" -!endif diff --git a/csharp/src/Glacier2/SessionFactoryHelper.cs b/csharp/src/Glacier2/SessionFactoryHelper.cs index 9ca34d50d5f..d29978e1f37 100644 --- a/csharp/src/Glacier2/SessionFactoryHelper.cs +++ b/csharp/src/Glacier2/SessionFactoryHelper.cs @@ -147,13 +147,13 @@ public class SessionFactoryHelper { return getProtocol().Equals("ssl"); } - + /// <summary> /// Sets the protocol that will be used by the session factory to establish the connection.. /// </summary> /// <param name="protocol">The protocol.</param> public void - setProtocol(String protocol) + setProtocol(string protocol) { lock(this) { @@ -161,7 +161,7 @@ public class SessionFactoryHelper { throw new ArgumentException("You must use a valid protocol"); } - + if(!protocol.Equals("tcp") && !protocol.Equals("ssl") && !protocol.Equals("wss") && @@ -177,7 +177,7 @@ public class SessionFactoryHelper /// Returns the protocol that will be used by the session factory to establish the connection. /// </summary> /// <returns>The protocol.</returns> - public String + public string getProtocol() { lock(this) @@ -240,11 +240,11 @@ public class SessionFactoryHelper return getPortInternal(); } } - + private int getPortInternal() { - return _port == 0 ? ((_protocol.Equals("ssl") || + return _port == 0 ? ((_protocol.Equals("ssl") || _protocol.Equals("wss"))? GLACIER2_SSL_PORT : GLACIER2_TCP_PORT) : _port; } @@ -362,7 +362,7 @@ public class SessionFactoryHelper // plug-in has already been setup we don't want to override the // configuration so it can be loaded from a custom location. // - if((_protocol.Equals("ssl") || _protocol.Equals("wss")) && + if((_protocol.Equals("ssl") || _protocol.Equals("wss")) && initData.properties.getProperty("Ice.Plugin.IceSSL").Length == 0) { initData.properties.setProperty("Ice.Plugin.IceSSL", "IceSSL:IceSSL.PluginFactory"); @@ -383,8 +383,8 @@ public class SessionFactoryHelper { StringBuilder sb = new StringBuilder(); sb.Append("\""); - sb.Append(Ice.Util.identityToString(ident)); - sb.Append("\":"); + sb.Append(Ice.Util.identityToString(ident, Ice.ToStringMode.Unicode)); + sb.Append("\":"); sb.Append(_protocol + " -p "); sb.Append(getPortInternal()); sb.Append(" -h \""); diff --git a/csharp/src/Glacier2/SessionHelper.cs b/csharp/src/Glacier2/SessionHelper.cs index f115116f956..547221e8924 100644 --- a/csharp/src/Glacier2/SessionHelper.cs +++ b/csharp/src/Glacier2/SessionHelper.cs @@ -20,26 +20,6 @@ namespace Glacier2 /// </summary> public class SessionHelper { - private class ConnectionCallbackI : Ice.ConnectionCallback - { - internal ConnectionCallbackI(SessionHelper sessionHelper) - { - _sessionHelper = sessionHelper; - } - - public void heartbeat(Ice.Connection con) - { - - } - - public void closed(Ice.Connection con) - { - _sessionHelper.destroy(); - } - - private readonly SessionHelper _sessionHelper; - } - /// <summary> /// Creates a Glacier2 session. /// </summary> @@ -320,7 +300,7 @@ public class SessionHelper Ice.Connection connection = _router.ice_getCachedConnection(); Debug.Assert(connection != null); connection.setACM(acmTimeout, Ice.Util.None, Ice.ACMHeartbeat.HeartbeatAlways); - connection.setCallback(new ConnectionCallbackI(this)); + connection.setCloseCallback(_ => destroy()); } } @@ -330,7 +310,7 @@ public class SessionHelper { _callback.connected(this); } - catch(Glacier2.SessionNotExistException) + catch(SessionNotExistException) { destroy(); } @@ -340,7 +320,7 @@ public class SessionHelper private void destroyInternal() { - Glacier2.RouterPrx router; + RouterPrx router; Ice.Communicator communicator; lock(this) { @@ -381,13 +361,7 @@ public class SessionHelper communicator.getLogger().warning("SessionHelper: unexpected exception when destroying the session:\n" + e); } - try - { - communicator.destroy(); - } - catch(Exception) - { - } + communicator.destroy(); // Notify the callback that the session is gone. dispatchCallback(() => @@ -404,16 +378,11 @@ public class SessionHelper { communicator = _communicator; } - try - { - communicator.destroy(); - } - catch(Exception) - { - } + + communicator.destroy(); } - delegate Glacier2.SessionPrx ConnectStrategy(Glacier2.RouterPrx router); + delegate SessionPrx ConnectStrategy(RouterPrx router); private void connectImpl(ConnectStrategy factory) @@ -473,19 +442,14 @@ public class SessionHelper _callback.createdCommunicator(this); }); - Glacier2.RouterPrx routerPrx = Glacier2.RouterPrxHelper.uncheckedCast(_communicator.getDefaultRouter()); - Glacier2.SessionPrx session = factory(routerPrx); + RouterPrx routerPrx = RouterPrxHelper.uncheckedCast(_communicator.getDefaultRouter()); + SessionPrx session = factory(routerPrx); connected(routerPrx, session); } catch(Exception ex) { - try - { - _communicator.destroy(); - } - catch(Exception) - { - } + _communicator.destroy(); + dispatchCallback(() => { _callback.connectFailed(this, ex); @@ -494,13 +458,8 @@ public class SessionHelper })).Start(); } -#if COMPACT private void - dispatchCallback(Ice.VoidAction callback, Ice.Connection conn) -#else - private void - dispatchCallback(System.Action callback, Ice.Connection conn) -#endif + dispatchCallback(Action callback, Ice.Connection conn) { if(_initData.dispatcher != null) { @@ -512,13 +471,8 @@ public class SessionHelper } } -#if COMPACT - private void - dispatchCallbackAndWait(Ice.VoidAction callback) -#else private void - dispatchCallbackAndWait(System.Action callback) -#endif + dispatchCallbackAndWait(Action callback) { if(_initData.dispatcher != null) { @@ -539,8 +493,8 @@ public class SessionHelper private readonly Ice.InitializationData _initData; private Ice.Communicator _communicator; private Ice.ObjectAdapter _adapter; - private Glacier2.RouterPrx _router; - private Glacier2.SessionPrx _session; + private RouterPrx _router; + private SessionPrx _session; private bool _connected = false; private string _category; private string _finderStr; diff --git a/csharp/src/Glacier2/generated/.gitignore b/csharp/src/Glacier2/generated/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/csharp/src/Glacier2/generated/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/csharp/src/Glacier2/msbuild/glacier2.csproj b/csharp/src/Glacier2/msbuild/glacier2.csproj new file mode 100644 index 00000000000..2bfdcb84ca8 --- /dev/null +++ b/csharp/src/Glacier2/msbuild/glacier2.csproj @@ -0,0 +1,93 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{D765A8A0-01C2-4EEE-B6C0-5DD6F9C1087A}</ProjectGuid> + <OutputType>Library</OutputType> + <AssemblyName>Glacier2</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\Assemblies\Glacier2.XML</DocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\Application.cs"> + <Link>Application.cs</Link> + </Compile> + <Compile Include="..\AssemblyInfo.cs"> + <Link>AssemblyInfo.cs</Link> + </Compile> + <Compile Include="..\SessionCallback.cs"> + <Link>SessionCallback.cs</Link> + </Compile> + <Compile Include="..\SessionFactoryHelper.cs"> + <Link>SessionFactoryHelper.cs</Link> + </Compile> + <Compile Include="..\SessionHelper.cs"> + <Link>SessionHelper.cs</Link> + </Compile> + <Compile Include="generated\Metrics.cs" /> + <Compile Include="generated\PermissionsVerifier.cs" /> + <Compile Include="generated\PermissionsVerifierF.cs" /> + <Compile Include="generated\Router.cs" /> + <Compile Include="generated\RouterF.cs" /> + <Compile Include="generated\Session.cs" /> + <Compile Include="generated\SSLInfo.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\slice\Glacier2\Metrics.ice"> + <Link>Metrics.ice</Link> + </None> + <None Include="..\..\..\..\slice\Glacier2\PermissionsVerifier.ice"> + <Link>PermissionsVerifier.ice</Link> + </None> + <None Include="..\..\..\..\slice\Glacier2\PermissionsVerifierF.ice"> + <Link>PermissionsVerifierF.ice</Link> + </None> + <None Include="..\..\..\..\slice\Glacier2\Router.ice"> + <Link>Router.ice</Link> + </None> + <None Include="..\..\..\..\slice\Glacier2\RouterF.ice"> + <Link>RouterF.ice</Link> + </None> + <None Include="..\..\..\..\slice\Glacier2\Session.ice"> + <Link>Session.ice</Link> + </None> + <None Include="..\..\..\..\slice\Glacier2\SSLInfo.ice"> + <Link>SSLInfo.ice</Link> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\Ice\msbuild\ice.csproj"> + <Project>{7cb4715e-dd8b-48f8-b478-27b8bd4008c7}</Project> + <Name>ice</Name> + <Private>False</Private> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\config\ice.sign.targets" /> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/Ice/.depend.mak b/csharp/src/Ice/.depend.mak deleted file mode 100644 index 48e527e7f4a..00000000000 --- a/csharp/src/Ice/.depend.mak +++ /dev/null @@ -1,144 +0,0 @@ - -BuiltinSequences.cs: \ - "$(slicedir)\Ice\BuiltinSequences.ice" - -Communicator.cs: \ - "$(slicedir)\Ice\Communicator.ice" \ - "$(slicedir)/Ice/LoggerF.ice" \ - "$(slicedir)/Ice/InstrumentationF.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/ObjectFactoryF.ice" \ - "$(slicedir)/Ice/RouterF.ice" \ - "$(slicedir)/Ice/LocatorF.ice" \ - "$(slicedir)/Ice/PluginF.ice" \ - "$(slicedir)/Ice/ImplicitContextF.ice" \ - "$(slicedir)/Ice/Current.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/FacetMap.ice" - -Connection.cs: \ - "$(slicedir)\Ice\Connection.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Endpoint.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/EndpointF.ice" - -Current.cs: \ - "$(slicedir)\Ice\Current.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" - -Endpoint.cs: \ - "$(slicedir)\Ice\Endpoint.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/EndpointF.ice" - -EndpointTypes.cs: \ - "$(slicedir)\Ice\EndpointTypes.ice" - -FacetMap.cs: \ - "$(slicedir)\Ice\FacetMap.ice" - -Identity.cs: \ - "$(slicedir)\Ice\Identity.ice" - -ImplicitContext.cs: \ - "$(slicedir)\Ice\ImplicitContext.ice" \ - "$(slicedir)/Ice/LocalException.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Current.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" - -Instrumentation.cs: \ - "$(slicedir)\Ice\Instrumentation.ice" \ - "$(slicedir)/Ice/EndpointF.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" \ - "$(slicedir)/Ice/Current.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" - -LocalException.cs: \ - "$(slicedir)\Ice\LocalException.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Locator.cs: \ - "$(slicedir)\Ice\Locator.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/ProcessF.ice" - -Logger.cs: \ - "$(slicedir)\Ice\Logger.ice" - -Metrics.cs: \ - "$(slicedir)\Ice\Metrics.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -ObjectAdapter.cs: \ - "$(slicedir)\Ice\ObjectAdapter.ice" \ - "$(slicedir)/Ice/CommunicatorF.ice" \ - "$(slicedir)/Ice/ServantLocatorF.ice" \ - "$(slicedir)/Ice/LocatorF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/FacetMap.ice" \ - "$(slicedir)/Ice/Endpoint.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/EndpointF.ice" - -ObjectFactory.cs: \ - "$(slicedir)\Ice\ObjectFactory.ice" - -Plugin.cs: \ - "$(slicedir)\Ice\Plugin.ice" \ - "$(slicedir)/Ice/LoggerF.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Process.cs: \ - "$(slicedir)\Ice\Process.ice" - -Properties.cs: \ - "$(slicedir)\Ice\Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -PropertiesAdmin.cs: \ - "$(slicedir)\Ice\PropertiesAdmin.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -RemoteLogger.cs: \ - "$(slicedir)\Ice\RemoteLogger.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Router.cs: \ - "$(slicedir)\Ice\Router.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -ServantLocator.cs: \ - "$(slicedir)\Ice\ServantLocator.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/Current.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" - -SliceChecksumDict.cs: \ - "$(slicedir)\Ice\SliceChecksumDict.ice" - -Version.cs: \ - "$(slicedir)\Ice\Version.ice" diff --git a/csharp/src/Ice/ACM.cs b/csharp/src/Ice/ACM.cs index 9abef7bda64..28a8b0427b7 100644 --- a/csharp/src/Ice/ACM.cs +++ b/csharp/src/Ice/ACM.cs @@ -34,7 +34,7 @@ namespace IceInternal else { timeoutProperty = prefix + ".Timeout"; - }; + } timeout = p.getPropertyAsIntWithDefault(timeoutProperty, dflt.timeout / 1000) * 1000; @@ -71,7 +71,7 @@ namespace IceInternal public int timeout; public Ice.ACMHeartbeat heartbeat; public Ice.ACMClose close; - }; + } public interface ACMMonitor : TimerTask { @@ -81,7 +81,7 @@ namespace IceInternal ACMMonitor acm(Ice.Optional<int> timeout, Ice.Optional<Ice.ACMClose> c, Ice.Optional<Ice.ACMHeartbeat> h); Ice.ACM getACM(); - }; + } class FactoryACMMonitor : ACMMonitor { @@ -95,7 +95,7 @@ namespace IceInternal public readonly Ice.ConnectionI connection; public readonly bool remove; - }; + } internal FactoryACMMonitor(Instance instance, ACMConfig config) { @@ -269,7 +269,7 @@ namespace IceInternal private HashSet<Ice.ConnectionI> _connections = new HashSet<Ice.ConnectionI>(); private List<Change> _changes = new List<Change>(); private List<Ice.ConnectionI> _reapedConnections = new List<Ice.ConnectionI>(); - }; + } internal class ConnectionACMMonitor : ACMMonitor { @@ -352,5 +352,5 @@ namespace IceInternal readonly private ACMConfig _config; private Ice.ConnectionI _connection; - }; + } } diff --git a/csharp/src/Ice/AMDCallback.cs b/csharp/src/Ice/AMDCallback.cs deleted file mode 100644 index 2e05e41d0d7..00000000000 --- a/csharp/src/Ice/AMDCallback.cs +++ /dev/null @@ -1,26 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -namespace Ice -{ - /// <summary> - /// AMDCallback is the interface from which all AMD callbacks are derived. - /// </summary> - public interface AMDCallback - { - /// <summary> - /// Indicates to the Ice run time that an operation completed - /// with a run-time exception. - /// </summary> - /// <param name="ex">The encoded Ice run-time exception. Note that, if ex - /// is a user exception, the caller receives UnknownUserException. - /// Use ice_response to raise user exceptions.</param> - void ice_exception(System.Exception ex); - } -} diff --git a/csharp/src/Ice/Application.cs b/csharp/src/Ice/Application.cs index 29391813126..b7a15c2184a 100644 --- a/csharp/src/Ice/Application.cs +++ b/csharp/src/Ice/Application.cs @@ -7,8 +7,6 @@ // // ********************************************************************** -#if !SILVERLIGHT - namespace Ice { using System; @@ -20,17 +18,10 @@ namespace Ice internal static class NativeMethods { -#if !COMPACT && !UNITY - // - // Technically it's not necessary to wrap DllImport in conditional compilation because - // the binding occurs at run time and it will never be executed on Mono. However, it - // causes problems for the Compact Framework. - // [DllImport("kernel32.dll")] [return: MarshalAsAttribute(UnmanagedType.Bool)] internal static extern bool SetConsoleCtrlHandler(CtrlCEventHandler eh, [MarshalAsAttribute(UnmanagedType.Bool)]bool add); -#endif } /// <summary> @@ -87,19 +78,13 @@ namespace Ice } /// <summary> - /// Initializes an instance that calls Communicator.shutdown if a signal is received. - /// </summary> - public Application() - { - } - - /// <summary> /// Initializes an instance that handles signals according to the signal policy. + /// If not signal policy is provided the default SinalPolicy.NoSignalHandling + /// will be used, which calls Communicator.shutdown if a signal is received. /// </summary> /// <param name="signalPolicy">Determines how to respond to signals.</param> - public Application(SignalPolicy signalPolicy) + public Application(SignalPolicy signalPolicy = SignalPolicy.NoSignalHandling) { - signalPolicy__ = signalPolicy; } /// <summary> @@ -139,7 +124,7 @@ namespace Ice { if(Util.getProcessLogger() is ConsoleLoggerI) { - Util.setProcessLogger(new ConsoleLoggerI(appName__)); + Util.setProcessLogger(new ConsoleLoggerI(iceAppName)); } InitializationData initData = new InitializationData(); @@ -182,10 +167,10 @@ namespace Ice { if(Util.getProcessLogger() is ConsoleLoggerI) { - Util.setProcessLogger(new ConsoleLoggerI(appName__)); + Util.setProcessLogger(new ConsoleLoggerI(iceAppName)); } - if(communicator__ != null) + if(iceCommunicator != null) { Util.getProcessLogger().error("only one instance of the Application class can be used"); return 1; @@ -218,25 +203,15 @@ namespace Ice Util.getProcessLogger().error("unknown exception:\n" + ex); return 1; } - appName__ = initData.properties.getPropertyWithDefault("Ice.ProgramName", appName__); + iceAppName = initData.properties.getPropertyWithDefault("Ice.ProgramName", iceAppName); - nohup__ = initData.properties.getPropertyAsInt("Ice.Nohup") > 0; + iceNohup = initData.properties.getPropertyAsInt("Ice.Nohup") > 0; _application = this; int status; -#if COMPACT || UNITY - status = doMain(args, initData); -#else - if(signalPolicy__ == SignalPolicy.HandleSignals) + if(iceSignalPolicy == SignalPolicy.HandleSignals) { - if(IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows) - { - _signals = new WindowsSignals(); - } - else - { - _signals = new MonoSignals(); - } + _signals = new WindowsSignals(); _signals.register(_handler); status = doMain(args, initData); @@ -248,7 +223,6 @@ namespace Ice { status = doMain(args, initData); } -#endif return status; } @@ -262,7 +236,7 @@ namespace Ice /// <returns>The name of the application.</returns> public static string appName() { - return appName__; + return iceAppName; } /// <summary> @@ -273,7 +247,7 @@ namespace Ice /// <returns>The communicator for the application.</returns> public static Communicator communicator() { - return communicator__; + return iceCommunicator; } /// <summary> @@ -282,14 +256,14 @@ namespace Ice /// </summary> public static void destroyOnInterrupt() { - if(signalPolicy__ == SignalPolicy.HandleSignals) + if(iceSignalPolicy == SignalPolicy.HandleSignals) { - lock(mutex__) + lock(iceMutex) { if(_callback == _holdCallback) { - released__ = true; - System.Threading.Monitor.Pulse(mutex__); + iceReleased = true; + System.Threading.Monitor.Pulse(iceMutex); } _callback = _destroyCallback; } @@ -306,14 +280,14 @@ namespace Ice /// </summary> public static void shutdownOnInterrupt() { - if(signalPolicy__ == SignalPolicy.HandleSignals) + if(iceSignalPolicy == SignalPolicy.HandleSignals) { - lock(mutex__) + lock(iceMutex) { if(_callback == _holdCallback) { - released__ = true; - System.Threading.Monitor.Pulse(mutex__); + iceReleased = true; + System.Threading.Monitor.Pulse(iceMutex); } _callback = _shutdownCallback; } @@ -330,14 +304,14 @@ namespace Ice /// </summary> public static void ignoreInterrupt() { - if(signalPolicy__ == SignalPolicy.HandleSignals) + if(iceSignalPolicy == SignalPolicy.HandleSignals) { - lock(mutex__) + lock(iceMutex) { if(_callback == _holdCallback) { - released__ = true; - System.Threading.Monitor.Pulse(mutex__); + iceReleased = true; + System.Threading.Monitor.Pulse(iceMutex); } _callback = null; } @@ -355,14 +329,14 @@ namespace Ice /// </summary> public static void callbackOnInterrupt() { - if(signalPolicy__ == SignalPolicy.HandleSignals) + if(iceSignalPolicy == SignalPolicy.HandleSignals) { - lock(mutex__) + lock(iceMutex) { if(_callback == _holdCallback) { - released__ = true; - System.Threading.Monitor.Pulse(mutex__); + iceReleased = true; + System.Threading.Monitor.Pulse(iceMutex); } _callback = _userCallback; } @@ -379,14 +353,14 @@ namespace Ice /// </summary> public static void holdInterrupt() { - if(signalPolicy__ == SignalPolicy.HandleSignals) + if(iceSignalPolicy == SignalPolicy.HandleSignals) { - lock(mutex__) + lock(iceMutex) { if(_callback != _holdCallback) { _previousCallback = _callback; - released__ = false; + iceReleased = false; _callback = _holdCallback; } // else, we were already holding signals @@ -405,22 +379,22 @@ namespace Ice /// </summary> public static void releaseInterrupt() { - if(signalPolicy__ == SignalPolicy.HandleSignals) + if(iceSignalPolicy == SignalPolicy.HandleSignals) { - lock(mutex__) + lock(iceMutex) { if(_callback == _holdCallback) { // // Note that it's very possible no signal is held; // in this case the callback is just replaced and - // setting released__ to true and signalling this + // setting iceReleased to true and signalling this // will do no harm. // - released__ = true; + iceReleased = true; _callback = _previousCallback; - System.Threading.Monitor.Pulse(mutex__); + System.Threading.Monitor.Pulse(iceMutex); } // Else nothing to release. } @@ -439,9 +413,9 @@ namespace Ice /// <returns>True if a signal caused the communicator to shut down; false otherwise.</returns> public static bool interrupted() { - lock(mutex__) + lock(iceMutex) { - return interrupted__; + return iceInterrupted; } } @@ -461,13 +435,13 @@ namespace Ice Util.setProcessLogger(new ConsoleLoggerI(initData.properties.getProperty("Ice.ProgramName"))); } - communicator__ = Util.initialize(ref args, initData); - destroyed__ = false; + iceCommunicator = Util.initialize(ref args, initData); + iceDestroyed = false; // // The default is to destroy when a signal is received. // - if(signalPolicy__ == SignalPolicy.HandleSignals) + if(iceSignalPolicy == SignalPolicy.HandleSignals) { destroyOnInterrupt(); } @@ -490,38 +464,38 @@ namespace Ice // (post-run), it would not make sense to release a held // signal to run shutdown or destroy. // - if(signalPolicy__ == SignalPolicy.HandleSignals) + if(iceSignalPolicy == SignalPolicy.HandleSignals) { ignoreInterrupt(); } - lock(mutex__) + lock(iceMutex) { - while(callbackInProgress__) + while(iceCallbackInProgress) { - System.Threading.Monitor.Wait(mutex__); + System.Threading.Monitor.Wait(iceMutex); } - if(destroyed__) + if(iceDestroyed) { - communicator__ = null; + iceCommunicator = null; } else { - destroyed__ = true; + iceDestroyed = true; // - // communicator__ != null means that it will be destroyed - // next; destroyed__ == true ensures that any + // iceCommunicator != null means that it will be destroyed + // next; iceDestroyed == true ensures that any // remaining callback won't do anything // } _application = null; } - if(communicator__ != null) + if(iceCommunicator != null) { try { - communicator__.destroy(); + iceCommunicator.destroy(); } catch(Ice.Exception ex) { @@ -533,7 +507,7 @@ namespace Ice Util.getProcessLogger().error("unknown exception:\n" + ex); status = 1; } - communicator__ = null; + iceCommunicator = null; } return status; @@ -546,7 +520,7 @@ namespace Ice { Callback callback; - lock(mutex__) + lock(iceMutex) { callback = _callback; } @@ -570,14 +544,14 @@ namespace Ice private static void holdInterruptCallback(int sig) { Callback callback = null; - lock(mutex__) + lock(iceMutex) { - while(!released__) + while(!iceReleased) { - System.Threading.Monitor.Wait(mutex__); + System.Threading.Monitor.Wait(iceMutex); } - if(destroyed__) + if(iceDestroyed) { // // Being destroyed by main thread @@ -599,86 +573,86 @@ namespace Ice // private static void destroyOnInterruptCallback(int sig) { - lock(mutex__) + lock(iceMutex) { - if(destroyed__) + if(iceDestroyed) { // // Being destroyed by main thread // return; } - if(nohup__ && sig == SIGHUP) + if(iceNohup && sig == SIGHUP) { return; } - Debug.Assert(!callbackInProgress__); - callbackInProgress__ = true; - interrupted__ = true; - destroyed__ = true; + Debug.Assert(!iceCallbackInProgress); + iceCallbackInProgress = true; + iceInterrupted = true; + iceDestroyed = true; } try { - Debug.Assert(communicator__ != null); - communicator__.destroy(); + Debug.Assert(iceCommunicator != null); + iceCommunicator.destroy(); } catch(System.Exception ex) { Util.getProcessLogger().error("(while destroying in response to signal " + sig + "):\n" + ex); } - lock(mutex__) + lock(iceMutex) { - callbackInProgress__ = false; - System.Threading.Monitor.Pulse(mutex__); + iceCallbackInProgress = false; + System.Threading.Monitor.Pulse(iceMutex); } } private static void shutdownOnInterruptCallback(int sig) { - lock(mutex__) + lock(iceMutex) { - if(destroyed__) + if(iceDestroyed) { // // Being destroyed by main thread // return; } - if(nohup__ && sig == SIGHUP) + if(iceNohup && sig == SIGHUP) { return; } - Debug.Assert(!callbackInProgress__); - callbackInProgress__ = true; - interrupted__ = true; + Debug.Assert(!iceCallbackInProgress); + iceCallbackInProgress = true; + iceInterrupted = true; } try { - Debug.Assert(communicator__ != null); - communicator__.shutdown(); + Debug.Assert(iceCommunicator != null); + iceCommunicator.shutdown(); } catch(System.Exception ex) { Util.getProcessLogger().error("(while shutting down in response to signal " + sig + "):\n" + ex); } - lock(mutex__) + lock(iceMutex) { - callbackInProgress__ = false; - System.Threading.Monitor.Pulse(mutex__); + iceCallbackInProgress = false; + System.Threading.Monitor.Pulse(iceMutex); } } private static void userCallbackOnInterruptCallback(int sig) { - lock(mutex__) + lock(iceMutex) { - if(destroyed__) + if(iceDestroyed) { // // Being destroyed by main thread @@ -687,9 +661,9 @@ namespace Ice } // For SIGHUP the user callback is always called. It can // decide what to do. - Debug.Assert(!callbackInProgress__); - callbackInProgress__ = true; - interrupted__ = true; + Debug.Assert(!iceCallbackInProgress); + iceCallbackInProgress = true; + iceInterrupted = true; } try @@ -702,20 +676,20 @@ namespace Ice Util.getProcessLogger().error("(while interrupting in response to signal " + sig + "):\n" + ex); } - lock(mutex__) + lock(iceMutex) { - callbackInProgress__ = false; - System.Threading.Monitor.Pulse(mutex__); + iceCallbackInProgress = false; + System.Threading.Monitor.Pulse(iceMutex); } } - protected static object mutex__ = new object(); - protected static bool callbackInProgress__ = false; - protected static bool destroyed__ = false; - protected static bool interrupted__ = false; - protected static bool released__ = false; - protected static bool nohup__ = false; - protected static SignalPolicy signalPolicy__ = SignalPolicy.HandleSignals; + protected static object iceMutex = new object(); + protected static bool iceCallbackInProgress = false; + protected static bool iceDestroyed = false; + protected static bool iceInterrupted = false; + protected static bool iceReleased = false; + protected static bool iceNohup = false; + protected static SignalPolicy iceSignalPolicy = SignalPolicy.HandleSignals; private delegate void Callback(int sig); private static readonly Callback _destroyCallback = new Callback(destroyOnInterruptCallback); @@ -730,26 +704,18 @@ namespace Ice // We use FriendlyName instead of Process.GetCurrentProcess().ProcessName because the latter // is terribly slow. (It takes around 1 second!) // - protected static string appName__ = AppDomain.CurrentDomain.FriendlyName; - protected static Communicator communicator__; + protected static string iceAppName = AppDomain.CurrentDomain.FriendlyName; + protected static Communicator iceCommunicator; private static Application _application; private static int SIGHUP; static Application() { - if(IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows) - { - SIGHUP = 5; // CTRL_LOGOFF_EVENT, from wincon.h - } - else - { - SIGHUP = 1; - } + SIGHUP = 5; // CTRL_LOGOFF_EVENT, from wincon.h } private delegate void SignalHandler(int sig); private static readonly SignalHandler _handler = new SignalHandler(signalHandler); -#if !COMPACT && !UNITY private Signals _signals; private interface Signals @@ -758,136 +724,6 @@ namespace Ice void destroy(); } - private class MonoSignals : Signals - { - public void register(SignalHandler handler) - { - _handler = handler; - _destroyed = false; - - try - { - // - // Signal handling in Mono is provided in the Mono.Unix.Native namespace. - // We use reflection to do the equivalent of the following: - // - // Stdlib.signal(Signum.SIGHUP, delegate); - // Stdlib.signal(Signum.SIGINT, delegate); - // Stdlib.signal(Signum.SIGTERM, delegate); - // - // We don't use conditional compilation so that the Ice assembly can be - // used without change on Windows and Mono. - // - Assembly a = Assembly.Load( - "Mono.Posix, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"); - Type sigs = a.GetType("Mono.Unix.Native.Signum"); - object SIGHUP = Enum.Parse(sigs, "SIGHUP"); - object SIGINT = Enum.Parse(sigs, "SIGINT"); - object SIGTERM = Enum.Parse(sigs, "SIGTERM"); - Type stdlib = a.GetType("Mono.Unix.Native.Stdlib"); - MethodInfo method = stdlib.GetMethod("signal", BindingFlags.Static | BindingFlags.Public); - Type delType = a.GetType("Mono.Unix.Native.SignalHandler"); - Delegate del = Delegate.CreateDelegate(delType, this, "callback"); - object[] args = new object[2]; - args[0] = SIGHUP; - args[1] = del; - method.Invoke(null, args); - args[0] = SIGINT; - args[1] = del; - method.Invoke(null, args); - args[0] = SIGTERM; - args[1] = del; - method.Invoke(null, args); - - // - // Doing certain activities within Mono's signal dispatch thread - // can cause the VM to crash, so we use a separate thread to invoke - // the handler. - // - _thread = new Thread(new ThreadStart(run)); - _thread.IsBackground = true; - _thread.Name = "Ice.Application.SignalThread"; - _thread.Start(); - } - catch(System.DllNotFoundException) - { - // - // The class Mono.Unix.Native.Stdlib requires libMonoPosixHelper.so. Mono raises - // DllNotFoundException if it cannot be found in the shared library search path. - // - Util.getProcessLogger().warning("unable to initialize signals"); - } - } - - public void destroy() - { - lock(_m) - { - _destroyed = true; - System.Threading.Monitor.Pulse(_m); - } - - if(_thread != null) - { - _thread.Join(); - _thread = null; - } - } - - private void callback(int sig) - { - lock(_m) - { - _signals.Add(sig); - System.Threading.Monitor.Pulse(_m); - } - } - - private void run() - { - while(true) - { - List<int> signals = null; - bool destroyed = false; - - lock(_m) - { - if(!_destroyed && _signals.Count == 0) - { - System.Threading.Monitor.Wait(_m); - } - - if(_signals.Count > 0) - { - signals = _signals; - _signals = new List<int>(); - } - - destroyed = _destroyed; - } - - if(signals != null) - { - foreach(int sig in signals) - { - _handler(sig); - } - } - - if(destroyed) - { - break; - } - } - } - - private static SignalHandler _handler; - private static bool _destroyed; - private static object _m = new object(); - private static Thread _thread; - private static List<int> _signals = new List<int>(); - } - private class WindowsSignals : Signals { #if MANAGED @@ -928,9 +764,7 @@ namespace Ice #endif private SignalHandler _handler; } -#endif } delegate bool CtrlCEventHandler(int sig); } -#endif diff --git a/csharp/src/Ice/Arrays.cs b/csharp/src/Ice/Arrays.cs index 7d920f71927..a18e2550798 100644 --- a/csharp/src/Ice/Arrays.cs +++ b/csharp/src/Ice/Arrays.cs @@ -12,7 +12,6 @@ using System.Collections; namespace IceUtilInternal { - public sealed class Arrays { public static bool Equals(object[] arr1, object[] arr2) diff --git a/csharp/src/Ice/AssemblyInfo.cs b/csharp/src/Ice/AssemblyInfo.cs index 2b8b2651530..9c5d9ad01f7 100644 --- a/csharp/src/Ice/AssemblyInfo.cs +++ b/csharp/src/Ice/AssemblyInfo.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/Ice/AssemblyUtil.cs b/csharp/src/Ice/AssemblyUtil.cs index e0b75768620..ee4cbca4211 100644 --- a/csharp/src/Ice/AssemblyUtil.cs +++ b/csharp/src/Ice/AssemblyUtil.cs @@ -9,107 +9,13 @@ namespace IceInternal { - using System; using System.Collections; using System.Collections.Generic; - using System.Diagnostics; using System.Reflection; - using System.Threading; public sealed class AssemblyUtil { - public enum Runtime { DotNET, Mono }; - public enum Platform { Windows, NonWindows }; - - static AssemblyUtil() - { - PlatformID id = Environment.OSVersion.Platform; - if( id == PlatformID.Win32NT - || id == PlatformID.Win32S - || id == PlatformID.Win32Windows - || id == PlatformID.WinCE) - { - platform_ = Platform.Windows; - } - else - { - platform_ = Platform.NonWindows; - } - - if(System.Type.GetType("Mono.Runtime") != null) - { - runtime_ = Runtime.Mono; - } - else - { - runtime_ = Runtime.DotNET; - } - - System.Version v = System.Environment.Version; - runtimeMajor_ = v.Major; - runtimeMinor_ = v.Minor; - runtimeBuild_ = v.Build; - runtimeRevision_ = v.Revision; - - v = System.Environment.OSVersion.Version; - xp_ = v.Major == 5 && v.Minor == 1; // Are we running on XP? - - osx_ = false; -#if COMPACT || SILVERLIGHT - // - // Populate the _iceAssemblies list with the fully-qualified names - // of the standard Ice assemblies. The fully-qualified name looks - // like this: - // - // Ice, Version=X.Y.Z.0, Culture=neutral, PublicKeyToken=... - // - string name = Assembly.GetExecutingAssembly().FullName; - _iceAssemblies.Add(name); - int pos = name.IndexOf(','); - if(pos >= 0 && pos < name.Length - 1) - { - // - // Strip off the leading assembly name and use the remainder of the - // string to compose the names of the other standard assemblies. - // - string suffix = name.Substring(pos + 1); - _iceAssemblies.Add("Glacier2," + suffix); - _iceAssemblies.Add("IceBox," + suffix); - _iceAssemblies.Add("IceGrid," + suffix); - _iceAssemblies.Add("IcePatch2," + suffix); - _iceAssemblies.Add("IceStorm," + suffix); - } -#elif !UNITY - if (platform_ == Platform.NonWindows) - { - try - { - Assembly a = Assembly.Load( - "Mono.Posix, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"); - Type syscall = a.GetType("Mono.Unix.Native.Syscall"); - if(syscall != null) - { - MethodInfo method = syscall.GetMethod("uname", BindingFlags.Static | BindingFlags.Public); - if(method != null) - { - object[] p = new object[1]; - method.Invoke(null, p); - if(p[0] != null) - { - Type utsname = a.GetType("Mono.Unix.Native.Utsname"); - osx_ = ((string)utsname.GetField("sysname").GetValue(p[0])).Equals("Darwin"); - } - } - } - } - catch(System.Exception) - { - } - } -#endif - } - public static Type findType(Instance instance, string csharpId) { lock(_mutex) @@ -119,33 +25,7 @@ namespace IceInternal { return t; } -#if COMPACT || SILVERLIGHT - string[] assemblies = instance.factoryAssemblies(); - for(int i = 0; i < assemblies.Length; ++i) - { - string s = csharpId + "," + assemblies[i]; - if((t = Type.GetType(s)) != null) - { - _typeTable[csharpId] = t; - return t; - } - } - // - // As a last resort, look for the type in the standard Ice assemblies. - // This avoids the need for a program to set a property such as: - // - // Ice.FactoryAssemblies=Ice - // - foreach(string a in _iceAssemblies) - { - string s = csharpId + "," + a; - if((t = Type.GetType(s)) != null) - { - _typeTable[csharpId] = t; - return t; - } - } -#else + loadAssemblies(); // Lazy initialization foreach (Assembly a in _loadedAssemblies.Values) { @@ -155,12 +35,10 @@ namespace IceInternal return t; } } -#endif } return null; } -#if !COMPACT && !SILVERLIGHT public static Type[] findTypesWithPrefix(string prefix) { LinkedList<Type> l = new LinkedList<Type>(); @@ -195,7 +73,6 @@ namespace IceInternal } return result; } -#endif public static object createInstance(Type t) { @@ -209,7 +86,6 @@ namespace IceInternal } } -#if !COMPACT && !SILVERLIGHT // // Make sure that all assemblies that are referenced by this process // are actually loaded. This is necessary so we can use reflection @@ -262,7 +138,7 @@ namespace IceInternal _loadedAssemblies[ra.FullName] = ra; loadReferencedAssemblies(ra); } - catch(System.Exception) + catch(Exception) { // Ignore assemblies that cannot be loaded. } @@ -271,25 +147,7 @@ namespace IceInternal } private static Hashtable _loadedAssemblies = new Hashtable(); // <string, Assembly> pairs. -#else - private static List<string> _iceAssemblies = new List<string>(); -#endif private static Dictionary<string, Type> _typeTable = new Dictionary<string, Type>(); // <type name, Type> pairs. private static object _mutex = new object(); - - public readonly static Runtime runtime_; // Either DotNET or Mono - // - // Versioning is: Major.Minor.Build.Revision. (Yes, really. It is not Major.Minor.Revision.Build, as - // one might expect.) If a part of a version number (such as revision) is not defined, it is -1. - // - public readonly static int runtimeMajor_; - public readonly static int runtimeMinor_; - public readonly static int runtimeBuild_; - public readonly static int runtimeRevision_; - - public readonly static Platform platform_; - public readonly static bool xp_; - public readonly static bool osx_; } - } diff --git a/csharp/src/Ice/AsyncIOThread.cs b/csharp/src/Ice/AsyncIOThread.cs index 5333b454384..c9d714a4074 100644 --- a/csharp/src/Ice/AsyncIOThread.cs +++ b/csharp/src/Ice/AsyncIOThread.cs @@ -9,10 +9,8 @@ namespace IceInternal { - using System; using System.Collections.Generic; using System.Diagnostics; - using System.Net; using System.Threading; public class AsyncIOThread @@ -23,20 +21,8 @@ namespace IceInternal _thread = new HelperThread(this); updateObserver(); -#if !SILVERLIGHT - if(instance.initializationData().properties.getProperty("Ice.ThreadPriority").Length > 0) - { - ThreadPriority priority = IceInternal.Util.stringToThreadPriority( - instance.initializationData().properties.getProperty("Ice.ThreadPriority")); - _thread.Start(priority); - } - else - { - _thread.Start(ThreadPriority.Normal); - } -#else - _thread.Start(); -#endif + _thread.Start(Util.stringToThreadPriority( + instance.initializationData().properties.getProperty("Ice.ThreadPriority"))); } public void @@ -65,7 +51,7 @@ namespace IceInternal { Debug.Assert(!_destroyed); _queue.AddLast(callback); - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } } @@ -75,7 +61,7 @@ namespace IceInternal { Debug.Assert(!_destroyed); _destroyed = true; - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } } @@ -109,7 +95,7 @@ namespace IceInternal while(!_destroyed && _queue.Count == 0) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } LinkedList<ThreadPoolWorkItem> tmp = queue; @@ -146,7 +132,7 @@ namespace IceInternal if(_observer != null) { - _observer.detach(); + _observer.detach(); } } @@ -178,18 +164,11 @@ namespace IceInternal return _name; } -#if !SILVERLIGHT public void Start(ThreadPriority priority) -#else - public void Start() -#endif { _thread = new Thread(new ThreadStart(Run)); _thread.IsBackground = true; _thread.Name = _name; -#if !SILVERLIGHT - _thread.Priority = priority; -#endif _thread.Start(); } diff --git a/csharp/src/Ice/AsyncResult.cs b/csharp/src/Ice/AsyncResult.cs index fc6be85c5a4..6e4d4adddfb 100644 --- a/csharp/src/Ice/AsyncResult.cs +++ b/csharp/src/Ice/AsyncResult.cs @@ -26,8 +26,8 @@ namespace Ice /// /// <summary> - /// Callback for the successful completion of an operation - /// that returns no data. + /// Callback to inform when a call has been passed to the local + /// transport. /// </summary> /// public delegate void SentCallback(bool sentSynchronously); @@ -47,13 +47,14 @@ namespace Ice { void cancel(); - Ice.Communicator getCommunicator(); + Communicator getCommunicator(); - Ice.Connection getConnection(); + Connection getConnection(); ObjectPrx getProxy(); bool isCompleted_(); + void waitForCompleted(); bool isSent(); @@ -65,35 +66,31 @@ namespace Ice string getOperation(); - AsyncResult whenSent(Ice.AsyncCallback cb); - AsyncResult whenSent(Ice.SentCallback cb); - - AsyncResult whenCompleted(Ice.ExceptionCallback excb); + AsyncResult whenSent(AsyncCallback cb); + AsyncResult whenSent(SentCallback cb); + AsyncResult whenCompleted(ExceptionCallback excb); } public interface AsyncResult<T> : AsyncResult { - AsyncResult<T> whenCompleted(T cb, Ice.ExceptionCallback excb); + AsyncResult<T> whenCompleted(T cb, ExceptionCallback excb); - new AsyncResult<T> whenCompleted(Ice.ExceptionCallback excb); - new AsyncResult<T> whenSent(Ice.SentCallback cb); + new AsyncResult<T> whenCompleted(ExceptionCallback excb); + new AsyncResult<T> whenSent(SentCallback cb); } } namespace IceInternal { - using System.Collections.Generic; using System.Diagnostics; using System.Threading; - public delegate void ProxyTwowayCallback<T>(Ice.AsyncResult result, T cb, Ice.ExceptionCallback excb); - public delegate void ProxyOnewayCallback<T>(T cb); - - public class AsyncResultI : Ice.AsyncResult + abstract public class AsyncResultI : Ice.AsyncResult { public virtual void cancel() { - cancel(new Ice.InvocationCanceledException()); + Debug.Assert(outgoing_ != null); + outgoing_.cancel(); } public Ice.Communicator getCommunicator() @@ -125,7 +122,7 @@ namespace IceInternal { while((state_ & StateDone) == 0) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } } } @@ -142,9 +139,9 @@ namespace IceInternal { lock(this) { - while((state_ & StateSent) == 0 && _exception == null) + while((state_ & StateSent) == 0 && exception_ == null) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } } } @@ -153,22 +150,22 @@ namespace IceInternal { lock(this) { - if(_exception != null) + if(exception_ != null) { - throw _exception; + throw exception_; } } } public bool sentSynchronously() { - return sentSynchronously_; // No lock needed + Debug.Assert(outgoing_ != null); + return outgoing_.sentSynchronously(); // No lock needed } // // Implementation of System.IAsyncResult properties // - public bool IsCompleted { get @@ -181,11 +178,12 @@ namespace IceInternal { get { + Debug.Assert(outgoing_ != null); if(getProxy() != null && getProxy().ice_isTwoway()) { return false; } - return sentSynchronously_; + return outgoing_.sentSynchronously(); } } @@ -203,23 +201,27 @@ namespace IceInternal { lock(this) { - if(_waitHandle == null) + if(waitHandle_ == null) { -#if SILVERLIGHT - _waitHandle = new ManualResetEvent(false); -#else - _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset); -#endif + waitHandle_ = new EventWaitHandle(false, EventResetMode.ManualReset); } if((state_ & StateDone) != 0) { - _waitHandle.Set(); + waitHandle_.Set(); } - return _waitHandle; + return waitHandle_; } } } + public OutgoingAsyncBase OutgoingAsync + { + get + { + return outgoing_; + } + } + public Ice.AsyncResult whenSent(Ice.AsyncCallback cb) { lock(this) @@ -228,22 +230,22 @@ namespace IceInternal { throw new System.ArgumentException("callback is null"); } - if(_sentCallback != null) + if(sentCallback_ != null) { throw new System.ArgumentException("sent callback already set"); } - _sentCallback = cb; + sentCallback_ = cb; if((state_ & StateSent) == 0) { return this; } } - if(sentSynchronously_) + if(outgoing_.sentSynchronously()) { try { - _sentCallback(this); + sentCallback_(this); } catch(System.Exception ex) { @@ -256,7 +258,7 @@ namespace IceInternal { try { - _sentCallback(this); + sentCallback_(this); } catch(System.Exception ex) { @@ -275,21 +277,21 @@ namespace IceInternal { throw new System.ArgumentException("callback is null"); } - if(_sentCallback != null) + if(sentCallback_ != null) { throw new System.ArgumentException("sent callback already set"); } - _sentCallback = (Ice.AsyncResult result) => - { - cb(result.sentSynchronously()); - }; + sentCallback_ = (Ice.AsyncResult r) => + { + cb(r.sentSynchronously()); + }; if((state_ & StateSent) == 0) { return this; } } - if(sentSynchronously_) + if(outgoing_.sentSynchronously()) { try { @@ -317,12 +319,6 @@ namespace IceInternal return this; } - public Ice.AsyncResult whenCompletedWithAsyncCallback(Ice.AsyncCallback cb) - { - setCompletedCallback(cb); - return this; - } - public Ice.AsyncResult whenCompleted(Ice.ExceptionCallback cb) { if(cb == null) @@ -346,103 +342,6 @@ namespace IceInternal return _operation; } - public void invokeSent(Ice.AsyncCallback cb) - { - Debug.Assert(cb != null); - try - { - cb(this); - } - catch(System.Exception ex) - { - warning(ex); - } - - if(observer_ != null) - { - Ice.ObjectPrx proxy = getProxy(); - if(proxy == null || !proxy.ice_isTwoway()) - { - observer_.detach(); - observer_ = null; - } - } - } - - public void invokeSentAsync(Ice.AsyncCallback cb) - { - // - // This is called when it's not safe to call the exception callback synchronously - // from this thread. Instead the exception callback is called asynchronously from - // the client thread pool. - // - Debug.Assert(cb != null); - try - { - instance_.clientThreadPool().dispatch(() => - { - invokeSent(cb); - }, cachedConnection_); - } - catch(Ice.CommunicatorDestroyedException) - { - } - } - - public void invokeCompleted(Ice.AsyncCallback cb) - { - Debug.Assert(cb != null); - try - { - cb(this); - } - catch(System.Exception ex) - { - warning(ex); - } - - if(observer_ != null) - { - observer_.detach(); - observer_ = null; - } - } - - public void invokeCompletedAsync(Ice.AsyncCallback cb) - { - // - // This is called when it's not safe to call the exception callback synchronously - // from this thread. Instead the exception callback is called asynchronously from - // the client thread pool. - // - Debug.Assert(cb != null); - - // CommunicatorDestroyedException is the only exception that can propagate directly. - instance_.clientThreadPool().dispatch(() => - { - invokeCompleted(cb); - }, cachedConnection_); - } - - public virtual void cancelable(CancellationHandler handler) - { - lock(this) - { - if(_cancellationException != null) - { - try - { - throw _cancellationException; - } - finally - { - _cancellationException = null; - } - } - _cancellationHandler = handler; - } - } - public bool wait() { lock(this) @@ -454,121 +353,30 @@ namespace IceInternal state_ |= StateEndCalled; while((state_ & StateDone) == 0) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } - if(_exception != null) + if(exception_ != null) { - throw _exception; + throw exception_; } return (state_ & StateOK) != 0; } } - public virtual void cacheMessageBuffers() - { - } - - protected AsyncResultI(Ice.Communicator communicator, Instance instance, string op, object cookie) + protected AsyncResultI(Ice.Communicator communicator, + Instance instance, + string op, + object cookie, + Ice.AsyncCallback cb) { instance_ = instance; - sentSynchronously_ = false; state_ = 0; _communicator = communicator; _operation = op; - _exception = null; + exception_ = null; _cookie = cookie; - } - - protected Ice.AsyncCallback sent(bool done) - { - lock(this) - { - Debug.Assert(_exception == null); - - bool alreadySent = (state_ & StateSent) != 0; - state_ |= StateSent; - if(done) - { - state_ |= StateDone | StateOK; - _cancellationHandler = null; - if(observer_ != null && _sentCallback == null) - { - observer_.detach(); - observer_ = null; - } - - // - // For oneway requests after the data has been sent - // the buffers can be reused unless this is a - // collocated invocation. For collocated invocations - // the buffer won't be reused because it has already - // been marked as cached in invokeCollocated. - // - cacheMessageBuffers(); - } - if(_waitHandle != null) - { - _waitHandle.Set(); - } - System.Threading.Monitor.PulseAll(this); - return !alreadySent ? _sentCallback : null; - } - } - - protected Ice.AsyncCallback finished(bool ok) - { - lock(this) - { - state_ |= StateDone; - if(ok) - { - state_ |= StateOK; - } - _cancellationHandler = null; - if(_completedCallback == null) - { - if(observer_ != null) - { - observer_.detach(); - observer_ = null; - } - } - if(_waitHandle != null) - { - _waitHandle.Set(); - } - System.Threading.Monitor.PulseAll(this); - return _completedCallback; - } - } - - protected Ice.AsyncCallback finished(Ice.Exception ex) - { - lock(this) - { - state_ |= StateDone; - _exception = ex; - _cancellationHandler = null; - if(observer_ != null) - { - observer_.failed(ex.ice_name()); - } - if(_completedCallback == null) - { - if(observer_ != null) - { - observer_.detach(); - observer_ = null; - } - } - if(_waitHandle != null) - { - _waitHandle.Set(); - } - System.Threading.Monitor.PulseAll(this); - return _completedCallback; - } + completedCallback_ = cb; } protected void setCompletedCallback(Ice.AsyncCallback cb) @@ -579,16 +387,16 @@ namespace IceInternal { throw new System.ArgumentException("callback is null"); } - if(_completedCallback != null) + if(completedCallback_ != null) { throw new System.ArgumentException("callback already set"); } - _completedCallback = cb; + completedCallback_ = cb; if((state_ & StateDone) == 0) { return; } - else if((getProxy() == null || !getProxy().ice_isTwoway()) && _exception == null) + else if((getProxy() == null || !getProxy().ice_isTwoway()) && exception_ == null) { return; } @@ -598,7 +406,14 @@ namespace IceInternal { try { - cb(this); + try + { + cb(this); + } + catch(System.AggregateException ex) + { + throw ex.InnerException; + } } catch(System.Exception ex) { @@ -607,44 +422,21 @@ namespace IceInternal }, cachedConnection_); } - protected virtual Ice.AsyncCallback getCompletedCallback() - { - return (Ice.AsyncResult result) => - { - Debug.Assert(exceptionCallback_ != null); - try - { - ((AsyncResultI)result).wait(); - } - catch(Ice.Exception ex) - { - exceptionCallback_(ex); - return; - } - }; - } + abstract protected Ice.AsyncCallback getCompletedCallback(); - protected void cancel(Ice.LocalException ex) + public static AsyncResultI check(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation) { - CancellationHandler handler; - lock(this) + if(r != null && r.getProxy() != prx) { - _cancellationException = ex; - if(_cancellationHandler == null) - { - return; - } - handler = _cancellationHandler; + throw new System.ArgumentException("Proxy for call to end_" + operation + + " does not match proxy that was used to call corresponding begin_" + + operation + " method"); } - handler.asyncRequestCanceled((OutgoingAsyncBase)this, ex); + return check(r, operation); } - protected virtual Ice.Instrumentation.InvocationObserver getObserver() - { - return observer_; - } - protected static T check<T>(Ice.AsyncResult r, string operation) + public static AsyncResultI check(Ice.AsyncResult r, string operation) { if(r == null) { @@ -655,11 +447,11 @@ namespace IceInternal throw new System.ArgumentException("Incorrect operation for end_" + operation + " method: " + r.getOperation()); } - if(!(r is T)) + if(!(r is AsyncResultI)) { throw new System.ArgumentException("Incorrect AsyncResult object for end_" + operation + " method"); } - return (T)r; + return (AsyncResultI)r; } protected void warning(System.Exception ex) @@ -670,29 +462,25 @@ namespace IceInternal } } - protected IceInternal.Instance instance_; + protected Instance instance_; protected Ice.Instrumentation.InvocationObserver observer_; protected Ice.Connection cachedConnection_; - protected bool sentSynchronously_; private readonly Ice.Communicator _communicator; private readonly string _operation; private readonly object _cookie; - private Ice.Exception _exception; - private EventWaitHandle _waitHandle; - - private CancellationHandler _cancellationHandler; - private Ice.LocalException _cancellationException; + protected Ice.Exception exception_; + protected EventWaitHandle waitHandle_; - private Ice.AsyncCallback _completedCallback; - private Ice.AsyncCallback _sentCallback; + protected Ice.AsyncCallback completedCallback_; + protected Ice.AsyncCallback sentCallback_; protected Ice.ExceptionCallback exceptionCallback_; protected const int StateOK = 0x1; protected const int StateDone = 0x2; protected const int StateSent = 0x4; protected const int StateEndCalled = 0x8; - protected const int StateCachedBuffers = 0x10; protected int state_; + protected OutgoingAsyncBase outgoing_; } } diff --git a/csharp/src/Ice/BZip2.cs b/csharp/src/Ice/BZip2.cs new file mode 100644 index 00000000000..c2943208cef --- /dev/null +++ b/csharp/src/Ice/BZip2.cs @@ -0,0 +1,281 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +namespace IceInternal +{ + + using System; + using System.Diagnostics; + using System.Runtime.InteropServices; + +#if !MANAGED + internal static class NativeMethods + { + [DllImport("bzip2.dll")] + internal static extern IntPtr BZ2_bzlibVersion(); + + [DllImport("bzip2.dll")] + internal static extern int BZ2_bzBuffToBuffCompress(byte[] dest, + ref int destLen, + byte[] source, + int sourceLen, + int blockSize100k, + int verbosity, + int workFactor); + + [DllImport("bzip2.dll")] + internal static extern int BZ2_bzBuffToBuffDecompress(byte[] dest, + ref int destLen, + byte[] source, + int sourceLen, + int small, + int verbosity); + } +#endif + + public class BZip2 + { + static BZip2() + { +#if MANAGED + // + // Protocol compression is not supported when using managed code. + // + _bzlibInstalled = false; +#else + // + // Simple trick to find out whether bzip2 is installed: Call the BZ2_bzlibVersion() function in the + // library. If we get an exception, the library is not available. + // + _bzlibInstalled = false; + + // + // We are setting the library name here because, under Mono, we don't know the exact library name. + // In addition, the FileName member of the BadImageFormatException is the empty string, even though + // it should provide the name of the library. + // + try + { + NativeMethods.BZ2_bzlibVersion(); + _bzlibInstalled = true; + } + catch(DllNotFoundException) + { + // Expected -- bzip2.dll not installed or not in PATH. + } + catch(EntryPointNotFoundException) + { + Console.Error.WriteLine("warning: found bzip2.dll but entry point BZ2_bzlibVersion is missing."); + } + catch(BadImageFormatException ex) + { + string lib = "bzip2.dll"; + if(!String.IsNullOrEmpty(ex.FileName)) + { + lib = ex.FileName; // Future-proof: we'll do the right thing if the FileName member is non-empty. + } + Console.Error.Write("warning: " + lib + " could not be loaded (likely due to 32/64-bit mismatch)."); + if(IntPtr.Size == 8) + { + Console.Error.Write(" Make sure the directory containing the 64-bit " + lib + " is in your PATH."); + } + Console.Error.WriteLine(); + } +#endif + } + +#if !MANAGED + static string getBZ2Error(int error) + { + string rc; + + switch(error) + { + case BZ_SEQUENCE_ERROR: + { + rc = "BZ_SEQUENCE_ERROR"; + break; + } + case BZ_PARAM_ERROR: + { + rc = "BZ_PARAM_ERROR"; + break; + } + case BZ_MEM_ERROR: + { + rc = "BZ_MEM_ERROR"; + break; + } + case BZ_DATA_ERROR: + { + rc = "BZ_DATA_ERROR"; + break; + } + case BZ_DATA_ERROR_MAGIC: + { + rc = "BZ_DATA_ERROR_MAGIC"; + break; + } + case BZ_IO_ERROR: + { + rc = "BZ_IO_ERROR"; + break; + } + case BZ_UNEXPECTED_EOF: + { + rc = "BZ_UNEXPECTED_EOF"; + break; + } + case BZ_OUTBUFF_FULL: + { + rc = "BZ_OUTBUFF_FULL"; + break; + } + case BZ_CONFIG_ERROR: + { + rc = "BZ_CONFIG_ERROR"; + break; + } + default: + { + rc = "Unknown bzip2 error: " + error; + break; + } + } + return rc; + } +#endif + + public static bool supported() + { + return _bzlibInstalled; + } + + public static Buffer compress(Buffer buf, int headerSize, int compressionLevel) + { + Debug.Assert(supported()); + +#if MANAGED + return null; +#else + // + // Compress the message body, but not the header. + // + int uncompressedLen = buf.size() - headerSize; + byte[] data = buf.b.rawBytes(headerSize, uncompressedLen); + int compressedLen = (int)(uncompressedLen * 1.01 + 600); + byte[] compressed = new byte[compressedLen]; + + int rc = NativeMethods.BZ2_bzBuffToBuffCompress(compressed, ref compressedLen, data, uncompressedLen, + compressionLevel, 0, 0); + if(rc == BZ_OUTBUFF_FULL) + { + return null; + } + else if(rc < 0) + { + Ice.CompressionException ex = new Ice.CompressionException("BZ2_bzBuffToBuffCompress failed"); + ex.reason = getBZ2Error(rc); + throw ex; + } + + // + // Don't bother if the compressed data is larger than the + // uncompressed data. + // + if(compressedLen >= uncompressedLen) + { + return null; + } + + Buffer r = new Buffer(); + r.resize(headerSize + 4 + compressedLen, false); + r.b.position(0); + + // + // Copy the header from the uncompressed stream to the + // compressed one. + // + r.b.put(buf.b.rawBytes(0, headerSize)); + + // + // Add the size of the uncompressed stream before the + // message body. + // + r.b.putInt(buf.size()); + + // + // Add the compressed message body. + // + r.b.put(compressed, 0, compressedLen); + + return r; +#endif + } + + public static Buffer uncompress(Buffer buf, int headerSize, int messageSizeMax) + { + Debug.Assert(supported()); + +#if MANAGED + return null; +#else + buf.b.position(headerSize); + int uncompressedSize = buf.b.getInt(); + if(uncompressedSize <= headerSize) + { + throw new Ice.IllegalMessageSizeException("compressed size <= header size"); + } + if(uncompressedSize > messageSizeMax) + { + IceInternal.Ex.throwMemoryLimitException(uncompressedSize, messageSizeMax); + } + + int compressedLen = buf.size() - headerSize - 4; + byte[] compressed = buf.b.rawBytes(headerSize + 4, compressedLen); + int uncompressedLen = uncompressedSize - headerSize; + + byte[] uncompressed = new byte[uncompressedLen]; + int rc = NativeMethods.BZ2_bzBuffToBuffDecompress(uncompressed, ref uncompressedLen, compressed, + compressedLen, 0, 0); + if(rc < 0) + { + Ice.CompressionException ex = new Ice.CompressionException("BZ2_bzBuffToBuffDecompress failed"); + ex.reason = getBZ2Error(rc); + throw ex; + } + + Buffer r = new Buffer(); + r.resize(uncompressedSize, false); + + // + // Copy the header from the compressed buffer to the uncompressed one. + // + r.b.position(0); + r.b.put(buf.b.rawBytes(), 0, headerSize); + r.b.put(uncompressed); + + return r; +#endif + } + + private static bool _bzlibInstalled; + + const int BZ_SEQUENCE_ERROR = -1; + const int BZ_PARAM_ERROR = -2; + const int BZ_MEM_ERROR = -3; + const int BZ_DATA_ERROR = -4; + const int BZ_DATA_ERROR_MAGIC = -5; + const int BZ_IO_ERROR = -6; + const int BZ_UNEXPECTED_EOF = -7; + const int BZ_OUTBUFF_FULL = -8; + const int BZ_CONFIG_ERROR = -9; + } + +} diff --git a/csharp/src/Ice/Base64.cs b/csharp/src/Ice/Base64.cs deleted file mode 100644 index 5f536757a48..00000000000 --- a/csharp/src/Ice/Base64.cs +++ /dev/null @@ -1,276 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -namespace IceUtilInternal -{ - -public class Base64 -{ - -public static string -encode(byte[] plainSeq) -{ - if(plainSeq == null || plainSeq.Length == 0) - { - return ""; - } - - System.Text.StringBuilder retval = new System.Text.StringBuilder(); - int base64Bytes = (((plainSeq.Length * 4) / 3) + 1); - int newlineBytes = (((base64Bytes * 2) / 76) + 1); - int totalBytes = base64Bytes + newlineBytes; - - retval.Capacity = totalBytes; - - byte by1; - byte by2; - byte by3; - byte by4; - byte by5; - byte by6; - byte by7; - - for(int i = 0; i < plainSeq.Length; i += 3) - { - by1 = plainSeq[i]; - by2 = 0; - by3 = 0; - - if((i + 1) < plainSeq.Length) - { - by2 = plainSeq[i+1]; - } - - if((i + 2) < plainSeq.Length) - { - by3 = plainSeq[i+2]; - } - - by4 = (byte)(by1 >> 2); - by5 = (byte)(((by1 & 0x3) << 4) | (by2 >> 4)); - by6 = (byte)(((by2 & 0xf) << 2) | (by3 >> 6)); - by7 = (byte)(by3 & 0x3f); - - retval.Append(encode(by4)); - retval.Append(encode(by5)); - - if((i + 1) < plainSeq.Length) - { - retval.Append(encode(by6)); - } - else - { - retval.Append('='); - } - - if((i + 2) < plainSeq.Length) - { - retval.Append(encode(by7)); - } - else - { - retval.Append('='); - } - } - - System.Text.StringBuilder outString = new System.Text.StringBuilder(); - outString.Capacity = totalBytes; - int iter = 0; - - while((retval.Length - iter) > 76) - { - outString.Append(retval.ToString().Substring(iter, 76)); - outString.Append("\r\n"); - iter += 76; - } - - outString.Append(retval.ToString().Substring(iter)); - - return outString.ToString(); -} - -public static byte[] -decode(string str) -{ - System.Text.StringBuilder newStr = new System.Text.StringBuilder(); - - newStr.Capacity = str.Length; - - for(int j = 0; j < str.Length; j++) - { - char c = str[j]; - if(isBase64(c)) - { - newStr.Append(c); - } - } - - if(newStr.Length == 0) - { - return null; - } - - // Note: This is how we were previously computing the size of the return - // sequence. The method below is more efficient (and correct). - // size_t lines = str.size() / 78; - // size_t totalBytes = (lines * 76) + (((str.size() - (lines * 78)) * 3) / 4); - - // Figure out how long the final sequence is going to be. - int totalBytes = (newStr.Length * 3 / 4) + 1; - - IceInternal.ByteBuffer retval = IceInternal.ByteBuffer.allocate(totalBytes); - - byte by1; - byte by2; - byte by3; - byte by4; - - char c1, c2, c3, c4; - - int pos = 0; - for(int i = 0; i < newStr.Length; i += 4) - { - c1 = 'A'; - c2 = 'A'; - c3 = 'A'; - c4 = 'A'; - - c1 = newStr[i]; - - if((i + 1) < newStr.Length) - { - c2 = newStr[i + 1]; - } - - if((i + 2) < newStr.Length) - { - c3 = newStr[i + 2]; - } - - if((i + 3) < newStr.Length) - { - c4 = newStr[i + 3]; - } - - by1 = decode(c1); - by2 = decode(c2); - by3 = decode(c3); - by4 = decode(c4); - - retval.put((byte)((by1 << 2) | (by2 >> 4))); - ++pos; - - if(c3 != '=') - { - retval.put((byte)(((by2 & 0xf) << 4) | (by3 >> 2))); - ++pos; - } - - if(c4 != '=') - { - retval.put((byte)(((by3 & 0x3) << 6) | by4)); - ++pos; - } - } - - return retval.toArray(0, pos); -} - -public static bool -isBase64(char c) -{ - if(c >= 'A' && c <= 'Z') - { - return true; - } - - if(c >= 'a' && c <= 'z') - { - return true; - } - - if(c >= '0' && c <= '9') - { - return true; - } - - if(c == '+') - { - return true; - } - - if(c == '/') - { - return true; - } - - if(c == '=') - { - return true; - } - - return false; -} - -private static char -encode(byte uc) -{ - if(uc < 26) - { - return (char)('A' + uc); - } - - if(uc < 52) - { - return (char)('a' + (uc - 26)); - } - - if(uc < 62) - { - return (char)('0' + (uc - 52)); - } - - if(uc == 62) - { - return '+'; - } - - return '/'; -} - -private static byte -decode(char c) -{ - if(c >= 'A' && c <= 'Z') - { - return (byte)(c - 'A'); - } - - if(c >= 'a' && c <= 'z') - { - return (byte)(c - 'a' + 26); - } - - if(c >= '0' && c <= '9') - { - return (byte)(c - '0' + 52); - } - - if(c == '+') - { - return 62; - } - - return 63; -} - -} - -} - diff --git a/csharp/src/Ice/BasicStream.cs b/csharp/src/Ice/BasicStream.cs deleted file mode 100644 index 9769b69d4c2..00000000000 --- a/csharp/src/Ice/BasicStream.cs +++ /dev/null @@ -1,5426 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -namespace IceInternal -{ - - using System; - using System.Collections; - using System.Collections.Generic; - using System.Diagnostics; - using System.Reflection; -#if !COMPACT && !SILVERLIGHT - using System.Runtime.InteropServices; - using System.Runtime.Serialization; - using System.Runtime.Serialization.Formatters.Binary; -#endif - using System.Threading; - -#if !MANAGED && !COMPACT && !SILVERLIGHT - internal static class NativeMethods - { - [DllImport("bzip2.dll")] - internal static extern IntPtr BZ2_bzlibVersion(); - - [DllImport("bzip2.dll")] - internal static extern int BZ2_bzBuffToBuffCompress(byte[] dest, - ref int destLen, - byte[] source, - int sourceLen, - int blockSize100k, - int verbosity, - int workFactor); - - [DllImport("bzip2.dll")] - internal static extern int BZ2_bzBuffToBuffDecompress(byte[] dest, - ref int destLen, - byte[] source, - int sourceLen, - int small, - int verbosity); - } -#endif - - public class BasicStream - { - - static BasicStream() - { -#if MANAGED || COMPACT || SILVERLIGHT - // - // Protocol compression is not supported when using managed code. - // - _bzlibInstalled = false; -#else - // - // Simple trick to find out whether bzip2 is - // installed: Call the BZ2_bzlibVersion() function in the - // library. If we get an exception, the library is - // not available. - // - _bzlibInstalled = false; - - // - // We are setting the library name here because, under Mono, we don't know the exact library name. - // In addition, the FileName member of the BadImageFormatException is the empty string, even though - // it should provide the name of the library. - // - string lib = AssemblyUtil.runtime_ == AssemblyUtil.Runtime.Mono ? "bzip2 library" : "bzip2.dll"; - try - { - NativeMethods.BZ2_bzlibVersion(); - _bzlibInstalled = true; - } - catch(DllNotFoundException) - { - // Expected -- bzip2.dll not installed or not in PATH. - } - catch(EntryPointNotFoundException) - { - Console.Error.WriteLine("warning: found " + lib + " but entry point BZ2_bzlibVersion is missing."); - } - catch(BadImageFormatException ex) - { - if(ex.FileName != null && ex.FileName.Length != 0) - { - lib = ex.FileName; // Future-proof: we'll do the right thing if the FileName member is non-empty. - } - Console.Error.Write("warning: " + lib + " could not be loaded (likely due to 32/64-bit mismatch)."); - if(IntPtr.Size == 8) - { - Console.Error.Write(" Make sure the directory containing the 64-bit " + lib + " is in your PATH."); - } - Console.Error.WriteLine(); - } -#endif - } - - public BasicStream(Instance instance, Ice.EncodingVersion encoding) - { - initialize(instance, encoding); - _buf = new Buffer(); - } - - public BasicStream(Instance instance, Ice.EncodingVersion encoding, byte[] data) - { - initialize(instance, encoding); - _buf = new Buffer(data); - } - - private void initialize(Instance instance, Ice.EncodingVersion encoding) - { - instance_ = instance; - _closure = null; - _encoding = encoding; - - _readEncapsStack = null; - _writeEncapsStack = null; - _readEncapsCache = null; - _writeEncapsCache = null; - - _sliceObjects = true; - - _startSeq = -1; - } - - // - // This function allows this object to be reused, rather than - // reallocated. - // - public void reset() - { - _buf.reset(); - clear(); - } - - public void clear() - { - if(_readEncapsStack != null) - { - Debug.Assert(_readEncapsStack.next == null); - _readEncapsStack.next = _readEncapsCache; - _readEncapsCache = _readEncapsStack; - _readEncapsStack = null; - _readEncapsCache.reset(); - } - - if(_writeEncapsStack != null) - { - Debug.Assert(_writeEncapsStack.next == null); - _writeEncapsStack.next = _writeEncapsCache; - _writeEncapsCache = _writeEncapsStack; - _writeEncapsStack = null; - _writeEncapsCache.reset(); - } - - _startSeq = -1; - - _sliceObjects = true; - } - - public Instance instance() - { - return instance_; - } - - public object closure() - { - return _closure; - } - - public object closure(object p) - { - object prev = _closure; - _closure = p; - return prev; - } - - public void swap(BasicStream other) - { - Debug.Assert(instance_ == other.instance_); - - Buffer tmpBuf = other._buf; - other._buf = _buf; - _buf = tmpBuf; - - object tmpClosure = other._closure; - other._closure = _closure; - _closure = tmpClosure; - - // - // Swap is never called for BasicStreams that have encapsulations being read/write. However, - // encapsulations might still be set in case marshalling or un-marshalling failed. We just - // reset the encapsulations if there are still some set. - // - resetEncaps(); - other.resetEncaps(); - - int tmpStartSeq = other._startSeq; - other._startSeq = _startSeq; - _startSeq = tmpStartSeq; - - int tmpMinSeqSize = other._minSeqSize; - other._minSeqSize = _minSeqSize; - _minSeqSize = tmpMinSeqSize; - } - - public void resetEncaps() - { - _readEncapsStack = null; - _writeEncapsStack = null; - } - - public void resize(int sz, bool reading) - { - _buf.resize(sz, reading); - _buf.b.position(sz); - } - - public Buffer prepareWrite() - { - _buf.b.limit(_buf.size()); - _buf.b.position(0); - return _buf; - } - - public Buffer getBuffer() - { - return _buf; - } - - public void startWriteObject(Ice.SlicedData data) - { - Debug.Assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.startInstance(SliceType.ObjectSlice, data); - } - - public void endWriteObject() - { - Debug.Assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.endInstance(); - } - - public void startReadObject() - { - Debug.Assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - _readEncapsStack.decoder.startInstance(SliceType.ObjectSlice); - } - - public Ice.SlicedData endReadObject(bool preserve) - { - Debug.Assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - return _readEncapsStack.decoder.endInstance(preserve); - } - - public void startWriteException(Ice.SlicedData data) - { - Debug.Assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.startInstance(SliceType.ExceptionSlice, data); - } - - public void endWriteException() - { - Debug.Assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.endInstance(); - } - - public void startReadException() - { - Debug.Assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - _readEncapsStack.decoder.startInstance(SliceType.ExceptionSlice); - } - - public Ice.SlicedData endReadException(bool preserve) - { - Debug.Assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - return _readEncapsStack.decoder.endInstance(preserve); - } - - public void startWriteEncaps() - { - // - // If no encoding version is specified, use the current write - // encapsulation encoding version if there's a current write - // encapsulation, otherwise, use the stream encoding version. - // - - if(_writeEncapsStack != null) - { - startWriteEncaps(_writeEncapsStack.encoding, _writeEncapsStack.format); - } - else - { - startWriteEncaps(_encoding, Ice.FormatType.DefaultFormat); - } - } - - public void startWriteEncaps(Ice.EncodingVersion encoding, Ice.FormatType format) - { - Protocol.checkSupportedEncoding(encoding); - - WriteEncaps curr = _writeEncapsCache; - if(curr != null) - { - curr.reset(); - _writeEncapsCache = _writeEncapsCache.next; - } - else - { - curr = new WriteEncaps(); - } - curr.next = _writeEncapsStack; - _writeEncapsStack = curr; - - _writeEncapsStack.format = format; - _writeEncapsStack.setEncoding(encoding); - _writeEncapsStack.start = _buf.b.position(); - - writeInt(0); // Placeholder for the encapsulation length. - _writeEncapsStack.encoding.write__(this); - } - - public void endWriteEncaps() - { - Debug.Assert(_writeEncapsStack != null); - - // Size includes size and version. - int start = _writeEncapsStack.start; - int sz = _buf.size() - start; - _buf.b.putInt(start, sz); - - WriteEncaps curr = _writeEncapsStack; - _writeEncapsStack = curr.next; - curr.next = _writeEncapsCache; - _writeEncapsCache = curr; - _writeEncapsCache.reset(); - } - - public void endWriteEncapsChecked() - { - if(_writeEncapsStack == null) - { - throw new Ice.EncapsulationException("not in an encapsulation"); - } - endWriteEncaps(); - } - - public void writeEmptyEncaps(Ice.EncodingVersion encoding) - { - Protocol.checkSupportedEncoding(encoding); - writeInt(6); // Size - encoding.write__(this); - } - - public void writeEncaps(byte[] v) - { - if(v.Length < 6) - { - throw new Ice.EncapsulationException(); - } - expand(v.Length); - _buf.b.put(v); - } - - public Ice.EncodingVersion getWriteEncoding() - { - return _writeEncapsStack != null ? _writeEncapsStack.encoding : _encoding; - } - - public Ice.EncodingVersion startReadEncaps() - { - ReadEncaps curr = _readEncapsCache; - if(curr != null) - { - curr.reset(); - _readEncapsCache = _readEncapsCache.next; - } - else - { - curr = new ReadEncaps(); - } - curr.next = _readEncapsStack; - _readEncapsStack = curr; - - _readEncapsStack.start = _buf.b.position(); - - // - // I don't use readSize() and writeSize() for encapsulations, - // because when creating an encapsulation, I must know in advance - // how many bytes the size information will require in the data - // stream. If I use an Int, it is always 4 bytes. For - // readSize()/writeSize(), it could be 1 or 5 bytes. - // - int sz = readInt(); - if(sz < 6) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - if(sz - 4 > _buf.b.remaining()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - _readEncapsStack.sz = sz; - - Ice.EncodingVersion encoding = new Ice.EncodingVersion(); - encoding.read__(this); - Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported. - _readEncapsStack.setEncoding(encoding); - - return encoding; - } - - public void endReadEncaps() - { - Debug.Assert(_readEncapsStack != null); - - if(!_readEncapsStack.encoding_1_0) - { - skipOpts(); - if(_buf.b.position() != _readEncapsStack.start + _readEncapsStack.sz) - { - throw new Ice.EncapsulationException(); - } - } - else if(_buf.b.position() != _readEncapsStack.start + _readEncapsStack.sz) - { - if(_buf.b.position() + 1 != _readEncapsStack.start + _readEncapsStack.sz) - { - throw new Ice.EncapsulationException(); - } - - // - // Ice version < 3.3 had a bug where user exceptions with - // class members could be encoded with a trailing byte - // when dispatched with AMD. So we tolerate an extra byte - // in the encapsulation. - // - try - { - _buf.b.get(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - ReadEncaps curr = _readEncapsStack; - _readEncapsStack = curr.next; - curr.next = _readEncapsCache; - _readEncapsCache = curr; - _readEncapsCache.reset(); - } - - public Ice.EncodingVersion skipEmptyEncaps() - { - int sz = readInt(); - if(sz < 6) - { - throw new Ice.EncapsulationException(); - } - if(sz - 4 > _buf.b.remaining()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - Ice.EncodingVersion encoding = new Ice.EncodingVersion(); - encoding.read__(this); - if(encoding.Equals(Ice.Util.Encoding_1_0)) - { - if(sz != 6) - { - throw new Ice.EncapsulationException(); - } - } - else - { - // Skip the optional content of the encapsulation if we are expecting an - // empty encapsulation. - _buf.b.position(_buf.b.position() + sz - 6); - } - return encoding; - } - - public void endReadEncapsChecked() // Used by public stream API. - { - if(_readEncapsStack == null) - { - throw new Ice.EncapsulationException("not in an encapsulation"); - } - endReadEncaps(); - } - - public byte[] readEncaps(out Ice.EncodingVersion encoding) - { - int sz = readInt(); - if(sz < 6) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - if(sz - 4 > _buf.b.remaining()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - encoding = new Ice.EncodingVersion(); - encoding.read__(this); - _buf.b.position(_buf.b.position() - 6); - - byte[] v = new byte[sz]; - try - { - _buf.b.get(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public Ice.EncodingVersion getReadEncoding() - { - return _readEncapsStack != null ? _readEncapsStack.encoding : _encoding; - } - - public int getReadEncapsSize() - { - Debug.Assert(_readEncapsStack != null); - return _readEncapsStack.sz - 6; - } - - public Ice.EncodingVersion skipEncaps() - { - int sz = readInt(); - if(sz < 6) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - Ice.EncodingVersion encoding = new Ice.EncodingVersion(); - encoding.read__(this); - try - { - _buf.b.position(_buf.b.position() + sz - 6); - } - catch(ArgumentOutOfRangeException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - return encoding; - } - - public void startWriteSlice(string typeId, int compactId, bool last) - { - Debug.Assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.startSlice(typeId, compactId, last); - } - - public void endWriteSlice() - { - Debug.Assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.endSlice(); - } - - public string startReadSlice() // Returns type ID of next slice - { - Debug.Assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - return _readEncapsStack.decoder.startSlice(); - } - - public void endReadSlice() - { - Debug.Assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - _readEncapsStack.decoder.endSlice(); - } - - public void skipSlice() - { - Debug.Assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - _readEncapsStack.decoder.skipSlice(); - } - - public void readPendingObjects() - { - if(_readEncapsStack != null && _readEncapsStack.decoder != null) - { - _readEncapsStack.decoder.readPendingObjects(); - } - else if(_readEncapsStack != null ? _readEncapsStack.encoding_1_0 : _encoding.Equals(Ice.Util.Encoding_1_0)) - { - // - // If using the 1.0 encoding and no objects were read, we - // still read an empty sequence of pending objects if - // requested (i.e.: if this is called). - // - // This is required by the 1.0 encoding, even if no objects - // are written we do marshal an empty sequence if marshaled - // data types use classes. - // - skipSize(); - } - } - - public void writePendingObjects() - { - if(_writeEncapsStack != null && _writeEncapsStack.encoder != null) - { - _writeEncapsStack.encoder.writePendingObjects(); - } - else if(_writeEncapsStack != null ? - _writeEncapsStack.encoding_1_0 : _encoding.Equals(Ice.Util.Encoding_1_0)) - { - // - // If using the 1.0 encoding and no objects were written, we - // still write an empty sequence for pending objects if - // requested (i.e.: if this is called). - // - // This is required by the 1.0 encoding, even if no objects - // are written we do marshal an empty sequence if marshaled - // data types use classes. - // - writeSize(0); - } - } - - public void writeSize(int v) - { - if(v > 254) - { - expand(5); - _buf.b.put((byte)255); - _buf.b.putInt(v); - } - else - { - expand(1); - _buf.b.put((byte)v); - } - } - - public int readSize() - { - try - { - // - // COMPILERFIX: for some reasons _buf.get() doesn't work here on OS X with Mono; - // - //byte b = _buf.b.get(); - byte b = readByte(); - if(b == 255) - { - int v = _buf.b.getInt(); - if(v < 0) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - return v; - } - else - { - return b; // byte is unsigned - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public int readAndCheckSeqSize(int minSize) - { - int sz = readSize(); - - if(sz == 0) - { - return 0; - } - - // - // The _startSeq variable points to the start of the sequence for which - // we expect to read at least _minSeqSize bytes from the stream. - // - // If not initialized or if we already read more data than _minSeqSize, - // we reset _startSeq and _minSeqSize for this sequence (possibly a - // top-level sequence or enclosed sequence it doesn't really matter). - // - // Otherwise, we are reading an enclosed sequence and we have to bump - // _minSeqSize by the minimum size that this sequence will require on - // the stream. - // - // The goal of this check is to ensure that when we start un-marshalling - // a new sequence, we check the minimal size of this new sequence against - // the estimated remaining buffer size. This estimatation is based on - // the minimum size of the enclosing sequences, it's _minSeqSize. - // - if(_startSeq == -1 || _buf.b.position() > (_startSeq + _minSeqSize)) - { - _startSeq = _buf.b.position(); - _minSeqSize = sz * minSize; - } - else - { - _minSeqSize += sz * minSize; - } - - // - // If there isn't enough data to read on the stream for the sequence (and - // possibly enclosed sequences), something is wrong with the marshalled - // data: it's claiming having more data that what is possible to read. - // - if(_startSeq + _minSeqSize > _buf.size()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - return sz; - } - - public int startSize() - { - int pos = _buf.b.position(); - writeInt(0); // Placeholder for 32-bit size - return pos; - } - - public void endSize(int pos) - { - Debug.Assert(pos >= 0); - rewriteInt(_buf.b.position() - pos - 4, pos); - } - - public void writeBlob(byte[] v) - { - if(v == null) - { - return; - } - expand(v.Length); - _buf.b.put(v); - } - - public void readBlob(byte[] v) - { - try - { - _buf.b.get(v); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public byte[] readBlob(int sz) - { - if(_buf.b.remaining() < sz) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - byte[] v = new byte[sz]; - try - { - _buf.b.get(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - // Read/write type and tag for optionals - public bool writeOpt(int tag, Ice.OptionalFormat format) - { - Debug.Assert(_writeEncapsStack != null); - if(_writeEncapsStack.encoder != null) - { - return _writeEncapsStack.encoder.writeOpt(tag, format); - } - else - { - return writeOptImpl(tag, format); - } - } - - public bool readOpt(int tag, Ice.OptionalFormat expectedFormat) - { - Debug.Assert(_readEncapsStack != null); - if(_readEncapsStack.decoder != null) - { - return _readEncapsStack.decoder.readOpt(tag, expectedFormat); - } - else - { - return readOptImpl(tag, expectedFormat); - } - } - - public void writeByte(byte v) - { - expand(1); - _buf.b.put(v); - } - - public void writeByte(int tag, Ice.Optional<byte> v) - { - if(v.HasValue) - { - writeByte(tag, v.Value); - } - } - - public void writeByte(int tag, byte v) - { - if(writeOpt(tag, Ice.OptionalFormat.F1)) - { - writeByte(v); - } - } - - public void rewriteByte(byte v, int dest) - { - _buf.b.put(dest, v); - } - - public void writeByteSeq(byte[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length); - _buf.b.put(v); - } - } - - public void writeByteSeq(int count, IEnumerable<byte> v) - { - if(count == 0) - { - writeSize(0); - return; - } - - { - List<byte> value = v as List<byte>; - if(value != null) - { - writeByteSeq(value.ToArray()); - return; - } - } - - { - LinkedList<byte> value = v as LinkedList<byte>; - if(value != null) - { - writeSize(count); - expand(count); - IEnumerator<byte> i = v.GetEnumerator(); - while(i.MoveNext()) - { - _buf.b.put(i.Current); - } - return; - } - } - - { - Queue<byte> value = v as Queue<byte>; - if(value != null) - { - writeByteSeq(value.ToArray()); - return; - } - } - - { - Stack<byte> value = v as Stack<byte>; - if(value != null) - { - writeByteSeq(value.ToArray()); - return; - } - } - - writeSize(count); - expand(count); - foreach(byte b in v) - { - _buf.b.put(b); - } - } - - public void writeByteSeq(int tag, Ice.Optional<byte[]> v) - { - if(v.HasValue) - { - writeByteSeq(tag, v.Value); - } - } - - public void writeByteSeq<T>(int tag, int count, Ice.Optional<T> v) - where T : IEnumerable<byte> - { - if(v.HasValue && writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeByteSeq(count, v.Value); - } - } - - public void writeByteSeq(int tag, byte[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeByteSeq(v); - } - } - - public void writeByteSeq(int tag, int count, IEnumerable<byte> v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeByteSeq(count, v); - } - } - - public void writeSerializable(object o) - { -#if !COMPACT && !SILVERLIGHT - if(o == null) - { - writeSize(0); - return; - } - try - { - StreamWrapper w = new StreamWrapper(this); - IFormatter f = new BinaryFormatter(); - f.Serialize(w, o); - w.Close(); - } - catch(System.Exception ex) - { - throw new Ice.MarshalException("cannot serialize object:", ex); - } -#else - throw new Ice.MarshalException("serialization not supported"); -#endif - } - - public byte readByte() - { - try - { - return _buf.b.get(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public Ice.Optional<byte> readByte(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.F1)) - { - return new Ice.Optional<byte>(readByte()); - } - else - { - return new Ice.Optional<byte>(); - } - } - - public void readByte(int tag, out bool isset, out byte v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.F1)) - { - v = readByte(); - } - else - { - v = 0; - } - } - - public byte[] readByteSeq() - { - try - { - int sz = readAndCheckSeqSize(1); - byte[] v = new byte[sz]; - _buf.b.get(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readByteSeq(out List<byte> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new List<byte>(readByteSeq()); - } - - public void readByteSeq(out LinkedList<byte> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new LinkedList<byte>(readByteSeq()); - } - - public void readByteSeq(out Queue<byte> l) - { - // - // Reading into an array and copy-constructing the - // queue is faster than constructing the queue - // and adding to it one element at a time. - // - l = new Queue<byte>(readByteSeq()); - } - - public void readByteSeq(out Stack<byte> l) - { - // - // Reverse the contents by copying into an array first - // because the stack is marshaled in top-to-bottom order. - // - byte[] array = readByteSeq(); - Array.Reverse(array); - l = new Stack<byte>(array); - } - - public Ice.Optional<byte[]> readByteSeq(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - return new Ice.Optional<byte[]>(readByteSeq()); - } - else - { - return new Ice.Optional<byte[]>(); - } - } - - public void readByteSeq(int tag, out bool isset, out byte[] v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.VSize)) - { - v = readByteSeq(); - } - else - { - v = null; - } - } - - public object readSerializable() - { -#if !COMPACT && !SILVERLIGHT - int sz = readAndCheckSeqSize(1); - if(sz == 0) - { - return null; - } - try - { - StreamWrapper w = new StreamWrapper(sz, this); - IFormatter f = new BinaryFormatter(); - return f.Deserialize(w); - } - catch(System.Exception ex) - { - throw new Ice.MarshalException("cannot deserialize object:", ex); - } -#else - throw new Ice.MarshalException("serialization not supported"); -#endif - } - - public void writeBool(bool v) - { - expand(1); - _buf.b.put(v ? (byte)1 : (byte)0); - } - - public void writeBool(int tag, Ice.Optional<bool> v) - { - if(v.HasValue) - { - writeBool(tag, v.Value); - } - } - - public void writeBool(int tag, bool v) - { - if(writeOpt(tag, Ice.OptionalFormat.F1)) - { - writeBool(v); - } - } - - public void rewriteBool(bool v, int dest) - { - _buf.b.put(dest, v ? (byte)1 : (byte)0); - } - - public void writeBoolSeq(bool[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length); - _buf.b.putBoolSeq(v); - } - } - - public void writeBoolSeq(int count, IEnumerable<bool> v) - { - if(count == 0) - { - writeSize(0); - return; - } - - { - List<bool> value = v as List<bool>; - if(value != null) - { - writeBoolSeq(value.ToArray()); - return; - } - } - - { - LinkedList<bool> value = v as LinkedList<bool>; - if(value != null) - { - writeSize(count); - expand(count); - IEnumerator<bool> i = v.GetEnumerator(); - while(i.MoveNext()) - { - _buf.b.putBool(i.Current); - } - return; - } - } - - { - Queue<bool> value = v as Queue<bool>; - if(value != null) - { - writeBoolSeq(value.ToArray()); - return; - } - } - - { - Stack<bool> value = v as Stack<bool>; - if(value != null) - { - writeBoolSeq(value.ToArray()); - return; - } - } - - writeSize(count); - expand(count); - foreach(bool b in v) - { - _buf.b.putBool(b); - } - } - - public void writeBoolSeq(int tag, Ice.Optional<bool[]> v) - { - if(v.HasValue) - { - writeBoolSeq(tag, v.Value); - } - } - - public void writeBoolSeq<T>(int tag, int count, Ice.Optional<T> v) - where T : IEnumerable<bool> - { - if(v.HasValue && writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeBoolSeq(count, v.Value); - } - } - - public void writeBoolSeq(int tag, bool[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeBoolSeq(v); - } - } - - public void writeBoolSeq(int tag, int count, IEnumerable<bool> v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeBoolSeq(count, v); - } - } - - public bool readBool() - { - try - { - return _buf.b.get() == 1; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public Ice.Optional<bool> readBool(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.F1)) - { - return new Ice.Optional<bool>(readBool()); - } - else - { - return new Ice.Optional<bool>(); - } - } - - public void readBool(int tag, out bool isset, out bool v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.F1)) - { - v = readBool(); - } - else - { - v = false; - } - } - - public bool[] readBoolSeq() - { - try - { - int sz = readAndCheckSeqSize(1); - bool[] v = new bool[sz]; - _buf.b.getBoolSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readBoolSeq(out List<bool> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new List<bool>(readBoolSeq()); - } - - public void readBoolSeq(out LinkedList<bool> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new LinkedList<bool>(readBoolSeq()); - } - - public void readBoolSeq(out Queue<bool> l) - { - // - // Reading into an array and copy-constructing the - // queue is faster than constructing the queue - // and adding to it one element at a time. - // - l = new Queue<bool>(readBoolSeq()); - } - - public void readBoolSeq(out Stack<bool> l) - { - // - // Reverse the contents by copying into an array first - // because the stack is marshaled in top-to-bottom order. - // - bool[] array = readBoolSeq(); - Array.Reverse(array); - l = new Stack<bool>(array); - } - - public Ice.Optional<bool[]> readBoolSeq(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - return new Ice.Optional<bool[]>(readBoolSeq()); - } - else - { - return new Ice.Optional<bool[]>(); - } - } - - public void readBoolSeq(int tag, out bool isset, out bool[] v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.VSize)) - { - v = readBoolSeq(); - } - else - { - v = null; - } - } - - public void writeShort(short v) - { - expand(2); - _buf.b.putShort(v); - } - - public void writeShort(int tag, Ice.Optional<short> v) - { - if(v.HasValue) - { - writeShort(tag, v.Value); - } - } - - public void writeShort(int tag, short v) - { - if(writeOpt(tag, Ice.OptionalFormat.F2)) - { - writeShort(v); - } - } - - public void writeShortSeq(short[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 2); - _buf.b.putShortSeq(v); - } - } - - public void writeShortSeq(int count, IEnumerable<short> v) - { - if(count == 0) - { - writeSize(0); - return; - } - - { - List<short> value = v as List<short>; - if(value != null) - { - writeShortSeq(value.ToArray()); - return; - } - } - - { - LinkedList<short> value = v as LinkedList<short>; - if(value != null) - { - writeSize(count); - expand(count * 2); - IEnumerator<short> i = v.GetEnumerator(); - while(i.MoveNext()) - { - _buf.b.putShort(i.Current); - } - return; - } - } - - { - Queue<short> value = v as Queue<short>; - if(value != null) - { - writeShortSeq(value.ToArray()); - return; - } - } - - { - Stack<short> value = v as Stack<short>; - if(value != null) - { - writeShortSeq(value.ToArray()); - return; - } - } - - writeSize(count); - expand(count * 2); - foreach(short s in v) - { - _buf.b.putShort(s); - } - } - - public void writeShortSeq(int tag, Ice.Optional<short[]> v) - { - if(v.HasValue) - { - writeShortSeq(tag, v.Value); - } - } - - public void writeShortSeq<T>(int tag, int count, Ice.Optional<T> v) - where T : IEnumerable<short> - { - if(v.HasValue && writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(count == 0 ? 1 : count * 2 + (count > 254 ? 5 : 1)); - writeShortSeq(count, v.Value); - } - } - - public void writeShortSeq(int tag, short[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.Length == 0 ? 1 : v.Length * 2 + (v.Length > 254 ? 5 : 1)); - writeShortSeq(v); - } - } - - public void writeShortSeq(int tag, int count, IEnumerable<short> v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || count == 0 ? 1 : count * 2 + (count > 254 ? 5 : 1)); - writeShortSeq(count, v); - } - } - - public short readShort() - { - try - { - return _buf.b.getShort(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public Ice.Optional<short> readShort(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.F2)) - { - return new Ice.Optional<short>(readShort()); - } - else - { - return new Ice.Optional<short>(); - } - } - - public void readShort(int tag, out bool isset, out short v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.F2)) - { - v = readShort(); - } - else - { - v = 0; - } - } - - public short[] readShortSeq() - { - try - { - int sz = readAndCheckSeqSize(2); - short[] v = new short[sz]; - _buf.b.getShortSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readShortSeq(out List<short> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new List<short>(readShortSeq()); - } - - public void readShortSeq(out LinkedList<short> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new LinkedList<short>(readShortSeq()); - } - - public void readShortSeq(out Queue<short> l) - { - // - // Reading into an array and copy-constructing the - // queue is faster than constructing the queue - // and adding to it one element at a time. - // - l = new Queue<short>(readShortSeq()); - } - - public void readShortSeq(out Stack<short> l) - { - // - // Reverse the contents by copying into an array first - // because the stack is marshaled in top-to-bottom order. - // - short[] array = readShortSeq(); - Array.Reverse(array); - l = new Stack<short>(array); - } - - public Ice.Optional<short[]> readShortSeq(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - return new Ice.Optional<short[]>(readShortSeq()); - } - else - { - return new Ice.Optional<short[]>(); - } - } - - public void readShortSeq(int tag, out bool isset, out short[] v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v = readShortSeq(); - } - else - { - v = null; - } - } - - public void writeInt(int v) - { - expand(4); - _buf.b.putInt(v); - } - - public void writeInt(int tag, Ice.Optional<int> v) - { - if(v.HasValue) - { - writeInt(tag, v.Value); - } - } - - public void writeInt(int tag, int v) - { - if(writeOpt(tag, Ice.OptionalFormat.F4)) - { - writeInt(v); - } - } - - public void rewriteInt(int v, int dest) - { - _buf.b.putInt(dest, v); - } - - public void writeIntSeq(int[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 4); - _buf.b.putIntSeq(v); - } - } - - public void writeIntSeq(int count, IEnumerable<int> v) - { - if(count == 0) - { - writeSize(0); - return; - } - - { - List<int> value = v as List<int>; - if(value != null) - { - writeIntSeq(value.ToArray()); - return; - } - } - - { - LinkedList<int> value = v as LinkedList<int>; - if(value != null) - { - writeSize(count); - expand(count * 4); - IEnumerator<int> i = v.GetEnumerator(); - while(i.MoveNext()) - { - _buf.b.putInt(i.Current); - } - return; - } - } - - { - Queue<int> value = v as Queue<int>; - if(value != null) - { - writeIntSeq(value.ToArray()); - return; - } - } - - { - Stack<int> value = v as Stack<int>; - if(value != null) - { - writeIntSeq(value.ToArray()); - return; - } - } - - writeSize(count); - expand(count * 4); - foreach(int i in v) - { - _buf.b.putInt(i); - } - } - - public void writeIntSeq(int tag, Ice.Optional<int[]> v) - { - if(v.HasValue) - { - writeIntSeq(tag, v.Value); - } - } - - public void writeIntSeq<T>(int tag, int count, Ice.Optional<T> v) - where T : IEnumerable<int> - { - if(v.HasValue && writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(count == 0 ? 1 : count * 4 + (count > 254 ? 5 : 1)); - writeIntSeq(count, v.Value); - } - } - - public void writeIntSeq(int tag, int[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.Length == 0 ? 1 : v.Length * 4 + (v.Length > 254 ? 5 : 1)); - writeIntSeq(v); - } - } - - public void writeIntSeq(int tag, int count, IEnumerable<int> v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || count == 0 ? 1 : count * 4 + (count > 254 ? 5 : 1)); - writeIntSeq(count, v); - } - } - - public int readInt() - { - try - { - return _buf.b.getInt(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public Ice.Optional<int> readInt(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.F4)) - { - return new Ice.Optional<int>(readInt()); - } - else - { - return new Ice.Optional<int>(); - } - } - - public void readInt(int tag, out bool isset, out int v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.F4)) - { - v = readInt(); - } - else - { - v = 0; - } - } - - public int[] readIntSeq() - { - try - { - int sz = readAndCheckSeqSize(4); - int[] v = new int[sz]; - _buf.b.getIntSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readIntSeq(out List<int> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new List<int>(readIntSeq()); - } - - public void readIntSeq(out LinkedList<int> l) - { - try - { - int sz = readAndCheckSeqSize(4); - l = new LinkedList<int>(); - for(int i = 0; i < sz; ++i) - { - l.AddLast(_buf.b.getInt()); - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readIntSeq(out Queue<int> l) - { - // - // Reading into an array and copy-constructing the - // queue takes the same time as constructing the queue - // and adding to it one element at a time, so - // we avoid the copy. - // - try - { - int sz = readAndCheckSeqSize(4); - l = new Queue<int>(sz); - for(int i = 0; i < sz; ++i) - { - l.Enqueue(_buf.b.getInt()); - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readIntSeq(out Stack<int> l) - { - // - // Reverse the contents by copying into an array first - // because the stack is marshaled in top-to-bottom order. - // - int[] array = readIntSeq(); - Array.Reverse(array); - l = new Stack<int>(array); - } - - public Ice.Optional<int[]> readIntSeq(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - return new Ice.Optional<int[]>(readIntSeq()); - } - else - { - return new Ice.Optional<int[]>(); - } - } - - public void readIntSeq(int tag, out bool isset, out int[] v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v = readIntSeq(); - } - else - { - v = null; - } - } - - public void writeLong(long v) - { - expand(8); - _buf.b.putLong(v); - } - - public void writeLong(int tag, Ice.Optional<long> v) - { - if(v.HasValue) - { - writeLong(tag, v.Value); - } - } - - public void writeLong(int tag, long v) - { - if(writeOpt(tag, Ice.OptionalFormat.F8)) - { - writeLong(v); - } - } - - public void writeLongSeq(long[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 8); - _buf.b.putLongSeq(v); - } - } - - public void writeLongSeq(int count, IEnumerable<long> v) - { - if(count == 0) - { - writeSize(0); - return; - } - - { - List<long> value = v as List<long>; - if(value != null) - { - writeLongSeq(value.ToArray()); - return; - } - } - - { - LinkedList<long> value = v as LinkedList<long>; - if(value != null) - { - writeSize(count); - expand(count * 8); - IEnumerator<long> i = v.GetEnumerator(); - while(i.MoveNext()) - { - _buf.b.putLong(i.Current); - } - return; - } - } - - { - Queue<long> value = v as Queue<long>; - if(value != null) - { - writeLongSeq(value.ToArray()); - return; - } - } - - { - Stack<long> value = v as Stack<long>; - if(value != null) - { - writeLongSeq(value.ToArray()); - return; - } - } - - writeSize(count); - expand(count * 8); - foreach(long l in v) - { - _buf.b.putLong(l); - } - } - - public void writeLongSeq(int tag, Ice.Optional<long[]> v) - { - if(v.HasValue) - { - writeLongSeq(tag, v.Value); - } - } - - public void writeLongSeq<T>(int tag, int count, Ice.Optional<T> v) - where T : IEnumerable<long> - { - if(v.HasValue && writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(count == 0 ? 1 : count * 8 + (count > 254 ? 5 : 1)); - writeLongSeq(count, v.Value); - } - } - - public void writeLongSeq(int tag, long[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.Length == 0 ? 1 : v.Length * 8 + (v.Length > 254 ? 5 : 1)); - writeLongSeq(v); - } - } - - public void writeLongSeq(int tag, int count, IEnumerable<long> v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || count == 0 ? 1 : count * 8 + (count > 254 ? 5 : 1)); - writeLongSeq(count, v); - } - } - - public long readLong() - { - try - { - return _buf.b.getLong(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public Ice.Optional<long> readLong(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.F8)) - { - return new Ice.Optional<long>(readLong()); - } - else - { - return new Ice.Optional<long>(); - } - } - - public void readLong(int tag, out bool isset, out long v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.F8)) - { - v = readLong(); - } - else - { - v = 0; - } - } - - public long[] readLongSeq() - { - try - { - int sz = readAndCheckSeqSize(8); - long[] v = new long[sz]; - _buf.b.getLongSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readLongSeq(out List<long> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new List<long>(readLongSeq()); - } - - public void readLongSeq(out LinkedList<long> l) - { - try - { - int sz = readAndCheckSeqSize(4); - l = new LinkedList<long>(); - for(int i = 0; i < sz; ++i) - { - l.AddLast(_buf.b.getLong()); - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readLongSeq(out Queue<long> l) - { - // - // Reading into an array and copy-constructing the - // queue takes the same time as constructing the queue - // and adding to it one element at a time, so - // we avoid the copy. - // - try - { - int sz = readAndCheckSeqSize(4); - l = new Queue<long>(sz); - for(int i = 0; i < sz; ++i) - { - l.Enqueue(_buf.b.getLong()); - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readLongSeq(out Stack<long> l) - { - // - // Reverse the contents by copying into an array first - // because the stack is marshaled in top-to-bottom order. - // - long[] array = readLongSeq(); - Array.Reverse(array); - l = new Stack<long>(array); - } - - public Ice.Optional<long[]> readLongSeq(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - return new Ice.Optional<long[]>(readLongSeq()); - } - else - { - return new Ice.Optional<long[]>(); - } - } - - public void readLongSeq(int tag, out bool isset, out long[] v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v = readLongSeq(); - } - else - { - v = null; - } - } - - public void writeFloat(float v) - { - expand(4); - _buf.b.putFloat(v); - } - - public void writeFloat(int tag, Ice.Optional<float> v) - { - if(v.HasValue) - { - writeFloat(tag, v.Value); - } - } - - public void writeFloat(int tag, float v) - { - if(writeOpt(tag, Ice.OptionalFormat.F4)) - { - writeFloat(v); - } - } - - public void writeFloatSeq(float[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 4); - _buf.b.putFloatSeq(v); - } - } - - public void writeFloatSeq(int count, IEnumerable<float> v) - { - if(count == 0) - { - writeSize(0); - return; - } - - { - List<float> value = v as List<float>; - if(value != null) - { - writeFloatSeq(value.ToArray()); - return; - } - } - - { - LinkedList<float> value = v as LinkedList<float>; - if(value != null) - { - writeSize(count); - expand(count * 4); - IEnumerator<float> i = v.GetEnumerator(); - while(i.MoveNext()) - { - _buf.b.putFloat(i.Current); - } - return; - } - } - - { - Queue<float> value = v as Queue<float>; - if(value != null) - { - writeFloatSeq(value.ToArray()); - return; - } - } - - { - Stack<float> value = v as Stack<float>; - if(value != null) - { - writeFloatSeq(value.ToArray()); - return; - } - } - - writeSize(count); - expand(count * 4); - foreach(float f in v) - { - _buf.b.putFloat(f); - } - } - - public void writeFloatSeq(int tag, Ice.Optional<float[]> v) - { - if(v.HasValue) - { - writeFloatSeq(tag, v.Value); - } - } - - public void writeFloatSeq<T>(int tag, int count, Ice.Optional<T> v) - where T : IEnumerable<float> - { - if(v.HasValue && writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(count == 0 ? 1 : count * 4 + (count > 254 ? 5 : 1)); - writeFloatSeq(count, v.Value); - } - } - - public void writeFloatSeq(int tag, float[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.Length == 0 ? 1 : v.Length * 4 + (v.Length > 254 ? 5 : 1)); - writeFloatSeq(v); - } - } - - public void writeFloatSeq(int tag, int count, IEnumerable<float> v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || count == 0 ? 1 : count * 4 + (count > 254 ? 5 : 1)); - writeFloatSeq(count, v); - } - } - - public float readFloat() - { - try - { - return _buf.b.getFloat(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public Ice.Optional<float> readFloat(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.F4)) - { - return new Ice.Optional<float>(readFloat()); - } - else - { - return new Ice.Optional<float>(); - } - } - - public void readFloat(int tag, out bool isset, out float v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.F4)) - { - v = readFloat(); - } - else - { - v = 0; - } - } - - public float[] readFloatSeq() - { - try - { - int sz = readAndCheckSeqSize(4); - float[] v = new float[sz]; - _buf.b.getFloatSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readFloatSeq(out List<float> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new List<float>(readFloatSeq()); - } - - public void readFloatSeq(out LinkedList<float> l) - { - try - { - int sz = readAndCheckSeqSize(4); - l = new LinkedList<float>(); - for(int i = 0; i < sz; ++i) - { - l.AddLast(_buf.b.getFloat()); - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readFloatSeq(out Queue<float> l) - { - // - // Reading into an array and copy-constructing the - // queue takes the same time as constructing the queue - // and adding to it one element at a time, so - // we avoid the copy. - // - try - { - int sz = readAndCheckSeqSize(4); - l = new Queue<float>(sz); - for(int i = 0; i < sz; ++i) - { - l.Enqueue(_buf.b.getFloat()); - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readFloatSeq(out Stack<float> l) - { - // - // Reverse the contents by copying into an array first - // because the stack is marshaled in top-to-bottom order. - // - float[] array = readFloatSeq(); - Array.Reverse(array); - l = new Stack<float>(array); - } - - public Ice.Optional<float[]> readFloatSeq(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - return new Ice.Optional<float[]>(readFloatSeq()); - } - else - { - return new Ice.Optional<float[]>(); - } - } - - public void readFloatSeq(int tag, out bool isset, out float[] v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v = readFloatSeq(); - } - else - { - v = null; - } - } - - public void writeDouble(double v) - { - expand(8); - _buf.b.putDouble(v); - } - - public void writeDouble(int tag, Ice.Optional<double> v) - { - if(v.HasValue) - { - writeDouble(tag, v.Value); - } - } - - public void writeDouble(int tag, double v) - { - if(writeOpt(tag, Ice.OptionalFormat.F8)) - { - writeDouble(v); - } - } - - public void writeDoubleSeq(double[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 8); - _buf.b.putDoubleSeq(v); - } - } - - public void writeDoubleSeq(int count, IEnumerable<double> v) - { - if(count == 0) - { - writeSize(0); - return; - } - - { - List<double> value = v as List<double>; - if(value != null) - { - writeDoubleSeq(value.ToArray()); - return; - } - } - - { - LinkedList<double> value = v as LinkedList<double>; - if(value != null) - { - writeSize(count); - expand(count * 8); - IEnumerator<double> i = v.GetEnumerator(); - while(i.MoveNext()) - { - _buf.b.putDouble(i.Current); - } - return; - } - } - - { - Queue<double> value = v as Queue<double>; - if(value != null) - { - writeDoubleSeq(value.ToArray()); - return; - } - } - - { - Stack<double> value = v as Stack<double>; - if (value != null) - { - writeDoubleSeq(value.ToArray()); - return; - } - } - - writeSize(count); - expand(count * 8); - foreach(double d in v) - { - _buf.b.putDouble(d); - } - } - - public void writeDoubleSeq(int tag, Ice.Optional<double[]> v) - { - if(v.HasValue) - { - writeDoubleSeq(tag, v.Value); - } - } - - public void writeDoubleSeq<T>(int tag, int count, Ice.Optional<T> v) - where T : IEnumerable<double> - { - if(v.HasValue && writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(count == 0 ? 1 : count * 8 + (count > 254 ? 5 : 1)); - writeDoubleSeq(count, v.Value); - } - } - - public void writeDoubleSeq(int tag, double[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.Length == 0 ? 1 : v.Length * 8 + (v.Length > 254 ? 5 : 1)); - writeDoubleSeq(v); - } - } - - public void writeDoubleSeq(int tag, int count, IEnumerable<double> v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || count == 0 ? 1 : count * 8 + (count > 254 ? 5 : 1)); - writeDoubleSeq(count, v); - } - } - - public double readDouble() - { - try - { - return _buf.b.getDouble(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public Ice.Optional<double> readDouble(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.F8)) - { - return new Ice.Optional<double>(readDouble()); - } - else - { - return new Ice.Optional<double>(); - } - } - - public void readDouble(int tag, out bool isset, out double v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.F8)) - { - v = readDouble(); - } - else - { - v = 0; - } - } - - public double[] readDoubleSeq() - { - try - { - int sz = readAndCheckSeqSize(8); - double[] v = new double[sz]; - _buf.b.getDoubleSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readDoubleSeq(out List<double> l) - { - // - // Reading into an array and copy-constructing the - // list is faster than constructing the list - // and adding to it one element at a time. - // - l = new List<double>(readDoubleSeq()); - } - - public void readDoubleSeq(out LinkedList<double> l) - { - try - { - int sz = readAndCheckSeqSize(4); - l = new LinkedList<double>(); - for(int i = 0; i < sz; ++i) - { - l.AddLast(_buf.b.getDouble()); - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readDoubleSeq(out Queue<double> l) - { - // - // Reading into an array and copy-constructing the - // queue takes the same time as constructing the queue - // and adding to it one element at a time, so - // we avoid the copy. - // - try - { - int sz = readAndCheckSeqSize(4); - l = new Queue<double>(sz); - for(int i = 0; i < sz; ++i) - { - l.Enqueue(_buf.b.getDouble()); - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public void readDoubleSeq(out Stack<double> l) - { - // - // Reverse the contents by copying into an array first - // because the stack is marshaled in top-to-bottom order. - // - double[] array = readDoubleSeq(); - Array.Reverse(array); - l = new Stack<double>(array); - } - - public Ice.Optional<double[]> readDoubleSeq(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - return new Ice.Optional<double[]>(readDoubleSeq()); - } - else - { - return new Ice.Optional<double[]>(); - } - } - - public void readDoubleSeq(int tag, out bool isset, out double[] v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v = readDoubleSeq(); - } - else - { - v = null; - } - } - - private static System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); - - public void writeString(string v) - { - if(v == null || v.Length == 0) - { - writeSize(0); - return; - } - byte[] arr = utf8.GetBytes(v); - writeSize(arr.Length); - expand(arr.Length); - _buf.b.put(arr); - } - - public void writeString(int tag, Ice.Optional<string> v) - { - if(v.HasValue) - { - writeString(tag, v.Value); - } - } - - public void writeString(int tag, string v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeString(v); - } - } - - public void writeStringSeq(string[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - for(int i = 0; i < v.Length; i++) - { - writeString(v[i]); - } - } - } - - public void writeStringSeq(int size, IEnumerable<string> e) - { - writeSize(size); - if(size != 0) - { - foreach(string s in e) - { - writeString(s); - } - } - } - - public void writeStringSeq(int tag, Ice.Optional<String[]> v) - { - if(v.HasValue) - { - writeStringSeq(tag, v.Value); - } - } - - public void writeStringSeq<T>(int tag, int count, Ice.Optional<T> v) - where T : IEnumerable<string> - { - if(v.HasValue && writeOpt(tag, Ice.OptionalFormat.FSize)) - { - int pos = startSize(); - writeStringSeq(count, v.Value); - endSize(pos); - } - } - - public void writeStringSeq(int tag, string[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.FSize)) - { - int pos = startSize(); - writeStringSeq(v); - endSize(pos); - } - } - - public void writeStringSeq(int tag, int count, IEnumerable<string> v) - { - if(writeOpt(tag, Ice.OptionalFormat.FSize)) - { - int pos = startSize(); - writeStringSeq(count, v); - endSize(pos); - } - } - - public string readString() - { - int len = readSize(); - - if(len == 0) - { - return ""; - } - - // - // Check the buffer has enough bytes to read. - // - if(_buf.b.remaining() < len) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - try - { - // - // We reuse the _stringBytes array to avoid creating - // excessive garbage - // - if(_stringBytes == null || len > _stringBytes.Length) - { - _stringBytes = new byte[len]; - } - _buf.b.get(_stringBytes, 0, len); - return utf8.GetString(_stringBytes, 0, len); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - catch(System.ArgumentException ex) - { - throw new Ice.MarshalException("Invalid UTF8 string", ex); - } - } - - public Ice.Optional<string> readString(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - return new Ice.Optional<string>(readString()); - } - else - { - return new Ice.Optional<string>(); - } - } - - public void readString(int tag, out bool isset, out string v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.VSize)) - { - v = readString(); - } - else - { - v = null; - } - } - - public string[] readStringSeq() - { - int sz = readAndCheckSeqSize(1); - string[] v = new string[sz]; - for(int i = 0; i < sz; i++) - { - v[i] = readString(); - } - return v; - } - - public void readStringSeq(out List<string> l) - { - // - // Reading into an array and copy-constructing the - // list is slower than constructing the list - // and adding to it one element at a time. - // - int sz = readAndCheckSeqSize(1); - l = new List<string>(sz); - for(int i = 0; i < sz; ++i) - { - l.Add(readString()); - } - } - - public void readStringSeq(out LinkedList<string> l) - { - // - // Reading into an array and copy-constructing the - // list is slower than constructing the list - // and adding to it one element at a time. - // - int sz = readAndCheckSeqSize(1); - l = new LinkedList<string>(); - for(int i = 0; i < sz; ++i) - { - l.AddLast(readString()); - } - } - - public void readStringSeq(out Queue<string> l) - { - // - // Reading into an array and copy-constructing the - // queue is slower than constructing the queue - // and adding to it one element at a time. - // - int sz = readAndCheckSeqSize(1); - l = new Queue<string>(); - for(int i = 0; i < sz; ++i) - { - l.Enqueue(readString()); - } - } - - public void readStringSeq(out Stack<string> l) - { - // - // Reverse the contents by copying into an array first - // because the stack is marshaled in top-to-bottom order. - // - string[] array = readStringSeq(); - Array.Reverse(array); - l = new Stack<string>(array); - } - - public Ice.Optional<string[]> readStringSeq(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.FSize)) - { - skip(4); - return new Ice.Optional<string[]>(readStringSeq()); - } - else - { - return new Ice.Optional<string[]>(); - } - } - - public void readStringSeq(int tag, out bool isset, out string[] v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.FSize)) - { - skip(4); - v = readStringSeq(); - } - else - { - v = null; - } - } - - public void writeProxy(Ice.ObjectPrx v) - { - instance_.proxyFactory().proxyToStream(v, this); - } - - public void writeProxy(int tag, Ice.Optional<Ice.ObjectPrx> v) - { - if(v.HasValue) - { - writeProxy(tag, v.Value); - } - } - - public void writeProxy(int tag, Ice.ObjectPrx v) - { - if(writeOpt(tag, Ice.OptionalFormat.FSize)) - { - int pos = startSize(); - writeProxy(v); - endSize(pos); - } - } - - public Ice.ObjectPrx readProxy() - { - return instance_.proxyFactory().streamToProxy(this); - } - - public Ice.Optional<Ice.ObjectPrx> readProxy(int tag) - { - if(readOpt(tag, Ice.OptionalFormat.FSize)) - { - skip(4); - return new Ice.Optional<Ice.ObjectPrx>(readProxy()); - } - else - { - return new Ice.Optional<Ice.ObjectPrx>(); - } - } - - public void readProxy(int tag, out bool isset, out Ice.ObjectPrx v) - { - if(isset = readOpt(tag, Ice.OptionalFormat.FSize)) - { - skip(4); - v = readProxy(); - } - else - { - v = null; - } - } - - public void writeEnum(int v, int maxValue) - { - if(isWriteEncoding_1_0()) - { - if(maxValue < 127) - { - writeByte((byte)v); - } - else if(maxValue < 32767) - { - writeShort((short)v); - } - else - { - writeInt(v); - } - } - else - { - writeSize(v); - } - } - - public void writeEnum(int tag, int v, int maxValue) - { - if(writeOpt(tag, Ice.OptionalFormat.Size)) - { - writeEnum(v, maxValue); - } - } - - public int readEnum(int maxValue) - { - if(getReadEncoding().Equals(Ice.Util.Encoding_1_0)) - { - if(maxValue < 127) - { - return readByte(); - } - else if(maxValue < 32767) - { - return readShort(); - } - else - { - return readInt(); - } - } - else - { - return readSize(); - } - } - - public void writeObject(Ice.Object v) - { - initWriteEncaps(); - _writeEncapsStack.encoder.writeObject(v); - } - - public void writeObject<T>(int tag, Ice.Optional<T> v) - where T : Ice.Object - { - if(v.HasValue) - { - writeObject(tag, v.Value); - } - } - - public void writeObject(int tag, Ice.Object v) - { - if(writeOpt(tag, Ice.OptionalFormat.Class)) - { - writeObject(v); - } - } - - public void readObject(IPatcher patcher) - { - initReadEncaps(); - _readEncapsStack.decoder.readObject(patcher); - } - - public void readObject(int tag, IPatcher patcher) - { - if(readOpt(tag, Ice.OptionalFormat.Class)) - { - readObject(patcher); - } - } - - public void writeUserException(Ice.UserException v) - { - initWriteEncaps(); - _writeEncapsStack.encoder.writeUserException(v); - } - - public void throwException(UserExceptionFactory factory) - { - initReadEncaps(); - _readEncapsStack.decoder.throwException(factory); - } - - public void sliceObjects(bool b) - { - _sliceObjects = b; - } - - public bool readOptImpl(int readTag, Ice.OptionalFormat expectedFormat) - { - if(isReadEncoding_1_0()) - { - return false; // Optional members aren't supported with the 1.0 encoding. - } - - while(true) - { - if(_buf.b.position() >= _readEncapsStack.start + _readEncapsStack.sz) - { - return false; // End of encapsulation also indicates end of optionals. - } - - int v = readByte(); - if(v == OPTIONAL_END_MARKER) - { - _buf.b.position(_buf.b.position() - 1); // Rewind. - return false; - } - - Ice.OptionalFormat format = (Ice.OptionalFormat)(v & 0x07); // First 3 bits. - int tag = v >> 3; - if(tag == 30) - { - tag = readSize(); - } - - if(tag > readTag) - { - int offset = tag < 30 ? 1 : (tag < 255 ? 2 : 6); // Rewind - _buf.b.position(_buf.b.position() - offset); - return false; // No optional data members with the requested tag. - } - else if(tag < readTag) - { - skipOpt(format); // Skip optional data members - } - else - { - if(format != expectedFormat) - { - throw new Ice.MarshalException("invalid optional data member `" + tag + "': unexpected format"); - } - return true; - } - } - } - - public bool writeOptImpl(int tag, Ice.OptionalFormat format) - { - if(isWriteEncoding_1_0()) - { - return false; // Optional members aren't supported with the 1.0 encoding. - } - - int v = (int)format; - if(tag < 30) - { - v |= tag << 3; - writeByte((byte)v); - } - else - { - v |= 0x0F0; // tag = 30 - writeByte((byte)v); - writeSize(tag); - } - return true; - } - - public void skipOpt(Ice.OptionalFormat format) - { - switch(format) - { - case Ice.OptionalFormat.F1: - { - skip(1); - break; - } - case Ice.OptionalFormat.F2: - { - skip(2); - break; - } - case Ice.OptionalFormat.F4: - { - skip(4); - break; - } - case Ice.OptionalFormat.F8: - { - skip(8); - break; - } - case Ice.OptionalFormat.Size: - { - skipSize(); - break; - } - case Ice.OptionalFormat.VSize: - { - skip(readSize()); - break; - } - case Ice.OptionalFormat.FSize: - { - skip(readInt()); - break; - } - case Ice.OptionalFormat.Class: - { - readObject(null); - break; - } - } - } - - public bool skipOpts() - { - // - // Skip remaining un-read optional members. - // - while(true) - { - if(_buf.b.position() >= _readEncapsStack.start + _readEncapsStack.sz) - { - return false; // End of encapsulation also indicates end of optionals. - } - - int v = readByte(); - if(v == OPTIONAL_END_MARKER) - { - return true; - } - - Ice.OptionalFormat format = (Ice.OptionalFormat)(v & 0x07); // Read first 3 bits. - if((v >> 3) == 30) - { - skipSize(); - } - skipOpt(format); - } - } - - public void skip(int size) - { - if(size > _buf.b.remaining()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - _buf.b.position(_buf.b.position() + size); - } - - public void skipSize() - { - byte b = readByte(); - if(b == 255) - { - skip(4); - } - } - - public int pos() - { - return _buf.b.position(); - } - - public void pos(int n) - { - _buf.b.position(n); - } - - public int size() - { - return _buf.size(); - } - -#if !MANAGED && !COMPACT && !SILVERLIGHT - static string getBZ2Error(int error) - { - string rc; - - switch(error) - { - case BZ_SEQUENCE_ERROR: - { - rc = "BZ_SEQUENCE_ERROR"; - break; - } - case BZ_PARAM_ERROR: - { - rc = "BZ_PARAM_ERROR"; - break; - } - case BZ_MEM_ERROR: - { - rc = "BZ_MEM_ERROR"; - break; - } - case BZ_DATA_ERROR: - { - rc = "BZ_DATA_ERROR"; - break; - } - case BZ_DATA_ERROR_MAGIC: - { - rc = "BZ_DATA_ERROR_MAGIC"; - break; - } - case BZ_IO_ERROR: - { - rc = "BZ_IO_ERROR"; - break; - } - case BZ_UNEXPECTED_EOF: - { - rc = "BZ_UNEXPECTED_EOF"; - break; - } - case BZ_OUTBUFF_FULL: - { - rc = "BZ_OUTBUFF_FULL"; - break; - } - case BZ_CONFIG_ERROR: - { - rc = "BZ_CONFIG_ERROR"; - break; - } - default: - { - rc = "Unknown bzip2 error: " + error; - break; - } - } - return rc; - } -#endif - - public static bool compressible() - { - return _bzlibInstalled; - } - - public bool compress(ref BasicStream cstream, int headerSize, int compressionLevel) - { -#if MANAGED || COMPACT || SILVERLIGHT - cstream = this; - return false; -#else - if(!_bzlibInstalled) - { - cstream = this; - return false; - } - - // - // Compress the message body, but not the header. - // - int uncompressedLen = size() - headerSize; - byte[] uncompressed = _buf.b.rawBytes(headerSize, uncompressedLen); - int compressedLen = (int)(uncompressedLen * 1.01 + 600); - byte[] compressed = new byte[compressedLen]; - - int rc = NativeMethods.BZ2_bzBuffToBuffCompress(compressed, ref compressedLen, uncompressed, - uncompressedLen, compressionLevel, 0, 0); - if(rc == BZ_OUTBUFF_FULL) - { - cstream = null; - return false; - } - else if(rc < 0) - { - Ice.CompressionException ex = new Ice.CompressionException("BZ2_bzBuffToBuffCompress failed"); - ex.reason = getBZ2Error(rc); - throw ex; - } - - // - // Don't bother if the compressed data is larger than the - // uncompressed data. - // - if(compressedLen >= uncompressedLen) - { - return false; - } - - cstream = new BasicStream(instance_, _encoding); - cstream.resize(headerSize + 4 + compressedLen, false); - cstream.pos(0); - - // - // Copy the header from the uncompressed stream to the - // compressed one. - // - cstream._buf.b.put(_buf.b.rawBytes(0, headerSize)); - - // - // Add the size of the uncompressed stream before the - // message body. - // - cstream.writeInt(size()); - - // - // Add the compressed message body. - // - cstream._buf.b.put(compressed, 0, compressedLen); - - return true; -#endif - } - - public BasicStream uncompress(int headerSize, int messageSizeMax) - { -#if MANAGED || COMPACT || SILVERLIGHT - return this; -#else - if(!_bzlibInstalled) - { - return this; - } - - pos(headerSize); - int uncompressedSize = readInt(); - if(uncompressedSize <= headerSize) - { - throw new Ice.IllegalMessageSizeException("compressed size <= header size"); - } - if(uncompressedSize > messageSizeMax) - { - IceInternal.Ex.throwMemoryLimitException(uncompressedSize, messageSizeMax); - } - - int compressedLen = size() - headerSize - 4; - byte[] compressed = _buf.b.rawBytes(headerSize + 4, compressedLen); - int uncompressedLen = uncompressedSize - headerSize; - byte[] uncompressed = new byte[uncompressedLen]; - int rc = NativeMethods.BZ2_bzBuffToBuffDecompress(uncompressed, ref uncompressedLen, compressed, - compressedLen, 0, 0); - if(rc < 0) - { - Ice.CompressionException ex = new Ice.CompressionException("BZ2_bzBuffToBuffDecompress failed"); - ex.reason = getBZ2Error(rc); - throw ex; - } - BasicStream ucStream = new BasicStream(instance_, _encoding); - ucStream.resize(uncompressedSize, false); - ucStream.pos(0); - ucStream._buf.b.put(_buf.b.rawBytes(0, headerSize)); - ucStream._buf.b.put(uncompressed, 0, uncompressedLen); - return ucStream; -#endif - } - - public bool isEmpty() - { - return _buf.empty(); - } - - public void expand(int n) - { - _buf.expand(n); - } - - private Ice.Object createObject(string id) - { - Ice.Object obj = null; - - try - { - Type c = AssemblyUtil.findType(instance_, typeToClass(id)); - // - // Ensure the class is instantiable. - // - if(c != null && !c.IsAbstract && !c.IsInterface) - { - obj = (Ice.Object)AssemblyUtil.createInstance(c); - } - } - catch(Exception ex) - { - Ice.NoObjectFactoryException e = new Ice.NoObjectFactoryException(ex); - e.type = id; - throw e; - } - - return obj; - } - - private string getTypeId(int compactId) - { - String className = "IceCompactId.TypeId_" + compactId; - try - { - Type c = AssemblyUtil.findType(instance_, className); - if(c != null) - { - return (string)c.GetField("typeId").GetValue(null); - } - } - catch(Exception) - { - } - return ""; - } - - private sealed class DynamicUserExceptionFactory : UserExceptionFactory - { - internal DynamicUserExceptionFactory(Type c) - { - _class = c; - } - - public void createAndThrow(string typeId) - { - try - { - throw (Ice.UserException)AssemblyUtil.createInstance(_class); - } - catch(Ice.UserException) - { - throw; - } - catch(Exception ex) - { - throw new Ice.SyscallException(ex); - } - } - - public void destroy() - { - } - - private Type _class; - } - - private Ice.UserException createUserException(string id) - { - Ice.UserException userEx = null; - - try - { - Type c = AssemblyUtil.findType(instance_, typeToClass(id)); - if(c != null) - { - // - // Ensure the class is instantiable. - // - Debug.Assert(!c.IsAbstract && !c.IsInterface); - userEx = (Ice.UserException)AssemblyUtil.createInstance(c); - } - } - catch(Exception ex) - { - throw new Ice.MarshalException(ex); - } - - return userEx; - } - - private static string typeToClass(string id) - { - if(!id.StartsWith("::", StringComparison.Ordinal)) - { - throw new Ice.MarshalException("expected type id but received `" + id + "'"); - } - return id.Substring(2).Replace("::", "."); - } - - // - // Optional data member type. - // - internal const int MemberFormatF1 = 0; - internal const int MemberFormatF2 = 1; - internal const int MemberFormatF4 = 2; - internal const int MemberFormatF8 = 3; - internal const int MemberFormatVSize = 4; - internal const int MemberFormatFSize = 5; - internal const int MemberFormatReserved = 6; - internal const int MemberFormatEndMarker = 7; - - private Instance instance_; - private Buffer _buf; - private object _closure; - private byte[] _stringBytes; // Reusable array for reading strings. - - private enum SliceType { NoSlice, ObjectSlice, ExceptionSlice } - - abstract private class EncapsDecoder - { - internal EncapsDecoder(BasicStream stream, ReadEncaps encaps, bool sliceObjects, ObjectFactoryManager f) - { - _stream = stream; - _encaps = encaps; - _sliceObjects = sliceObjects; - _servantFactoryManager = f; - _typeIdIndex = 0; - _unmarshaledMap = new Dictionary<int, Ice.Object>(); - } - - internal abstract void readObject(IPatcher patcher); - internal abstract void throwException(UserExceptionFactory factory); - - internal abstract void startInstance(SliceType type); - internal abstract Ice.SlicedData endInstance(bool preserve); - internal abstract string startSlice(); - internal abstract void endSlice(); - internal abstract void skipSlice(); - - internal virtual bool readOpt(int tag, Ice.OptionalFormat format) - { - return false; - } - - internal virtual void readPendingObjects() - { - } - - protected string readTypeId(bool isIndex) - { - if(_typeIdMap == null) - { - _typeIdMap = new Dictionary<int, string>(); - } - - if(isIndex) - { - int index = _stream.readSize(); - string typeId; - if(!_typeIdMap.TryGetValue(index, out typeId)) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - return typeId; - } - else - { - string typeId = _stream.readString(); - _typeIdMap.Add(++_typeIdIndex, typeId); - return typeId; - } - } - - protected Ice.Object newInstance(string typeId) - { - // - // Try to find a factory registered for the specific type. - // - Ice.ObjectFactory userFactory = _servantFactoryManager.find(typeId); - Ice.Object v = null; - if(userFactory != null) - { - v = userFactory.create(typeId); - } - - // - // If that fails, invoke the default factory if one has been - // registered. - // - if(v == null) - { - userFactory = _servantFactoryManager.find(""); - if(userFactory != null) - { - v = userFactory.create(typeId); - } - } - - // - // Last chance: try to instantiate the class dynamically. - // - if(v == null) - { - v = _stream.createObject(typeId); - } - - return v; - } - - protected void addPatchEntry(int index, IPatcher patcher) - { - Debug.Assert(index > 0); - - // - // Check if already un-marshalled the object. If that's the case, - // just patch the object smart pointer and we're done. - // - Ice.Object obj; - if(_unmarshaledMap.TryGetValue(index, out obj)) - { - patcher.patch(obj); - return; - } - - if(_patchMap == null) - { - _patchMap = new Dictionary<int, LinkedList<IPatcher>>(); - } - - // - // Add patch entry if the object isn't un-marshalled yet, - // the smart pointer will be patched when the instance is - // un-marshalled. - // - LinkedList<IPatcher> l; - if(!_patchMap.TryGetValue(index, out l)) - { - // - // We have no outstanding instances to be patched for this - // index, so make a new entry in the patch map. - // - l = new LinkedList<IPatcher>(); - _patchMap.Add(index, l); - } - - // - // Append a patch entry for this instance. - // - l.AddLast(patcher); - } - - protected void unmarshal(int index, Ice.Object v) - { - // - // Add the object to the map of un-marshalled objects, this must - // be done before reading the objects (for circular references). - // - _unmarshaledMap.Add(index, v); - - // - // Read the object. - // - v.read__(_stream); - - if(_patchMap != null) - { - // - // Patch all instances now that the object is un-marshalled. - // - LinkedList<IPatcher> l; - if(_patchMap.TryGetValue(index, out l)) - { - Debug.Assert(l.Count > 0); - - // - // Patch all pointers that refer to the instance. - // - foreach(IPatcher p in l) - { - p.patch(v); - } - - // - // Clear out the patch map for that index -- there is nothing left - // to patch for that index for the time being. - // - _patchMap.Remove(index); - } - } - - if((_patchMap == null || _patchMap.Count == 0) && _objectList == null) - { - try - { - v.ice_postUnmarshal(); - } - catch(System.Exception ex) - { - string s = "exception raised by ice_postUnmarshal:\n" + ex; - _stream.instance().initializationData().logger.warning(s); - } - } - else - { - if(_objectList == null) - { - _objectList = new List<Ice.Object>(); - } - _objectList.Add(v); - - if(_patchMap == null || _patchMap.Count == 0) - { - // - // Iterate over the object list and invoke ice_postUnmarshal on - // each object. We must do this after all objects have been - // unmarshaled in order to ensure that any object data members - // have been properly patched. - // - foreach(Ice.Object p in _objectList) - { - try - { - p.ice_postUnmarshal(); - } - catch(System.Exception ex) - { - string s = "exception raised by ice_postUnmarshal:\n" + ex; - _stream.instance().initializationData().logger.warning(s); - } - } - _objectList.Clear(); - } - } - } - - protected readonly BasicStream _stream; - protected readonly ReadEncaps _encaps; - protected readonly bool _sliceObjects; - protected ObjectFactoryManager _servantFactoryManager; - - // Encapsulation attributes for object un-marshalling - protected Dictionary<int, LinkedList<IPatcher> > _patchMap; - - // Encapsulation attributes for object un-marshalling - private Dictionary<int, Ice.Object> _unmarshaledMap; - private Dictionary<int, string> _typeIdMap; - private int _typeIdIndex; - private List<Ice.Object> _objectList; - }; - - private sealed class EncapsDecoder10 : EncapsDecoder - { - internal EncapsDecoder10(BasicStream stream, ReadEncaps encaps, bool sliceObjects, ObjectFactoryManager f) - : base(stream, encaps, sliceObjects, f) - { - _sliceType = SliceType.NoSlice; - } - - internal override void readObject(IPatcher patcher) - { - Debug.Assert(patcher != null); - - // - // Object references are encoded as a negative integer in 1.0. - // - int index = _stream.readInt(); - if(index > 0) - { - throw new Ice.MarshalException("invalid object id"); - } - index = -index; - - if(index == 0) - { - patcher.patch(null); - } - else - { - addPatchEntry(index, patcher); - } - } - - internal override void throwException(UserExceptionFactory factory) - { - Debug.Assert(_sliceType == SliceType.NoSlice); - - // - // User exception with the 1.0 encoding start with a bool flag - // that indicates whether or not the exception has classes. - // - // This allows reading the pending objects even if some part of - // the exception was sliced. - // - bool usesClasses = _stream.readBool(); - - _sliceType = SliceType.ExceptionSlice; - _skipFirstSlice = false; - - // - // Read the first slice header. - // - startSlice(); - string mostDerivedId = _typeId; - while(true) - { - Ice.UserException userEx = null; - - // - // Use a factory if one was provided. - // - if(factory != null) - { - try - { - factory.createAndThrow(_typeId); - } - catch(Ice.UserException ex) - { - userEx = ex; - } - } - - if(userEx == null) - { - userEx = _stream.createUserException(_typeId); - } - - // - // We found the exception. - // - if(userEx != null) - { - userEx.read__(_stream); - if(usesClasses) - { - readPendingObjects(); - } - throw userEx; - - // Never reached. - } - - // - // Slice off what we don't understand. - // - skipSlice(); - try - { - startSlice(); - } - catch(Ice.UnmarshalOutOfBoundsException ex) - { - // - // An oversight in the 1.0 encoding means there is no marker to indicate - // the last slice of an exception. As a result, we just try to read the - // next type ID, which raises UnmarshalOutOfBoundsException when the - // input buffer underflows. - // - // Set the reason member to a more helpful message. - // - ex.reason = "unknown exception type `" + mostDerivedId + "'"; - throw ex; - } - } - } - - internal override void startInstance(SliceType sliceType) - { - Debug.Assert(_sliceType == sliceType); - _skipFirstSlice = true; - } - - internal override Ice.SlicedData endInstance(bool preserve) - { - // - // Read the Ice::Object slice. - // - if(_sliceType == SliceType.ObjectSlice) - { - startSlice(); - int sz = _stream.readSize(); // For compatibility with the old AFM. - if(sz != 0) - { - throw new Ice.MarshalException("invalid Object slice"); - } - endSlice(); - } - - _sliceType = SliceType.NoSlice; - return null; - } - - internal override string startSlice() - { - // - // If first slice, don't read the header, it was already read in - // readInstance or throwException to find the factory. - // - if(_skipFirstSlice) - { - _skipFirstSlice = false; - return _typeId; - } - - // - // For objects, first read the type ID bool which indicates - // whether or not the type ID is encoded as a string or as an - // index. For exceptions, the type ID is always encoded as a - // string. - // - if(_sliceType == SliceType.ObjectSlice) // For exceptions, the type ID is always encoded as a string - { - bool isIndex = _stream.readBool(); - _typeId = readTypeId(isIndex); - } - else - { - _typeId = _stream.readString(); - } - - _sliceSize = _stream.readInt(); - if(_sliceSize < 4) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - return _typeId; - } - - internal override void endSlice() - { - } - - internal override void skipSlice() - { - if(_stream.instance().traceLevels().slicing > 0) - { - Ice.Logger logger = _stream.instance().initializationData().logger; - string slicingCat = _stream.instance().traceLevels().slicingCat; - if(_sliceType == SliceType.ObjectSlice) - { - TraceUtil.traceSlicing("object", _typeId, slicingCat, logger); - } - else - { - TraceUtil.traceSlicing("exception", _typeId, slicingCat, logger); - } - } - - Debug.Assert(_sliceSize >= 4); - _stream.skip(_sliceSize - 4); - } - - internal override void readPendingObjects() - { - int num; - do - { - num = _stream.readSize(); - for(int k = num; k > 0; --k) - { - readInstance(); - } - } - while(num > 0); - - if(_patchMap != null && _patchMap.Count > 0) - { - // - // If any entries remain in the patch map, the sender has sent an index for an object, but failed - // to supply the object. - // - throw new Ice.MarshalException("index for class received, but no instance"); - } - } - - private void readInstance() - { - int index = _stream.readInt(); - - if(index <= 0) - { - throw new Ice.MarshalException("invalid object id"); - } - - _sliceType = SliceType.ObjectSlice; - _skipFirstSlice = false; - - // - // Read the first slice header. - // - startSlice(); - string mostDerivedId = _typeId; - Ice.Object v = null; - while(true) - { - // - // For the 1.0 encoding, the type ID for the base Object class - // marks the last slice. - // - if(_typeId.Equals(Ice.ObjectImpl.ice_staticId())) - { - throw new Ice.NoObjectFactoryException("", mostDerivedId); - } - - v = newInstance(_typeId); - - // - // We found a factory, we get out of this loop. - // - if(v != null) - { - break; - } - - // - // If object slicing is disabled, stop un-marshalling. - // - if(!_sliceObjects) - { - throw new Ice.NoObjectFactoryException("no object factory found and object slicing is disabled", - _typeId); - } - - // - // Slice off what we don't understand. - // - skipSlice(); - startSlice(); // Read next Slice header for next iteration. - } - - // - // Un-marshal the object and add-it to the map of un-marshaled objects. - // - unmarshal(index, v); - } - - // Object/exception attributes - private SliceType _sliceType; - private bool _skipFirstSlice; - - // Slice attributes - private int _sliceSize; - private string _typeId; - } - - private sealed class EncapsDecoder11 : EncapsDecoder - { - internal EncapsDecoder11(BasicStream stream, ReadEncaps encaps, bool sliceObjects, ObjectFactoryManager f) - : base(stream, encaps, sliceObjects, f) - { - _objectIdIndex = 1; - _current = null; - } - - internal override void readObject(IPatcher patcher) - { - int index = _stream.readSize(); - if(index < 0) - { - throw new Ice.MarshalException("invalid object id"); - } - else if(index == 0) - { - if(patcher != null) - { - patcher.patch(null); - } - } - else if(_current != null && (_current.sliceFlags & FLAG_HAS_INDIRECTION_TABLE) != 0) - { - // - // When reading an object within a slice and there's an - // indirect object table, always read an indirect reference - // that points to an object from the indirect object table - // marshaled at the end of the Slice. - // - // Maintain a list of indirect references. Note that the - // indirect index starts at 1, so we decrement it by one to - // derive an index into the indirection table that we'll read - // at the end of the slice. - // - if(patcher != null) - { - if(_current.indirectPatchList == null) - { - _current.indirectPatchList = new Stack<IndirectPatchEntry>(); - } - IndirectPatchEntry e = new IndirectPatchEntry(); - e.index = index - 1; - e.patcher = patcher; - _current.indirectPatchList.Push(e); - } - } - else - { - readInstance(index, patcher); - } - } - - internal override void throwException(UserExceptionFactory factory) - { - Debug.Assert(_current == null); - - push(SliceType.ExceptionSlice); - - // - // Read the first slice header. - // - startSlice(); - string mostDerivedId = _current.typeId; - while(true) - { - Ice.UserException userEx = null; - - // - // Use a factory if one was provided. - // - if(factory != null) - { - try - { - factory.createAndThrow(_current.typeId); - } - catch(Ice.UserException ex) - { - userEx = ex; - } - } - - if(userEx == null) - { - userEx = _stream.createUserException(_current.typeId); - } - - // - // We found the exception. - // - if(userEx != null) - { - userEx.read__(_stream); - throw userEx; - - // Never reached. - } - - // - // Slice off what we don't understand. - // - skipSlice(); - - if((_current.sliceFlags & FLAG_IS_LAST_SLICE) != 0) - { - if(mostDerivedId.StartsWith("::", StringComparison.Ordinal)) - { - throw new Ice.UnknownUserException(mostDerivedId.Substring(2)); - } - else - { - throw new Ice.UnknownUserException(mostDerivedId); - } - } - - startSlice(); - } - } - - internal override void startInstance(SliceType sliceType) - { - Debug.Assert(_current.sliceType == sliceType); - _current.skipFirstSlice = true; - } - - internal override Ice.SlicedData endInstance(bool preserve) - { - Ice.SlicedData slicedData = null; - if(preserve) - { - slicedData = readSlicedData(); - } - if(_current.slices != null) - { - _current.slices.Clear(); - _current.indirectionTables.Clear(); - } - _current = _current.previous; - return slicedData; - } - - internal override string startSlice() - { - // - // If first slice, don't read the header, it was already read in - // readInstance or throwException to find the factory. - // - if(_current.skipFirstSlice) - { - _current.skipFirstSlice = false; - return _current.typeId; - } - - _current.sliceFlags = _stream.readByte(); - - // - // Read the type ID, for object slices the type ID is encoded as a - // string or as an index, for exceptions it's always encoded as a - // string. - // - if(_current.sliceType == SliceType.ObjectSlice) - { - if((_current.sliceFlags & FLAG_HAS_TYPE_ID_COMPACT) == FLAG_HAS_TYPE_ID_COMPACT) // Must - // be - // checked - // 1st! - { - _current.typeId = ""; - _current.compactId = _stream.readSize(); - } - else if((_current.sliceFlags & (FLAG_HAS_TYPE_ID_INDEX | FLAG_HAS_TYPE_ID_STRING)) != 0) - { - _current.typeId = readTypeId((_current.sliceFlags & FLAG_HAS_TYPE_ID_INDEX) != 0); - _current.compactId = -1; - } - else - { - // Only the most derived slice encodes the type ID for the compact format. - _current.typeId = ""; - _current.compactId = -1; - } - } - else - { - _current.typeId = _stream.readString(); - _current.compactId = -1; - } - - // - // Read the slice size if necessary. - // - if((_current.sliceFlags & FLAG_HAS_SLICE_SIZE) != 0) - { - _current.sliceSize = _stream.readInt(); - if(_current.sliceSize < 4) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - else - { - _current.sliceSize = 0; - } - - return _current.typeId; - } - - internal override void endSlice() - { - if((_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) != 0) - { - _stream.skipOpts(); - } - - // - // Read the indirection table if one is present and transform the - // indirect patch list into patch entries with direct references. - // - if((_current.sliceFlags & FLAG_HAS_INDIRECTION_TABLE) != 0) - { - // - // The table is written as a sequence<size> to conserve space. - // - int[] indirectionTable = new int[_stream.readAndCheckSeqSize(1)]; - for(int i = 0; i < indirectionTable.Length; ++i) - { - indirectionTable[i] = readInstance(_stream.readSize(), null); - } - - // - // Sanity checks. If there are optional members, it's possible - // that not all object references were read if they are from - // unknown optional data members. - // - if(indirectionTable.Length == 0) - { - throw new Ice.MarshalException("empty indirection table"); - } - if((_current.indirectPatchList == null || _current.indirectPatchList.Count == 0) && - (_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) == 0) - { - throw new Ice.MarshalException("no references to indirection table"); - } - - // - // Convert indirect references into direct references. - // - if(_current.indirectPatchList != null) - { - foreach(IndirectPatchEntry e in _current.indirectPatchList) - { - Debug.Assert(e.index >= 0); - if(e.index >= indirectionTable.Length) - { - throw new Ice.MarshalException("indirection out of range"); - } - addPatchEntry(indirectionTable[e.index], e.patcher); - } - _current.indirectPatchList.Clear(); - } - } - } - - internal override void skipSlice() - { - if(_stream.instance().traceLevels().slicing > 0) - { - Ice.Logger logger = _stream.instance().initializationData().logger; - string slicingCat = _stream.instance().traceLevels().slicingCat; - if(_current.sliceType == SliceType.ExceptionSlice) - { - TraceUtil.traceSlicing("exception", _current.typeId, slicingCat, logger); - } - else - { - TraceUtil.traceSlicing("object", _current.typeId, slicingCat, logger); - } - } - - int start = _stream.pos(); - - if((_current.sliceFlags & FLAG_HAS_SLICE_SIZE) != 0) - { - Debug.Assert(_current.sliceSize >= 4); - _stream.skip(_current.sliceSize - 4); - } - else - { - if(_current.sliceType == SliceType.ObjectSlice) - { - throw new Ice.NoObjectFactoryException("no object factory found and compact format prevents " + - "slicing (the sender should use the sliced format " + - "instead)", _current.typeId); - } - else - { - if(_current.typeId.StartsWith("::", StringComparison.Ordinal)) - { - throw new Ice.UnknownUserException(_current.typeId.Substring(2)); - } - else - { - throw new Ice.UnknownUserException(_current.typeId); - } - } - } - - // - // Preserve this slice. - // - Ice.SliceInfo info = new Ice.SliceInfo(); - info.typeId = _current.typeId; - info.compactId = _current.compactId; - info.hasOptionalMembers = (_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) != 0; - info.isLastSlice = (_current.sliceFlags & FLAG_IS_LAST_SLICE) != 0; - ByteBuffer b = _stream.getBuffer().b; - int end = b.position(); - int dataEnd = end; - if(info.hasOptionalMembers) - { - // - // Don't include the optional member end marker. It will be re-written by - // endSlice when the sliced data is re-written. - // - --dataEnd; - } - info.bytes = new byte[dataEnd - start]; - b.position(start); - b.get(info.bytes); - b.position(end); - - if(_current.slices == null) - { - _current.slices = new List<Ice.SliceInfo>(); - _current.indirectionTables = new List<int[]>(); - } - - // - // Read the indirect object table. We read the instances or their - // IDs if the instance is a reference to an already un-marhsaled - // object. - // - // The SliceInfo object sequence is initialized only if - // readSlicedData is called. - // - if((_current.sliceFlags & FLAG_HAS_INDIRECTION_TABLE) != 0) - { - int[] indirectionTable = new int[_stream.readAndCheckSeqSize(1)]; - for(int i = 0; i < indirectionTable.Length; ++i) - { - indirectionTable[i] = readInstance(_stream.readSize(), null); - } - _current.indirectionTables.Add(indirectionTable); - } - else - { - _current.indirectionTables.Add(null); - } - - _current.slices.Add(info); - } - - internal override bool readOpt(int readTag, Ice.OptionalFormat expectedFormat) - { - if(_current == null) - { - return _stream.readOptImpl(readTag, expectedFormat); - } - else if((_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) != 0) - { - return _stream.readOptImpl(readTag, expectedFormat); - } - return false; - } - - private int readInstance(int index, IPatcher patcher) - { - Debug.Assert(index > 0); - - if(index > 1) - { - if(patcher != null) - { - addPatchEntry(index, patcher); - } - return index; - } - - push(SliceType.ObjectSlice); - - // - // Get the object ID before we start reading slices. If some - // slices are skiped, the indirect object table are still read and - // might read other objects. - // - index = ++_objectIdIndex; - - // - // Read the first slice header. - // - startSlice(); - string mostDerivedId = _current.typeId; - Ice.Object v = null; - Ice.CompactIdResolver compactIdResolver = _stream.instance().initializationData().compactIdResolver; - while(true) - { - if(_current.compactId >= 0) - { - // - // Translate a compact (numeric) type ID into a string type ID. - // - _current.typeId = ""; - if(compactIdResolver != null) - { - try - { - _current.typeId = compactIdResolver(_current.compactId); - } - catch(Ice.LocalException) - { - throw; - } - catch(System.Exception ex) - { - throw new Ice.MarshalException("exception in CompactIdResolver for ID " + - _current.compactId, ex); - } - } - if(_current.typeId.Length == 0) - { - _current.typeId = _stream.getTypeId(_current.compactId); - } - } - - if(_current.typeId.Length > 0) - { - v = newInstance(_current.typeId); - - // - // We found a factory, we get out of this loop. - // - if(v != null) - { - break; - } - } - - // - // If object slicing is disabled, stop un-marshalling. - // - if(!_sliceObjects) - { - throw new Ice.NoObjectFactoryException("no object factory found and object slicing is disabled", - _current.typeId); - } - - // - // Slice off what we don't understand. - // - skipSlice(); - - // - // If this is the last slice, keep the object as an opaque - // UnknownSlicedData object. - // - if((_current.sliceFlags & FLAG_IS_LAST_SLICE) != 0) - { - // - // Provide a factory with an opportunity to supply the object. - // We pass the "::Ice::Object" ID to indicate that this is the - // last chance to preserve the object. - // - v = newInstance(Ice.ObjectImpl.ice_staticId()); - if(v == null) - { - v = new Ice.UnknownSlicedObject(mostDerivedId); - } - - break; - } - - startSlice(); // Read next Slice header for next iteration. - } - - // - // Un-marshal the object - // - unmarshal(index, v); - - if(_current == null && _patchMap != null && _patchMap.Count > 0) - { - // - // If any entries remain in the patch map, the sender has sent an index for an object, but failed - // to supply the object. - // - throw new Ice.MarshalException("index for class received, but no instance"); - } - - if(patcher != null) - { - patcher.patch(v); - } - return index; - } - - private Ice.SlicedData readSlicedData() - { - if(_current.slices == null) // No preserved slices. - { - return null; - } - - // - // The _indirectionTables member holds the indirection table for each slice - // in _slices. - // - Debug.Assert(_current.slices.Count == _current.indirectionTables.Count); - for(int n = 0; n < _current.slices.Count; ++n) - { - // - // We use the "objects" list in SliceInfo to hold references - // to the target objects. Note that the objects might not have - // been read yet in the case of a circular reference to an - // enclosing object. - // - int[] table = _current.indirectionTables[n]; - Ice.SliceInfo info = _current.slices[n]; - info.objects = new Ice.Object[table != null ? table.Length : 0]; - for(int j = 0; j < info.objects.Length; ++j) - { - IPatcher patcher = new ArrayPatcher<Ice.Object>(Ice.ObjectImpl.ice_staticId(), info.objects, j); - addPatchEntry(table[j], patcher); - } - } - - return new Ice.SlicedData(_current.slices.ToArray()); - } - - private void push(SliceType sliceType) - { - if(_current == null) - { - _current = new InstanceData(null); - } - else - { - _current = _current.next == null ? new InstanceData(_current) : _current.next; - } - _current.sliceType = sliceType; - _current.skipFirstSlice = false; - } - - private sealed class IndirectPatchEntry - { - public int index; - public IPatcher patcher; - } - - private sealed class InstanceData - { - internal InstanceData(InstanceData previous) - { - if(previous != null) - { - previous.next = this; - } - this.previous = previous; - this.next = null; - } - - // Instance attributes - internal SliceType sliceType; - internal bool skipFirstSlice; - internal List<Ice.SliceInfo> slices; // Preserved slices. - internal List<int[]> indirectionTables; - - // Slice attributes - internal byte sliceFlags; - internal int sliceSize; - internal string typeId; - internal int compactId; - internal Stack<IndirectPatchEntry> indirectPatchList; - - internal InstanceData previous; - internal InstanceData next; - }; - private InstanceData _current; - - private int _objectIdIndex; // The ID of the next object to un-marshal. - }; - - abstract private class EncapsEncoder - { - protected EncapsEncoder(BasicStream stream, WriteEncaps encaps) - { - _stream = stream; - _encaps = encaps; - _typeIdIndex = 0; - _marshaledMap = new Dictionary<Ice.Object, int>(); - } - - internal abstract void writeObject(Ice.Object v); - internal abstract void writeUserException(Ice.UserException v); - - internal abstract void startInstance(SliceType type, Ice.SlicedData data); - internal abstract void endInstance(); - internal abstract void startSlice(string typeId, int compactId, bool last); - internal abstract void endSlice(); - - internal virtual bool writeOpt(int tag, Ice.OptionalFormat format) - { - return false; - } - - internal virtual void writePendingObjects() - { - } - - protected int registerTypeId(string typeId) - { - if(_typeIdMap == null) - { - _typeIdMap = new Dictionary<string, int>(); - } - - int p; - if(_typeIdMap.TryGetValue(typeId, out p)) - { - return p; - } - else - { - _typeIdMap.Add(typeId, ++_typeIdIndex); - return -1; - } - } - - protected readonly BasicStream _stream; - protected readonly WriteEncaps _encaps; - - // Encapsulation attributes for object marshalling. - protected readonly Dictionary<Ice.Object, int> _marshaledMap; - - // Encapsulation attributes for object marshalling. - private Dictionary<string, int> _typeIdMap; - private int _typeIdIndex; - }; - - private sealed class EncapsEncoder10 : EncapsEncoder - { - internal EncapsEncoder10(BasicStream stream, WriteEncaps encaps) : base(stream, encaps) - { - _sliceType = SliceType.NoSlice; - _objectIdIndex = 0; - _toBeMarshaledMap = new Dictionary<Ice.Object, int>(); - } - - internal override void writeObject(Ice.Object v) - { - // - // Object references are encoded as a negative integer in 1.0. - // - if(v != null) - { - _stream.writeInt(-registerObject(v)); - } - else - { - _stream.writeInt(0); - } - } - - internal override void writeUserException(Ice.UserException v) - { - // - // User exception with the 1.0 encoding start with a bool - // flag that indicates whether or not the exception uses - // classes. - // - // This allows reading the pending objects even if some part of - // the exception was sliced. - // - bool usesClasses = v.usesClasses__(); - _stream.writeBool(usesClasses); - v.write__(_stream); - if(usesClasses) - { - writePendingObjects(); - } - } - - internal override void startInstance(SliceType sliceType, Ice.SlicedData sliceData) - { - _sliceType = sliceType; - } - - internal override void endInstance() - { - if(_sliceType == SliceType.ObjectSlice) - { - // - // Write the Object slice. - // - startSlice(Ice.ObjectImpl.ice_staticId(), -1, true); - _stream.writeSize(0); // For compatibility with the old AFM. - endSlice(); - } - _sliceType = SliceType.NoSlice; - } - - internal override void startSlice(string typeId, int compactId, bool last) - { - // - // For object slices, encode a bool to indicate how the type ID - // is encoded and the type ID either as a string or index. For - // exception slices, always encode the type ID as a string. - // - if(_sliceType == SliceType.ObjectSlice) - { - int index = registerTypeId(typeId); - if(index < 0) - { - _stream.writeBool(false); - _stream.writeString(typeId); - } - else - { - _stream.writeBool(true); - _stream.writeSize(index); - } - } - else - { - _stream.writeString(typeId); - } - - _stream.writeInt(0); // Placeholder for the slice length. - - _writeSlice = _stream.pos(); - } - - internal override void endSlice() - { - // - // Write the slice length. - // - int sz = _stream.pos() - _writeSlice + 4; - _stream.rewriteInt(sz, _writeSlice - 4); - } - - internal override void writePendingObjects() - { - while(_toBeMarshaledMap.Count > 0) - { - // - // Consider the to be marshalled objects as marshalled now, - // this is necessary to avoid adding again the "to be - // marshalled objects" into _toBeMarshaledMap while writing - // objects. - // - foreach(KeyValuePair<Ice.Object, int> e in _toBeMarshaledMap) - { - _marshaledMap.Add(e.Key, e.Value); - } - - Dictionary<Ice.Object, int> savedMap = _toBeMarshaledMap; - _toBeMarshaledMap = new Dictionary<Ice.Object, int>(); - _stream.writeSize(savedMap.Count); - foreach(KeyValuePair<Ice.Object, int> p in savedMap) - { - // - // Ask the instance to marshal itself. Any new class - // instances that are triggered by the classes marshaled - // are added to toBeMarshaledMap. - // - _stream.writeInt(p.Value); - - try - { - p.Key.ice_preMarshal(); - } - catch(System.Exception ex) - { - string s = "exception raised by ice_preMarshal:\n" + ex; - _stream.instance().initializationData().logger.warning(s); - } - - p.Key.write__(_stream); - } - } - _stream.writeSize(0); // Zero marker indicates end of sequence of sequences of instances. - } - - private int registerObject(Ice.Object v) - { - Debug.Assert(v != null); - - // - // Look for this instance in the to-be-marshaled map. - // - int p; - if(_toBeMarshaledMap.TryGetValue(v, out p)) - { - return p; - } - - // - // Didn't find it, try the marshaled map next. - // - if(_marshaledMap.TryGetValue(v, out p)) - { - return p; - } - - // - // We haven't seen this instance previously, create a new - // index, and insert it into the to-be-marshaled map. - // - _toBeMarshaledMap.Add(v, ++_objectIdIndex); - return _objectIdIndex; - } - - // Instance attributes - private SliceType _sliceType; - - // Slice attributes - private int _writeSlice; // Position of the slice data members - - // Encapsulation attributes for object marshalling. - private int _objectIdIndex; - private Dictionary<Ice.Object, int> _toBeMarshaledMap; - }; - - private sealed class EncapsEncoder11 : EncapsEncoder - { - internal EncapsEncoder11(BasicStream stream, WriteEncaps encaps) : base(stream, encaps) - { - _current = null; - _objectIdIndex = 1; - } - - internal override void writeObject(Ice.Object v) - { - if(v == null) - { - _stream.writeSize(0); - } - else if(_current != null && _encaps.format == Ice.FormatType.SlicedFormat) - { - if(_current.indirectionTable == null) - { - _current.indirectionTable = new List<Ice.Object>(); - _current.indirectionMap = new Dictionary<Ice.Object, int>(); - } - - // - // If writting an object within a slice and using the sliced - // format, write an index from the object indirection table. - // - int index; - if(!_current.indirectionMap.TryGetValue(v, out index)) - { - _current.indirectionTable.Add(v); - int idx = _current.indirectionTable.Count; // Position + 1 (0 is reserved for nil) - _current.indirectionMap.Add(v, idx); - _stream.writeSize(idx); - } - else - { - _stream.writeSize(index); - } - } - else - { - writeInstance(v); // Write the instance or a reference if already marshaled. - } - } - - internal override void writeUserException(Ice.UserException v) - { - v.write__(_stream); - } - - internal override void startInstance(SliceType sliceType, Ice.SlicedData data) - { - if(_current == null) - { - _current = new InstanceData(null); - } - else - { - _current = _current.next == null ? new InstanceData(_current) : _current.next; - } - _current.sliceType = sliceType; - _current.firstSlice = true; - - if(data != null) - { - writeSlicedData(data); - } - } - - internal override void endInstance() - { - _current = _current.previous; - } - - internal override void startSlice(string typeId, int compactId, bool last) - { - Debug.Assert((_current.indirectionTable == null || _current.indirectionTable.Count == 0) && - (_current.indirectionMap == null || _current.indirectionMap.Count == 0)); - - _current.sliceFlagsPos = _stream.pos(); - - _current.sliceFlags = (byte)0; - if(_encaps.format == Ice.FormatType.SlicedFormat) - { - _current.sliceFlags |= FLAG_HAS_SLICE_SIZE; // Encode the slice size if using the sliced format. - } - if(last) - { - _current.sliceFlags |= FLAG_IS_LAST_SLICE; // This is the last slice. - } - - _stream.writeByte((byte)0); // Placeholder for the slice flags - - // - // For object slices, encode the flag and the type ID either as a - // string or index. For exception slices, always encode the type - // ID a string. - // - if(_current.sliceType == SliceType.ObjectSlice) - { - // - // Encode the type ID (only in the first slice for the compact - // encoding). - // - if(_encaps.format == Ice.FormatType.SlicedFormat || _current.firstSlice) - { - if(compactId >= 0) - { - _current.sliceFlags |= FLAG_HAS_TYPE_ID_COMPACT; - _stream.writeSize(compactId); - } - else - { - int index = registerTypeId(typeId); - if(index < 0) - { - _current.sliceFlags |= FLAG_HAS_TYPE_ID_STRING; - _stream.writeString(typeId); - } - else - { - _current.sliceFlags |= FLAG_HAS_TYPE_ID_INDEX; - _stream.writeSize(index); - } - } - } - } - else - { - _stream.writeString(typeId); - } - - if((_current.sliceFlags & FLAG_HAS_SLICE_SIZE) != 0) - { - _stream.writeInt(0); // Placeholder for the slice length. - } - - _current.writeSlice = _stream.pos(); - _current.firstSlice = false; - } - - internal override void endSlice() - { - // - // Write the optional member end marker if some optional members - // were encoded. Note that the optional members are encoded before - // the indirection table and are included in the slice size. - // - if((_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) != 0) - { - _stream.writeByte((byte)OPTIONAL_END_MARKER); - } - - // - // Write the slice length if necessary. - // - if((_current.sliceFlags & FLAG_HAS_SLICE_SIZE) != 0) - { - int sz = _stream.pos() - _current.writeSlice + 4; - _stream.rewriteInt(sz, _current.writeSlice - 4); - } - - // - // Only write the indirection table if it contains entries. - // - if(_current.indirectionTable != null && _current.indirectionTable.Count > 0) - { - Debug.Assert(_encaps.format == Ice.FormatType.SlicedFormat); - _current.sliceFlags |= FLAG_HAS_INDIRECTION_TABLE; - - // - // Write the indirection object table. - // - _stream.writeSize(_current.indirectionTable.Count); - foreach(Ice.Object v in _current.indirectionTable) - { - writeInstance(v); - } - _current.indirectionTable.Clear(); - _current.indirectionMap.Clear(); - } - - // - // Finally, update the slice flags. - // - _stream.rewriteByte(_current.sliceFlags, _current.sliceFlagsPos); - } - - internal override bool writeOpt(int tag, Ice.OptionalFormat format) - { - if(_current == null) - { - return _stream.writeOptImpl(tag, format); - } - else - { - if(_stream.writeOptImpl(tag, format)) - { - _current.sliceFlags |= FLAG_HAS_OPTIONAL_MEMBERS; - return true; - } - else - { - return false; - } - } - } - - private void writeSlicedData(Ice.SlicedData slicedData) - { - Debug.Assert(slicedData != null); - - // - // We only remarshal preserved slices if we are using the sliced - // format. Otherwise, we ignore the preserved slices, which - // essentially "slices" the object into the most-derived type - // known by the sender. - // - if(_encaps.format != Ice.FormatType.SlicedFormat) - { - return; - } - - foreach(Ice.SliceInfo info in slicedData.slices) - { - startSlice(info.typeId, info.compactId, info.isLastSlice); - - // - // Write the bytes associated with this slice. - // - _stream.writeBlob(info.bytes); - - if(info.hasOptionalMembers) - { - _current.sliceFlags |= FLAG_HAS_OPTIONAL_MEMBERS; - } - - // - // Make sure to also re-write the object indirection table. - // - if(info.objects != null && info.objects.Length > 0) - { - if(_current.indirectionTable == null) - { - _current.indirectionTable = new List<Ice.Object>(); - _current.indirectionMap = new Dictionary<Ice.Object, int>(); - } - foreach(Ice.Object o in info.objects) - { - _current.indirectionTable.Add(o); - } - } - - endSlice(); - } - } - - private void writeInstance(Ice.Object v) - { - Debug.Assert(v != null); - - // - // If the instance was already marshaled, just write it's ID. - // - int p; - if(_marshaledMap.TryGetValue(v, out p)) - { - _stream.writeSize(p); - return; - } - - // - // We haven't seen this instance previously, create a new ID, - // insert it into the marshaled map, and write the instance. - // - _marshaledMap.Add(v, ++_objectIdIndex); - - try - { - v.ice_preMarshal(); - } - catch(System.Exception ex) - { - string s = "exception raised by ice_preMarshal:\n" + ex; - _stream.instance().initializationData().logger.warning(s); - } - - _stream.writeSize(1); // Object instance marker. - v.write__(_stream); - } - - private sealed class InstanceData - { - internal InstanceData(InstanceData previous) - { - if(previous != null) - { - previous.next = this; - } - this.previous = previous; - this.next = null; - } - - // Instance attributes - internal SliceType sliceType; - internal bool firstSlice; - - // Slice attributes - internal byte sliceFlags; - internal int writeSlice; // Position of the slice data members - internal int sliceFlagsPos; // Position of the slice flags - internal List<Ice.Object> indirectionTable; - internal Dictionary<Ice.Object, int> indirectionMap; - - internal InstanceData previous; - internal InstanceData next; - }; - private InstanceData _current; - - private int _objectIdIndex; // The ID of the next object to marhsal - }; - - private sealed class ReadEncaps - { - internal void reset() - { - decoder = null; - } - - internal void setEncoding(Ice.EncodingVersion encoding) - { - this.encoding = encoding; - encoding_1_0 = encoding.Equals(Ice.Util.Encoding_1_0); - } - - internal int start; - internal int sz; - internal Ice.EncodingVersion encoding; - internal bool encoding_1_0; - - internal EncapsDecoder decoder; - - internal ReadEncaps next; - } - - private sealed class WriteEncaps - { - internal void reset() - { - encoder = null; - } - - internal void setEncoding(Ice.EncodingVersion encoding) - { - this.encoding = encoding; - encoding_1_0 = encoding.Equals(Ice.Util.Encoding_1_0); - } - - internal int start; - internal Ice.EncodingVersion encoding; - internal bool encoding_1_0; - internal Ice.FormatType format = Ice.FormatType.DefaultFormat; - - internal EncapsEncoder encoder; - - internal WriteEncaps next; - } - - // - // The encoding version to use when there's no encapsulation to - // read from or write to. This is for example used to read message - // headers or when the user is using the streaming API with no - // encapsulation. - // - private Ice.EncodingVersion _encoding; - - private bool isReadEncoding_1_0() - { - return _readEncapsStack != null ? _readEncapsStack.encoding_1_0 : _encoding.Equals(Ice.Util.Encoding_1_0); - } - - private bool isWriteEncoding_1_0() - { - return _writeEncapsStack != null ? _writeEncapsStack.encoding_1_0 : _encoding.Equals(Ice.Util.Encoding_1_0); - } - - private ReadEncaps _readEncapsStack; - private WriteEncaps _writeEncapsStack; - private ReadEncaps _readEncapsCache; - private WriteEncaps _writeEncapsCache; - - private void initReadEncaps() - { - if(_readEncapsStack == null) // Lazy initialization - { - _readEncapsStack = _readEncapsCache; - if(_readEncapsStack != null) - { - _readEncapsCache = _readEncapsCache.next; - } - else - { - _readEncapsStack = new ReadEncaps(); - } - _readEncapsStack.setEncoding(_encoding); - _readEncapsStack.sz = _buf.b.limit(); - } - - if(_readEncapsStack.decoder == null) // Lazy initialization. - { - ObjectFactoryManager factoryMgr = instance_.servantFactoryManager(); - if(_readEncapsStack.encoding_1_0) - { - _readEncapsStack.decoder = new EncapsDecoder10(this, _readEncapsStack, _sliceObjects, factoryMgr); - } - else - { - _readEncapsStack.decoder = new EncapsDecoder11(this, _readEncapsStack, _sliceObjects, factoryMgr); - }; - } - } - - private void initWriteEncaps() - { - if(_writeEncapsStack == null) // Lazy initialization - { - _writeEncapsStack = _writeEncapsCache; - if(_writeEncapsStack != null) - { - _writeEncapsCache = _writeEncapsCache.next; - } - else - { - _writeEncapsStack = new WriteEncaps(); - } - _writeEncapsStack.setEncoding(_encoding); - } - - if(_writeEncapsStack.format == Ice.FormatType.DefaultFormat) - { - _writeEncapsStack.format = instance_.defaultsAndOverrides().defaultFormat; - } - - if(_writeEncapsStack.encoder == null) // Lazy initialization. - { - if(_writeEncapsStack.encoding_1_0) - { - _writeEncapsStack.encoder = new EncapsEncoder10(this, _writeEncapsStack); - } - else - { - _writeEncapsStack.encoder = new EncapsEncoder11(this, _writeEncapsStack); - } - } - } - - private bool _sliceObjects; - - private int _startSeq; - private int _minSeqSize; - - private const byte OPTIONAL_END_MARKER = 0xFF; - - private const byte FLAG_HAS_TYPE_ID_STRING = (byte)(1<<0); - private const byte FLAG_HAS_TYPE_ID_INDEX = (byte)(1<<1); - private const byte FLAG_HAS_TYPE_ID_COMPACT = (byte)(1<<1 | 1<<0); - private const byte FLAG_HAS_OPTIONAL_MEMBERS = (byte)(1<<2); - private const byte FLAG_HAS_INDIRECTION_TABLE = (byte)(1<<3); - private const byte FLAG_HAS_SLICE_SIZE = (byte)(1<<4); - private const byte FLAG_IS_LAST_SLICE = (byte)(1<<5); - - private static bool _bzlibInstalled; - - const int BZ_SEQUENCE_ERROR = -1; - const int BZ_PARAM_ERROR = -2; - const int BZ_MEM_ERROR = -3; - const int BZ_DATA_ERROR = -4; - const int BZ_DATA_ERROR_MAGIC = -5; - const int BZ_IO_ERROR = -6; - const int BZ_UNEXPECTED_EOF = -7; - const int BZ_OUTBUFF_FULL = -8; - const int BZ_CONFIG_ERROR = -9; - } - -} diff --git a/csharp/src/Ice/BatchRequestInterceptor.cs b/csharp/src/Ice/BatchRequestInterceptor.cs index 2c906a7c002..f871725b6f6 100644 --- a/csharp/src/Ice/BatchRequestInterceptor.cs +++ b/csharp/src/Ice/BatchRequestInterceptor.cs @@ -32,8 +32,8 @@ namespace Ice /// The proxy used to invoke the batch request. /// </summary> /// <returns>The request proxy.</returns> - Ice.ObjectPrx getProxy(); - }; + ObjectPrx getProxy(); + } /// <summary> /// Base interface for listening to batch request queues. @@ -52,6 +52,6 @@ namespace Ice /// <param name="request">The batch request.</param> /// <param name="queueBatchRequestCount">The number of batch request queued.</param> /// <param name="queueBatchRequestSize">The size of the queued batch requests.</param> - void enqueue(Ice.BatchRequest request, int queueBatchRequestCount, int queueBatchRequestSize); - }; -}; + void enqueue(BatchRequest request, int queueBatchRequestCount, int queueBatchRequestSize); + } +} diff --git a/csharp/src/Ice/BatchRequestQueue.cs b/csharp/src/Ice/BatchRequestQueue.cs index 0ef8535da7f..d8ee6fa20dd 100644 --- a/csharp/src/Ice/BatchRequestQueue.cs +++ b/csharp/src/Ice/BatchRequestQueue.cs @@ -27,7 +27,7 @@ namespace IceInternal public void enqueue() { - _queue.enqueueBatchRequest(); + _queue.enqueueBatchRequest(_proxy); } public Ice.ObjectPrx getProxy() @@ -49,8 +49,7 @@ namespace IceInternal private Ice.ObjectPrx _proxy; private string _operation; private int _size; - }; - + } public sealed class BatchRequestQueue { @@ -60,7 +59,7 @@ namespace IceInternal _interceptor = initData.batchRequestInterceptor; _batchStreamInUse = false; _batchRequestNum = 0; - _batchStream = new BasicStream(instance, Ice.Util.currentProtocolEncoding); + _batchStream = new Ice.OutputStream(instance, Ice.Util.currentProtocolEncoding); _batchStream.writeBlob(Protocol.requestBatchHdr); _batchMarker = _batchStream.size(); _request = new BatchRequestI(this); @@ -78,7 +77,7 @@ namespace IceInternal } public void - prepareBatchRequest(BasicStream os) + prepareBatchRequest(Ice.OutputStream os) { lock(this) { @@ -93,7 +92,7 @@ namespace IceInternal } public void - finishBatchRequest(BasicStream os, Ice.ObjectPrx proxy, string operation) + finishBatchRequest(Ice.OutputStream os, Ice.ObjectPrx proxy, string operation) { // // No need for synchronization, no other threads are supposed @@ -119,6 +118,11 @@ namespace IceInternal } else { + bool compress; + if(((Ice.ObjectPrxHelperBase)proxy).iceReference().getCompressOverride(out compress)) + { + _batchCompress |= compress; + } _batchMarker = _batchStream.size(); ++_batchRequestNum; } @@ -127,7 +131,7 @@ namespace IceInternal { lock(this) { - _batchStream.resize(_batchMarker, false); + _batchStream.resize(_batchMarker); _batchStreamInUse = false; _batchStreamCanFlush = false; System.Threading.Monitor.PulseAll(this); @@ -136,14 +140,14 @@ namespace IceInternal } public void - abortBatchRequest(BasicStream os) + abortBatchRequest(Ice.OutputStream os) { lock(this) { if(_batchStreamInUse) { _batchStream.swap(os); - _batchStream.resize(_batchMarker, false); + _batchStream.resize(_batchMarker); _batchStreamInUse = false; System.Threading.Monitor.PulseAll(this); } @@ -151,12 +155,13 @@ namespace IceInternal } public int - swap(BasicStream os) + swap(Ice.OutputStream os, out bool compress) { lock(this) { if(_batchRequestNum == 0) { + compress = false; return 0; } @@ -169,16 +174,18 @@ namespace IceInternal Buffer buffer = _batchStream.getBuffer(); buffer.b.position(_batchMarker); buffer.b.get(lastRequest); - _batchStream.resize(_batchMarker, false); + _batchStream.resize(_batchMarker); } int requestNum = _batchRequestNum; + compress = _batchCompress; _batchStream.swap(os); // // Reset the batch. // _batchRequestNum = 0; + _batchCompress = false; _batchStream.writeBlob(Protocol.requestBatchHdr); _batchMarker = _batchStream.size(); if(lastRequest != null) @@ -222,23 +229,29 @@ namespace IceInternal } } - internal void enqueueBatchRequest() + internal void enqueueBatchRequest(Ice.ObjectPrx proxy) { Debug.Assert(_batchMarker < _batchStream.size()); + bool compress; + if(((Ice.ObjectPrxHelperBase)proxy).iceReference().getCompressOverride(out compress)) + { + _batchCompress |= compress; + } _batchMarker = _batchStream.size(); ++_batchRequestNum; } private Ice.BatchRequestInterceptor _interceptor; - private BasicStream _batchStream; + private Ice.OutputStream _batchStream; private bool _batchStreamInUse; private bool _batchStreamCanFlush; private int _batchRequestNum; private int _batchMarker; + private bool _batchCompress; private BatchRequestI _request; private Ice.LocalException _exception; private int _maxSize; private static int _udpOverhead = 20 + 8; } -}; +} diff --git a/csharp/src/Ice/Buffer.cs b/csharp/src/Ice/Buffer.cs index f3d00137b95..57571bea340 100644 --- a/csharp/src/Ice/Buffer.cs +++ b/csharp/src/Ice/Buffer.cs @@ -42,6 +42,33 @@ namespace IceInternal _order = order; } + public Buffer(ByteBuffer data) : this(data, ByteBuffer.ByteOrder.LITTLE_ENDIAN) + { + } + + public Buffer(ByteBuffer data, ByteBuffer.ByteOrder order) + { + b = data; + b.order(order); + _size = data.remaining(); + _capacity = 0; + _order = order; + } + + public Buffer(Buffer buf, bool adopt) + { + b = buf.b; + _size = buf._size; + _capacity = buf._capacity; + _shrinkCounter = buf._shrinkCounter; + _order = buf._order; + + if(adopt) + { + buf.clear(); + } + } + public int size() { return _size; @@ -57,6 +84,7 @@ namespace IceInternal b = _emptyBuffer; _size = 0; _capacity = 0; + _shrinkCounter = 0; } // diff --git a/csharp/src/Ice/ByteBuffer.cs b/csharp/src/Ice/ByteBuffer.cs index 716dd09f4c5..246954c4f50 100644 --- a/csharp/src/Ice/ByteBuffer.cs +++ b/csharp/src/Ice/ByteBuffer.cs @@ -234,7 +234,7 @@ namespace IceInternal return put(b, 0, System.Buffer.ByteLength(b)); } - public ByteBuffer put(byte[]b, int offset, int length) + public ByteBuffer put(byte[] b, int offset, int length) { if(offset < 0) { @@ -323,7 +323,7 @@ namespace IceInternal return v; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public short getShort(int pos) @@ -331,7 +331,7 @@ namespace IceInternal checkUnderflow(pos, 2); if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[pos]) { _valBytes.shortVal = *((short*)p); @@ -370,7 +370,7 @@ namespace IceInternal _position += len; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public ByteBuffer putShort(short val) @@ -379,7 +379,7 @@ namespace IceInternal _valBytes.shortVal = val; if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[_position]) { *((short*)p) = _valBytes.shortVal; @@ -420,7 +420,7 @@ namespace IceInternal return this; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public int getInt() @@ -428,7 +428,7 @@ namespace IceInternal checkUnderflow(4); if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[_position]) { _valBytes.intVal = *((int*)p); @@ -481,7 +481,7 @@ namespace IceInternal return this; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public ByteBuffer putInt(int pos, int val) @@ -497,7 +497,7 @@ namespace IceInternal _valBytes.intVal = val; if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[pos]) { *((int*)p) = _valBytes.intVal; @@ -550,7 +550,7 @@ namespace IceInternal return v; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public long getLong(int pos) @@ -558,7 +558,7 @@ namespace IceInternal checkUnderflow(pos, 8); if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[pos]) { _valBytes.longVal = *((long*)p); @@ -615,7 +615,7 @@ namespace IceInternal _position += len; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public ByteBuffer putLong(long val) @@ -624,7 +624,7 @@ namespace IceInternal _valBytes.longVal = val; if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[_position]) { *((long*)p) = _valBytes.longVal; @@ -683,7 +683,7 @@ namespace IceInternal return this; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public float getFloat() @@ -691,7 +691,7 @@ namespace IceInternal checkUnderflow(4); if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[_position]) { _valBytes.floatVal = *((float*)p); @@ -737,7 +737,7 @@ namespace IceInternal _position += len; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public ByteBuffer putFloat(float val) @@ -746,7 +746,7 @@ namespace IceInternal _valBytes.floatVal = val; if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[_position]) { *((float*)p) = _valBytes.floatVal; @@ -793,7 +793,7 @@ namespace IceInternal return this; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public double getDouble() @@ -801,7 +801,7 @@ namespace IceInternal checkUnderflow(8); if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[_position]) { _valBytes.doubleVal = *((double*)p); @@ -859,7 +859,7 @@ namespace IceInternal _position += len; } -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED unsafe #endif public ByteBuffer putDouble(double val) @@ -868,7 +868,7 @@ namespace IceInternal _valBytes.doubleVal = val; if(NO._o == _order) { -#if !MANAGED && !COMPACT && !SILVERLIGHT +#if !MANAGED fixed(byte* p = &_bytes[_position]) { *((double*)p) = _valBytes.doubleVal; @@ -989,11 +989,7 @@ namespace IceInternal private static void throwOutOfRange(string param, object value, string message) { -#if COMPACT || SILVERLIGHT - throw new ArgumentOutOfRangeException(param, message); -#else throw new ArgumentOutOfRangeException(param, value, message); -#endif } } } diff --git a/csharp/src/Ice/CollectionBase.cs b/csharp/src/Ice/CollectionBase.cs deleted file mode 100644 index 33a4f8ad61a..00000000000 --- a/csharp/src/Ice/CollectionBase.cs +++ /dev/null @@ -1,450 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -using System; -using System.Collections.Generic; - -namespace IceInternal -{ -#if !SILVERLIGHT - [Serializable] -#endif - public abstract class CollectionBase<T> : System.Collections.IList - { - protected List<T> list_; - - public CollectionBase() - { - list_ = new List<T>(); - } - - public CollectionBase(int capacity) - { - list_ = new List<T>(capacity); - } - - public CollectionBase(T[] a) - { - if(a == null) - { - throw new ArgumentNullException("a", "Cannot construct collection from null array"); - } - - list_ = new List<T>(a.Length); - list_.AddRange(a); - } - - public CollectionBase(IEnumerable<T> l) - { - if(l == null) - { - throw new ArgumentNullException("l", "Cannot construct collection from null collection"); - } - - list_ = new List<T>(); - list_.AddRange(l); - } - - public static implicit operator List<T>(CollectionBase<T> l) - { - return l.list_; - } - - - public void CopyTo(T[] a__) - { - list_.CopyTo(a__); - } - - public void CopyTo(T[] a__, int i__) - { - list_.CopyTo(a__, i__); - } - - public void CopyTo(int i__, T[] a__, int ai__, int _c_) - { - list_.CopyTo(i__, a__, ai__, _c_); - } - - public T[] ToArray() - { - return list_.ToArray(); - } - - public virtual void TrimToSize() - { - list_.TrimExcess(); - } - - public virtual void Sort() - { - list_.Sort(); - } - - public virtual void Sort(System.Collections.IComparer comparer) - { - list_.Sort(new Comparer(comparer)); - } - - public virtual void Sort(int index, int count, System.Collections.IComparer comparer) - { - list_.Sort(index, count, new Comparer(comparer)); - } - - public virtual void Reverse() - { - list_.Reverse(); - } - - public virtual void Reverse(int index, int count) - { - list_.Reverse(index, count); - } - - public virtual int BinarySearch(T value) - { - return list_.BinarySearch(value); - } - - public virtual int BinarySearch(T value, System.Collections.IComparer comparer) - { - return list_.BinarySearch(value, new Comparer(comparer)); - } - - public virtual int BinarySearch(int index, int count, T value, System.Collections.IComparer comparer) - { - return list_.BinarySearch(index, count, value, new Comparer(comparer)); - } - - public virtual void InsertRange(int index, CollectionBase<T> c) - { - list_.InsertRange(index, c.list_); - } - - public virtual void InsertRange(int index, T[] c) - { - list_.InsertRange(index, c); - } - - public virtual void RemoveRange(int index, int count) - { - list_.RemoveRange(index, count); - } - - public virtual void SetRange(int index, CollectionBase<T> c) - { - if(c == null) - { - throw new ArgumentNullException("c", "Collection must not be null for SetRange()"); - } - if(index < 0 || index + c.Count > list_.Count) - { - throw new ArgumentOutOfRangeException("index", "Index out of range"); - } - for(int i = index; i < list_.Count; ++i) - { - list_[i] = c[i - index]; - } - } - - public virtual void SetRange(int index, T[] c) - { - if(c == null) - { - throw new ArgumentNullException("c", "Collection must not be null for SetRange()"); - } - if(index < 0 || index + c.Length > list_.Count) - { - throw new ArgumentOutOfRangeException("index", "Index out of range"); - } - for(int i = index; i < list_.Count; ++i) - { - list_[i] = c[i - index]; - } - } - - public virtual int LastIndexOf(T value) - { - return list_.LastIndexOf(value); - } - - public virtual int LastIndexOf(T value, int startIndex) - { - return list_.LastIndexOf(value, startIndex); - } - - public virtual int LastIndexOf(T value, int startIndex, int count) - { - return list_.LastIndexOf(value, startIndex, count); - } - - public void AddRange(CollectionBase<T> s__) - { - list_.AddRange(s__.list_); - } - - public void AddRange(T[] a__) - { - list_.AddRange(a__); - } - - public int Capacity - { - get - { - return list_.Capacity; - } - - set - { - list_.Capacity = value; - } - } - - public int Count - { - get - { - return list_.Count; - } - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return list_.GetEnumerator(); - } - - public IEnumerator<T> GetEnumerator() - { - return list_.GetEnumerator(); - } - - public void RemoveAt(int index) - { - list_.RemoveAt(index); - } - - public int Add(T value) - { - list_.Add(value); - return list_.Count - 1; - } - - public void Clear() - { - list_.Clear(); - } - - public bool IsFixedSize - { - get - { - return false; - } - } - - public bool IsReadOnly - { - get - { - return false; - } - } - - public int IndexOf(T value) - { - return list_.IndexOf(value); - } - - public void Insert(int index, T value) - { - list_.Insert(index, value); - } - - public void Remove(T value) - { - list_.Remove(value); - } - - public bool Contains(T value) - { - return list_.Contains(value); - } - - public bool IsSynchronized - { - get - { - return false; - } - } - - public object SyncRoot - { - get - { - return this; - } - } - - public T this[int index] - { - get - { - return list_[index]; - } - set - { - list_[index] = value; - } - } - - public override int GetHashCode() - { - int h = 5381; - for(int i = 0; i < Count; ++i) - { - T v__ = list_[i]; - IceInternal.HashUtil.hashAdd(ref h, v__); - } - return h; - } - - public override bool Equals(object other) - { - if(object.ReferenceEquals(this, other)) - { - return true; - } - try - { - CollectionBase<T> c = (CollectionBase<T>)other; - if(list_.Count != c.list_.Count) - { - return false; - } - if(list_.Count == 0) - { - return true; - } - for(int i = 0; i < list_.Count; ++i) - { - if(!Equals(list_[i], c.list_[i])) - { - return false; - } - } - } - catch(System.Exception) - { - return false; - } - - return true; - } - - public static bool operator==(CollectionBase<T> lhs__, CollectionBase<T> rhs__) - { - return Equals(lhs__, rhs__); - } - - public static bool operator!=(CollectionBase<T> lhs__, CollectionBase<T> rhs__) - { - return !Equals(lhs__, rhs__); - } - - private class Comparer : IComparer<T> - { - private System.Collections.IComparer _c; - - public Comparer(System.Collections.IComparer c) - { - _c = c; - } - - public virtual int Compare(T l, T r) - { - return _c.Compare(l, r); - } - } - - public int Add(object o) - { - checkType(o); - return Add((T)o); - } - - public bool Contains(object o) - { - checkType(o); - return Contains((T)o); - } - - public int IndexOf(object o) - { - checkType(o); - return IndexOf((T)o); - } - - public void Insert(int i, object o) - { - checkType(o); - Insert(i, (T)o); - } - - public void Remove(object o) - { - checkType(o); - Remove((T)o); - } - - object System.Collections.IList.this[int index] - { - get - { - return this[index]; - } - set - { - checkType(value); - this[index] = (T)value; - } - } - - public void CopyTo(Array a, int index) - { - Type t = a.GetType().GetElementType(); - if(!t.IsAssignableFrom(typeof(T))) - { - throw new ArgumentException("a__", "Cannot assign " + typeof(T).ToString() + " to array of " - + t.ToString()); - } - CopyTo((T[])a, index); - } - - private void checkType(object o) - { - - if(o != null && !(o is T)) - { - throw new ArgumentException("Cannot use an object of type " + o.GetType().ToString() - + " with a collection of " + typeof(T).ToString()); - } - } - } - -} - -namespace Ice -{ - [Obsolete("This class is deprecated.")] - public abstract class CollectionBase<T> : IceInternal.CollectionBase<T> - { - } -} diff --git a/csharp/src/Ice/Collections.cs b/csharp/src/Ice/Collections.cs index 10e85503172..d5f6516123a 100644 --- a/csharp/src/Ice/Collections.cs +++ b/csharp/src/Ice/Collections.cs @@ -17,7 +17,7 @@ namespace IceUtilInternal { public static bool SequenceEquals(ICollection seq1, ICollection seq2) { - if(object.ReferenceEquals(seq1, seq2)) + if(ReferenceEquals(seq1, seq2)) { return true; } @@ -55,7 +55,7 @@ namespace IceUtilInternal public static bool SequenceEquals(IEnumerable seq1, IEnumerable seq2) { - if(object.ReferenceEquals(seq1, seq2)) + if(ReferenceEquals(seq1, seq2)) { return true; } @@ -107,7 +107,7 @@ namespace IceUtilInternal public static bool DictionaryEquals(IDictionary d1, IDictionary d2) { - if(object.ReferenceEquals(d1, d2)) + if(ReferenceEquals(d1, d2)) { return true; } @@ -161,11 +161,11 @@ namespace IceUtilInternal public static void Shuffle<T>(ref List<T> l) { - lock(rand_) + lock(_rand) { for(int j = 0; j < l.Count - 1; ++j) { - int r = rand_.Next(l.Count - j) + j; + int r = _rand.Next(l.Count - j) + j; Debug.Assert(r >= j && r < l.Count); if(r != j) { @@ -234,6 +234,6 @@ namespace IceUtilInternal } } - private static System.Random rand_ = new System.Random(unchecked((int)System.DateTime.Now.Ticks)); + private static System.Random _rand = new System.Random(unchecked((int)System.DateTime.Now.Ticks)); } } diff --git a/csharp/src/Ice/CollocatedRequestHandler.cs b/csharp/src/Ice/CollocatedRequestHandler.cs index aead02b25a0..86c763c77e9 100644 --- a/csharp/src/Ice/CollocatedRequestHandler.cs +++ b/csharp/src/Ice/CollocatedRequestHandler.cs @@ -19,7 +19,7 @@ namespace IceInternal public class CollocatedRequestHandler : RequestHandler, ResponseHandler { private void - fillInValue(BasicStream os, int pos, int value) + fillInValue(Ice.OutputStream os, int pos, int value) { os.rewriteInt(value, pos); } @@ -42,9 +42,9 @@ namespace IceInternal return previousHandler == this ? newHandler : this; } - public bool sendAsyncRequest(ProxyOutgoingAsyncBase outAsync, out Ice.AsyncCallback sentCallback) + public int sendAsyncRequest(ProxyOutgoingAsyncBase outAsync) { - return outAsync.invokeCollocated(this, out sentCallback); + return outAsync.invokeCollocated(this); } public void asyncRequestCanceled(OutgoingAsyncBase outAsync, Ice.LocalException ex) @@ -59,10 +59,9 @@ namespace IceInternal _asyncRequests.Remove(requestId); } _sendAsyncRequests.Remove(outAsync); - Ice.AsyncCallback cb = outAsync.completed(ex); - if(cb != null) + if(outAsync.exception(ex)) { - outAsync.invokeCompletedAsync(cb); + outAsync.invokeExceptionAsync(); } _adapter.decDirectCount(); // invokeAll won't be called, decrease the direct count. return; @@ -76,10 +75,9 @@ namespace IceInternal if(e.Value == o) { _asyncRequests.Remove(e.Key); - Ice.AsyncCallback cb = outAsync.completed(ex); - if(cb != null) + if(outAsync.exception(ex)) { - outAsync.invokeCompletedAsync(cb); + outAsync.invokeExceptionAsync(); } return; } @@ -88,39 +86,48 @@ namespace IceInternal } } - public void sendResponse(int requestId, BasicStream os, byte status, bool amd) + public void sendResponse(int requestId, Ice.OutputStream os, byte status, bool amd) { - Ice.AsyncCallback cb = null; OutgoingAsyncBase outAsync; lock(this) { Debug.Assert(_response); - os.pos(Protocol.replyHdr.Length + 4); - if(_traceLevels.protocol >= 1) { fillInValue(os, 10, os.size()); - TraceUtil.traceRecv(os, _logger, _traceLevels); + } + + // Adopt the OutputStream's buffer. + Ice.InputStream iss = new Ice.InputStream(os.instance(), os.getEncoding(), os.getBuffer(), true); + + iss.pos(Protocol.replyHdr.Length + 4); + + if(_traceLevels.protocol >= 1) + { + TraceUtil.traceRecv(iss, _logger, _traceLevels); } if(_asyncRequests.TryGetValue(requestId, out outAsync)) { + outAsync.getIs().swap(iss); + if(!outAsync.response()) + { + outAsync = null; + } _asyncRequests.Remove(requestId); - outAsync.getIs().swap(os); - cb = outAsync.completed(); } } - if(cb != null) + if(outAsync != null) { if(amd) { - outAsync.invokeCompletedAsync(cb); + outAsync.invokeResponseAsync(); } else { - outAsync.invokeCompleted(cb); + outAsync.invokeResponse(); } } _adapter.decDirectCount(); @@ -159,8 +166,7 @@ namespace IceInternal return null; } - public bool invokeAsyncRequest(OutgoingAsyncBase outAsync, int batchRequestNum, bool synchronous, - out Ice.AsyncCallback sentCallback) + public int invokeAsyncRequest(OutgoingAsyncBase outAsync, int batchRequestNum, bool synchronous) { // // Increase the direct count to prevent the thread pool from being destroyed before @@ -184,61 +190,44 @@ namespace IceInternal _sendAsyncRequests.Add(outAsync, requestId); } } - catch(System.Exception ex) + catch(Exception) { _adapter.decDirectCount(); - throw ex; + throw; } outAsync.attachCollocatedObserver(_adapter, requestId); - - if(synchronous) + if(!synchronous || !_response || _reference.getInvocationTimeout() > 0) { - // - // Treat this collocated call as if it is a synchronous invocation. - // - if(_reference.getInvocationTimeout() > 0 || !_response) - { - // Don't invoke from the user thread, invocation timeouts wouldn't work otherwise. - _adapter.getThreadPool().dispatch(() => + // Don't invoke from the user thread if async or invocation timeout is set + _adapter.getThreadPool().dispatch( + () => { - if(sentAsync(outAsync)) + if (sentAsync(outAsync)) { invokeAll(outAsync.getOs(), requestId, batchRequestNum); } }, null); - } - else if(_dispatcher) - { - _adapter.getThreadPool().dispatchFromThisThread(() => + } + else if(_dispatcher) + { + _adapter.getThreadPool().dispatchFromThisThread( + () => { - if(sentAsync(outAsync)) + if (sentAsync(outAsync)) { invokeAll(outAsync.getOs(), requestId, batchRequestNum); } }, null); - } - else // Optimization: directly call invokeAll if there's no dispatcher. - { - if(sentAsync(outAsync)) - { - invokeAll(outAsync.getOs(), requestId, batchRequestNum); - } - } - sentCallback = null; } - else + else // Optimization: directly call invokeAll if there's no dispatcher. { - _adapter.getThreadPool().dispatch(() => + if(sentAsync(outAsync)) { - if(sentAsync(outAsync)) - { - invokeAll(outAsync.getOs(), requestId, batchRequestNum); - } - }, null); - sentCallback = null; + invokeAll(outAsync.getOs(), requestId, batchRequestNum); + } } - return false; + return OutgoingAsyncBase.AsyncStatusQueued; } private bool sentAsync(OutgoingAsyncBase outAsync) @@ -249,27 +238,18 @@ namespace IceInternal { return false; // The request timed-out. } - } - Ice.AsyncCallback cb = outAsync.sent(); - if(cb != null) - { - outAsync.invokeSent(cb); + if(!outAsync.sent()) + { + return true; + } } + outAsync.invokeSent(); return true; } - private void invokeAll(BasicStream os, int requestId, int batchRequestNum) + private void invokeAll(Ice.OutputStream os, int requestId, int batchRequestNum) { - if(batchRequestNum > 0) - { - os.pos(Protocol.requestBatchHdr.Length); - } - else - { - os.pos(Protocol.requestHdr.Length); - } - if(_traceLevels.protocol >= 1) { fillInValue(os, 10, os.size()); @@ -284,6 +264,17 @@ namespace IceInternal TraceUtil.traceSend(os, _logger, _traceLevels); } + Ice.InputStream iss = new Ice.InputStream(os.instance(), os.getEncoding(), os.getBuffer(), false); + + if(batchRequestNum > 0) + { + iss.pos(Protocol.requestBatchHdr.Length); + } + else + { + iss.pos(Protocol.requestHdr.Length); + } + int invokeNum = batchRequestNum > 0 ? batchRequestNum : 1; ServantManager servantManager = _adapter.getServantManager(); try @@ -306,9 +297,9 @@ namespace IceInternal break; } - Incoming @in = new Incoming(_reference.getInstance(), this, null, _adapter, _response, (byte)0, - requestId); - @in.invoke(servantManager, os); + Incoming inS = new Incoming(_reference.getInstance(), this, null, _adapter, _response, (byte)0, + requestId); + inS.invoke(servantManager, iss); --invokeNum; } } @@ -329,25 +320,32 @@ namespace IceInternal } OutgoingAsyncBase outAsync; - Ice.AsyncCallback cb = null; lock(this) { if(_asyncRequests.TryGetValue(requestId, out outAsync)) { + if(!outAsync.exception(ex)) + { + outAsync = null; + } _asyncRequests.Remove(requestId); - cb = outAsync.completed(ex); } } - if(cb != null) + if(outAsync != null) { + // + // If called from an AMD dispatch, invoke asynchronously + // the completion callback since this might be called from + // the user code. + // if(amd) { - outAsync.invokeCompletedAsync(cb); + outAsync.invokeExceptionAsync(); } else { - outAsync.invokeCompleted(cb); + outAsync.invokeException(); } } } diff --git a/csharp/src/Ice/CommunicatorI.cs b/csharp/src/Ice/CommunicatorI.cs index 5d72f713391..be11cce72ba 100644 --- a/csharp/src/Ice/CommunicatorI.cs +++ b/csharp/src/Ice/CommunicatorI.cs @@ -9,83 +9,86 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; +using System.Threading; + +using IceInternal; namespace Ice { - sealed class CommunicatorI : Communicator { public void destroy() { - instance_.destroy(); + _instance.destroy(); } public void shutdown() { - instance_.objectAdapterFactory().shutdown(); + _instance.objectAdapterFactory().shutdown(); } public void waitForShutdown() { - instance_.objectAdapterFactory().waitForShutdown(); + _instance.objectAdapterFactory().waitForShutdown(); } public bool isShutdown() { - return instance_.objectAdapterFactory().isShutdown(); + return _instance.objectAdapterFactory().isShutdown(); } - public Ice.ObjectPrx stringToProxy(string s) + public ObjectPrx stringToProxy(string s) { - return instance_.proxyFactory().stringToProxy(s); + return _instance.proxyFactory().stringToProxy(s); } - public string proxyToString(Ice.ObjectPrx proxy) + public string proxyToString(ObjectPrx proxy) { - return instance_.proxyFactory().proxyToString(proxy); + return _instance.proxyFactory().proxyToString(proxy); } - public Ice.ObjectPrx propertyToProxy(string s) + public ObjectPrx propertyToProxy(string s) { - return instance_.proxyFactory().propertyToProxy(s); + return _instance.proxyFactory().propertyToProxy(s); } - public Dictionary<string, string> proxyToProperty(Ice.ObjectPrx proxy, string prefix) + public Dictionary<string, string> proxyToProperty(ObjectPrx proxy, string prefix) { - return instance_.proxyFactory().proxyToProperty(proxy, prefix); + return _instance.proxyFactory().proxyToProperty(proxy, prefix); } - public Ice.Identity stringToIdentity(string s) + public Identity stringToIdentity(string s) { - return instance_.stringToIdentity(s); + return Util.stringToIdentity(s); } - public string identityToString(Ice.Identity ident) + public string identityToString(Identity ident) { - return instance_.identityToString(ident); + return Util.identityToString(ident, _instance.toStringMode()); } public ObjectAdapter createObjectAdapter(string name) { - return instance_.objectAdapterFactory().createObjectAdapter(name, null); + return _instance.objectAdapterFactory().createObjectAdapter(name, null); } public ObjectAdapter createObjectAdapterWithEndpoints(string name, string endpoints) { if(name.Length == 0) { - name = System.Guid.NewGuid().ToString(); + name = Guid.NewGuid().ToString(); } getProperties().setProperty(name + ".Endpoints", endpoints); - return instance_.objectAdapterFactory().createObjectAdapter(name, null); + return _instance.objectAdapterFactory().createObjectAdapter(name, null); } public ObjectAdapter createObjectAdapterWithRouter(string name, RouterPrx router) { if(name.Length == 0) { - name = System.Guid.NewGuid().ToString(); + name = Guid.NewGuid().ToString(); } // @@ -97,142 +100,173 @@ namespace Ice getProperties().setProperty(entry.Key, entry.Value); } - return instance_.objectAdapterFactory().createObjectAdapter(name, router); + return _instance.objectAdapterFactory().createObjectAdapter(name, router); } public void addObjectFactory(ObjectFactory factory, string id) { - instance_.servantFactoryManager().add(factory, id); + _instance.addObjectFactory(factory, id); } public ObjectFactory findObjectFactory(string id) { - return instance_.servantFactoryManager().find(id); + return _instance.findObjectFactory(id); + } + + public ValueFactoryManager getValueFactoryManager() + { + return _instance.initializationData().valueFactoryManager; } public Properties getProperties() { - return instance_.initializationData().properties; + return _instance.initializationData().properties; } public Logger getLogger() { - return instance_.initializationData().logger; + return _instance.initializationData().logger; } - public Ice.Instrumentation.CommunicatorObserver getObserver() + public Instrumentation.CommunicatorObserver getObserver() { - return instance_.initializationData().observer; + return _instance.initializationData().observer; } public RouterPrx getDefaultRouter() { - return instance_.referenceFactory().getDefaultRouter(); + return _instance.referenceFactory().getDefaultRouter(); } public void setDefaultRouter(RouterPrx router) { - instance_.setDefaultRouter(router); + _instance.setDefaultRouter(router); } public LocatorPrx getDefaultLocator() { - return instance_.referenceFactory().getDefaultLocator(); + return _instance.referenceFactory().getDefaultLocator(); } public void setDefaultLocator(LocatorPrx locator) { - instance_.setDefaultLocator(locator); + _instance.setDefaultLocator(locator); } public ImplicitContext getImplicitContext() { - return instance_.getImplicitContext(); + return _instance.getImplicitContext(); } public PluginManager getPluginManager() { - return instance_.pluginManager(); + return _instance.pluginManager(); } - public void flushBatchRequests() + public void flushBatchRequests(Ice.CompressBatch compressBatch) { - AsyncResult r = begin_flushBatchRequests(); - end_flushBatchRequests(r); + flushBatchRequestsAsync(compressBatch).Wait(); } - public AsyncResult begin_flushBatchRequests() + public Task flushBatchRequestsAsync(Ice.CompressBatch compressBatch, + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()) { - return begin_flushBatchRequests(null, null); + var completed = new FlushBatchTaskCompletionCallback(progress, cancel); + var outgoing = new CommunicatorFlushBatchAsync(_instance, completed); + outgoing.invoke(_flushBatchRequests_name, compressBatch); + return completed.Task; } - private const string __flushBatchRequests_name = "flushBatchRequests"; - - public AsyncResult begin_flushBatchRequests(AsyncCallback cb, object cookie) + public AsyncResult begin_flushBatchRequests(Ice.CompressBatch compressBatch) { - IceInternal.OutgoingConnectionFactory connectionFactory = instance_.outgoingConnectionFactory(); - IceInternal.ObjectAdapterFactory adapterFactory = instance_.objectAdapterFactory(); + return begin_flushBatchRequests(compressBatch, null, null); + } - // - // This callback object receives the results of all invocations - // of Connection.begin_flushBatchRequests. - // - IceInternal.CommunicatorFlushBatch result = - new IceInternal.CommunicatorFlushBatch(this, instance_, __flushBatchRequests_name, cookie); + private const string _flushBatchRequests_name = "flushBatchRequests"; - if(cb != null) + private class CommunicatorFlushBatchCompletionCallback : AsyncResultCompletionCallback + { + public CommunicatorFlushBatchCompletionCallback(Communicator communicator, + Instance instance, + string op, + object cookie, + AsyncCallback callback) + : base(communicator, instance, op, cookie, callback) { - result.whenCompletedWithAsyncCallback(cb); } - connectionFactory.flushAsyncBatchRequests(result); - adapterFactory.flushAsyncBatchRequests(result); - - // - // Inform the callback that we have finished initiating all of the - // flush requests. If all of the requests have already completed, - // the callback is invoked now. - // - result.ready(); + protected override AsyncCallback getCompletedCallback() + { + return (AsyncResult result) => + { + try + { + result.throwLocalException(); + } + catch(Exception ex) + { + if(exceptionCallback_ != null) + { + exceptionCallback_.Invoke(ex); + } + } + }; + } + }; + public AsyncResult begin_flushBatchRequests(Ice.CompressBatch compressBatch, AsyncCallback cb, object cookie) + { + var result = new CommunicatorFlushBatchCompletionCallback(this, + _instance, + _flushBatchRequests_name, + cookie, + cb); + var outgoing = new CommunicatorFlushBatchAsync(_instance, result); + outgoing.invoke(_flushBatchRequests_name, compressBatch); return result; } public void end_flushBatchRequests(AsyncResult result) { - IceInternal.CommunicatorFlushBatch outAsync = - IceInternal.CommunicatorFlushBatch.check(result, this, __flushBatchRequests_name); - outAsync.wait(); + if(result != null && result.getCommunicator() != this) + { + const string msg = "Communicator for call to end_" + _flushBatchRequests_name + + " does not match communicator that was used to call corresponding begin_" + + _flushBatchRequests_name + " method"; + throw new ArgumentException(msg); + } + AsyncResultI.check(result, _flushBatchRequests_name).wait(); } - public Ice.ObjectPrx createAdmin(ObjectAdapter adminAdapter, Identity adminIdentity) + public ObjectPrx createAdmin(ObjectAdapter adminAdapter, Identity adminIdentity) { - return instance_.createAdmin(adminAdapter, adminIdentity); + return _instance.createAdmin(adminAdapter, adminIdentity); } - - public Ice.ObjectPrx getAdmin() + + public ObjectPrx getAdmin() { - return instance_.getAdmin(); + return _instance.getAdmin(); } - public void addAdminFacet(Ice.Object servant, string facet) + public void addAdminFacet(Object servant, string facet) { - instance_.addAdminFacet(servant, facet); + _instance.addAdminFacet(servant, facet); } - public Ice.Object removeAdminFacet(string facet) + public Object removeAdminFacet(string facet) { - return instance_.removeAdminFacet(facet); + return _instance.removeAdminFacet(facet); } - public Ice.Object findAdminFacet(string facet) + public Object findAdminFacet(string facet) { - return instance_.findAdminFacet(facet); + return _instance.findAdminFacet(facet); } - public Dictionary<string, Ice.Object> findAllAdminFacets() + public Dictionary<string, Object> findAllAdminFacets() { - return instance_.findAllAdminFacets(); + return _instance.findAllAdminFacets(); } public void Dispose() @@ -242,7 +276,7 @@ namespace Ice internal CommunicatorI(InitializationData initData) { - instance_ = new IceInternal.Instance(this, initData); + _instance = new Instance(this, initData); } /* @@ -252,7 +286,7 @@ namespace Ice { if(!System.Environment.HasShutdownStarted) { - instance_.initializationData().logger.warning( + _instance.initializationData().logger.warning( "Ice::Communicator::destroy() has not been called"); } else @@ -271,11 +305,11 @@ namespace Ice { try { - instance_.finishSetup(ref args, this); + _instance.finishSetup(ref args, this); } catch(System.Exception) { - instance_.destroy(); + _instance.destroy(); throw; } } @@ -283,12 +317,11 @@ namespace Ice // // For use by Util.getInstance() // - internal IceInternal.Instance getInstance() + internal Instance getInstance() { - return instance_; + return _instance; } - private IceInternal.Instance instance_; + private Instance _instance; } - } diff --git a/csharp/src/Ice/Compare.cs b/csharp/src/Ice/Compare.cs index 251a57f74df..7f828640e02 100644 --- a/csharp/src/Ice/Compare.cs +++ b/csharp/src/Ice/Compare.cs @@ -7,9 +7,6 @@ // // ********************************************************************** -using System; -using System.Reflection; - namespace Ice { public class CollectionComparer @@ -25,7 +22,7 @@ namespace Ice System.Collections.ICollection c2, out bool result) { - if(object.ReferenceEquals(c1, c2)) + if(ReferenceEquals(c1, c2)) { result = true; return true; // Equal references means the collections are equal. @@ -138,7 +135,7 @@ namespace Ice { try { - if(object.ReferenceEquals(c1, c2)) + if(ReferenceEquals(c1, c2)) { return true; // Equal references means the collections are equal. } diff --git a/csharp/src/Ice/ConnectRequestHandler.cs b/csharp/src/Ice/ConnectRequestHandler.cs index aaa54600023..da1cd6e90fd 100644 --- a/csharp/src/Ice/ConnectRequestHandler.cs +++ b/csharp/src/Ice/ConnectRequestHandler.cs @@ -7,12 +7,9 @@ // // ********************************************************************** -using System; -using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; -using Ice.Instrumentation; namespace IceInternal { @@ -35,7 +32,7 @@ namespace IceInternal return previousHandler == this ? newHandler : this; } - public bool sendAsyncRequest(ProxyOutgoingAsyncBase outAsync, out Ice.AsyncCallback sentCallback) + public int sendAsyncRequest(ProxyOutgoingAsyncBase outAsync) { lock(this) { @@ -47,11 +44,10 @@ namespace IceInternal if(!initialized()) { _requests.AddLast(outAsync); - sentCallback = null; - return false; + return OutgoingAsyncBase.AsyncStatusQueued; } } - return outAsync.invokeRemote(_connection, _compress, _response, out sentCallback); + return outAsync.invokeRemote(_connection, _compress, _response); } public void asyncRequestCanceled(OutgoingAsyncBase outAsync, Ice.LocalException ex) @@ -71,10 +67,9 @@ namespace IceInternal if(p.Value == outAsync) { _requests.Remove(p); - Ice.AsyncCallback cb = outAsync.completed(ex); - if(cb != null) + if(outAsync.exception(ex)) { - outAsync.invokeCompletedAsync(cb); + outAsync.invokeExceptionAsync(); } return; } @@ -161,14 +156,13 @@ namespace IceInternal foreach(ProxyOutgoingAsyncBase outAsync in _requests) { - Ice.AsyncCallback cb = outAsync.completed(_exception); - if(cb != null) + if(outAsync.exception(_exception)) { - outAsync.invokeCompletedAsync(cb); + outAsync.invokeExceptionAsync(); } } _requests.Clear(); - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); } } @@ -205,7 +199,7 @@ namespace IceInternal { while(_flushing && _exception == null) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } if(_exception != null) @@ -248,13 +242,9 @@ namespace IceInternal { try { - Ice.AsyncCallback sentCallback = null; - if(outAsync.invokeRemote(_connection, _compress, _response, out sentCallback)) + if((outAsync.invokeRemote(_connection, _compress, _response) & OutgoingAsyncBase.AsyncStatusInvokeSentCallback) != 0) { - if(sentCallback != null) - { - outAsync.invokeSentAsync(sentCallback); - } + outAsync.invokeSentAsync(); } } catch(RetryException ex) @@ -269,10 +259,9 @@ namespace IceInternal catch(Ice.LocalException ex) { exception = ex; - Ice.AsyncCallback cb = outAsync.completed(ex); - if(cb != null) + if(outAsync.exception(ex)) { - outAsync.invokeCompletedAsync(cb); + outAsync.invokeExceptionAsync(); } } } @@ -289,7 +278,7 @@ namespace IceInternal _requestHandler = new ConnectionRequestHandler(_reference, _connection, _compress); foreach(Ice.ObjectPrxHelperBase prx in _proxies) { - prx.updateRequestHandler__(this, _requestHandler); + prx.iceUpdateRequestHandler(this, _requestHandler); } } @@ -308,7 +297,7 @@ namespace IceInternal _proxies.Clear(); _proxy = null; // Break cyclic reference count. - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); } } diff --git a/csharp/src/Ice/ConnectionFactory.cs b/csharp/src/Ice/ConnectionFactory.cs index dfafa3f1623..8f695852f23 100644 --- a/csharp/src/Ice/ConnectionFactory.cs +++ b/csharp/src/Ice/ConnectionFactory.cs @@ -9,15 +9,10 @@ namespace IceInternal { - using System; - using System.Collections; using System.Collections.Generic; using System.Diagnostics; - using System.Net.Sockets; - using System.Threading; using System.Text; - using IceUtilInternal; public class MultiDictionary<K, V> : Dictionary<K, ICollection<V>> { @@ -25,10 +20,10 @@ namespace IceInternal Add(K key, V value) { ICollection<V> list = null; - if(!this.TryGetValue(key, out list)) + if(!TryGetValue(key, out list)) { list = new List<V>(); - this.Add(key, list); + Add(key, list); } list.Add(value); } @@ -40,7 +35,7 @@ namespace IceInternal list.Remove(value); if(list.Count == 0) { - this.Remove(key); + Remove(key); } } } @@ -148,7 +143,6 @@ namespace IceInternal } } - public void create(EndpointI[] endpts, bool hasMore, Ice.EndpointSelectionType selType, CreateConnectionCallback callback) { @@ -261,7 +255,7 @@ namespace IceInternal } } - public void flushAsyncBatchRequests(CommunicatorFlushBatch outAsync) + public void flushAsyncBatchRequests(Ice.CompressBatch compressBatch, CommunicatorFlushBatchAsync outAsync) { ICollection<Ice.ConnectionI> c = new List<Ice.ConnectionI>(); @@ -286,7 +280,7 @@ namespace IceInternal { try { - outAsync.flushConnection(conn); + outAsync.flushConnection(conn, compressBatch); } catch(Ice.LocalException) { @@ -695,7 +689,7 @@ namespace IceInternal TraceLevels traceLevels = _instance.traceLevels(); if(traceLevels.retry >= 2) { - System.Text.StringBuilder s = new System.Text.StringBuilder(); + StringBuilder s = new StringBuilder(); s.Append("connection to endpoint failed"); if(ex is Ice.CommunicatorDestroyedException) { @@ -775,7 +769,7 @@ namespace IceInternal TraceLevels traceLevels = _instance.traceLevels(); if(traceLevels.retry >= 2) { - System.Text.StringBuilder s = new System.Text.StringBuilder(); + StringBuilder s = new StringBuilder(); s.Append("couldn't resolve endpoint host"); if(ex is Ice.CommunicatorDestroyedException) { @@ -1067,7 +1061,7 @@ namespace IceInternal { if(_observer != null) { - _observer.failed(ex.ice_name()); + _observer.failed(ex.ice_id()); _observer.detach(); } _factory.handleConnectionException(ex, _hasMore || _iter < _connectors.Count); @@ -1115,6 +1109,43 @@ namespace IceInternal public sealed class IncomingConnectionFactory : EventHandler, Ice.ConnectionI.StartCallback { + private class StartAcceptor : TimerTask + { + public StartAcceptor(IncomingConnectionFactory factory) + { + _factory = factory; + } + + public void runTimerTask() + { + _factory.startAcceptor(); + } + + private IncomingConnectionFactory _factory; + } + + public void startAcceptor() + { + lock(this) + { + if(_state >= StateClosed || _acceptorStarted) + { + return; + } + + try + { + createAcceptor(); + } + catch(Exception ex) + { + string s = "acceptor creation failed:\n" + ex + '\n' + _acceptor.ToString(); + _instance.initializationData().logger.error(s); + _instance.timer().schedule(new StartAcceptor(this), 1000); + } + } + } + public void activate() { lock(this) @@ -1261,7 +1292,7 @@ namespace IceInternal } } - public void flushAsyncBatchRequests(CommunicatorFlushBatch outAsync) + public void flushAsyncBatchRequests(Ice.CompressBatch compressBatch, CommunicatorFlushBatchAsync outAsync) { // // connections() is synchronized, no need to synchronize here. @@ -1270,7 +1301,7 @@ namespace IceInternal { try { - outAsync.flushConnection(connection); + outAsync.flushConnection(connection, compressBatch); } catch(Ice.LocalException) { @@ -1296,18 +1327,8 @@ namespace IceInternal } catch(Ice.LocalException ex) { - string s = "can't accept connections:\n" + ex + '\n' + _acceptor.ToString(); - try - { - _instance.initializationData().logger.error(s); - } - finally - { -#if !COMPACT && !SILVERLIGHT - System.Environment.FailFast(s); -#endif - } - return false; + _acceptorException = ex; + completedSynchronously = true; } return true; } @@ -1316,31 +1337,20 @@ namespace IceInternal { try { + if(_acceptorException != null) + { + throw _acceptorException; + } _acceptor.finishAccept(); } catch(Ice.LocalException ex) { - if(Network.noMoreFds(ex.InnerException)) - { - string s = "can't accept more connections:\n" + ex + '\n' + _acceptor.ToString(); - try - { - _instance.initializationData().logger.error(s); - } - finally - { -#if !COMPACT && !SILVERLIGHT - System.Environment.FailFast(s); -#endif - } - return false; - } - else - { - string s = "couldn't accept connection:\n" + ex + '\n' + _acceptor.ToString(); - _instance.initializationData().logger.error(s); - return false; - } + _acceptorException = null; + + string s = "couldn't accept connection:\n" + ex + '\n' + _acceptor.ToString(); + _instance.initializationData().logger.error(s); + _adapter.getThreadPool().finish(this); + closeAcceptor(); } return _state < StateClosed; } @@ -1381,6 +1391,11 @@ namespace IceInternal } } + if(!_acceptorStarted) + { + return; + } + // // Now accept a new connection. // @@ -1403,16 +1418,9 @@ namespace IceInternal if(Network.noMoreFds(ex.InnerException)) { string s = "can't accept more connections:\n" + ex + '\n' + _acceptor.ToString(); - try - { - _instance.initializationData().logger.error(s); - } - finally - { -#if !COMPACT && !SILVERLIGHT - System.Environment.FailFast(s); -#endif - } + _instance.initializationData().logger.error(s); + _adapter.getThreadPool().finish(this); + closeAcceptor(); } // Ignore socket exceptions. @@ -1469,6 +1477,10 @@ namespace IceInternal { lock(this) { + if(_state < StateClosed) + { + return; + } Debug.Assert(_state == StateClosed); setState(StateFinished); } @@ -1524,6 +1536,7 @@ namespace IceInternal _warn = _instance.initializationData().properties.getPropertyAsInt("Ice.Warn.Connections") > 0; _connections = new HashSet<Ice.ConnectionI>(); _state = StateHolding; + _acceptorStarted = false; _monitor = new FactoryACMMonitor(instance, ((Ice.ObjectAdapterI)adapter).getACM()); DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides(); @@ -1562,7 +1575,7 @@ namespace IceInternal createAcceptor(); } } - catch(System.Exception ex) + catch(Exception ex) { // // Clean up. @@ -1664,7 +1677,7 @@ namespace IceInternal case StateClosed: { - if(_acceptor != null) + if(_acceptorStarted) { _adapter.getThreadPool().finish(this); closeAcceptor(); @@ -1696,6 +1709,7 @@ namespace IceInternal { try { + Debug.Assert(!_acceptorStarted); _acceptor = _endpoint.acceptor(_adapter.getName()); Debug.Assert(_acceptor != null); @@ -1722,21 +1736,25 @@ namespace IceInternal if(_state == StateActive) { - _adapter.getThreadPool().unregister(this, SocketOperation.Read); + _adapter.getThreadPool().register(this, SocketOperation.Read); } + + _acceptorStarted = true; } - catch(SystemException ex) + catch(SystemException) { if(_acceptor != null) { _acceptor.close(); } - throw ex; + throw; } } private void closeAcceptor() { + Debug.Assert(_acceptor != null); + if(_instance.traceLevels().network >= 1) { StringBuilder s = new StringBuilder("stopping to accept "); @@ -1746,13 +1764,22 @@ namespace IceInternal _instance.initializationData().logger.trace(_instance.traceLevels().networkCat, s.ToString()); } + _acceptorStarted = false; _acceptor.close(); + + // + // If the acceptor hasn't been explicitly stopped (which is the case if the acceptor got closed + // because of an unexpected error), try to restart the acceptor in 5 seconds. + // + if(_state == StateHolding || _state == StateActive) + { + _instance.timer().schedule(new StartAcceptor(this), 1000); + } } private void warning(Ice.LocalException ex) { - _instance.initializationData().logger.warning("connection exception:\n" + ex + '\n' + - _acceptor.ToString()); + _instance.initializationData().logger.warning("connection exception:\n" + ex + '\n' + _acceptor.ToString()); } private Instance _instance; @@ -1769,6 +1796,8 @@ namespace IceInternal private HashSet<Ice.ConnectionI> _connections; private int _state; + private bool _acceptorStarted; + private Ice.LocalException _acceptorException; } } diff --git a/csharp/src/Ice/ConnectionI.cs b/csharp/src/Ice/ConnectionI.cs index 9d4c8fb1b38..b56135a5a9e 100644 --- a/csharp/src/Ice/ConnectionI.cs +++ b/csharp/src/Ice/ConnectionI.cs @@ -10,15 +10,17 @@ namespace Ice { using System; - using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; - using Ice.Instrumentation; + using System.Threading.Tasks; + using System.Linq; - public sealed class ConnectionI : - IceInternal.EventHandler, IceInternal.ResponseHandler, IceInternal.CancellationHandler, Connection + using Instrumentation; + using IceInternal; + + public sealed class ConnectionI : IceInternal.EventHandler, ResponseHandler, CancellationHandler, Connection { public interface StartCallback { @@ -26,7 +28,7 @@ namespace Ice void connectionStartFailed(ConnectionI connection, LocalException ex); } - private class TimeoutCallback : IceInternal.TimerTask + private class TimeoutCallback : TimerTask { public TimeoutCallback(ConnectionI connection) { @@ -38,7 +40,7 @@ namespace Ice _connection.timedOut(); } - private Ice.ConnectionI _connection; + private ConnectionI _connection; } public void start(StartCallback callback) @@ -56,7 +58,7 @@ namespace Ice throw _exception; } - if(!initialize(IceInternal.SocketOperation.None) || !validate(IceInternal.SocketOperation.None)) + if(!initialize(SocketOperation.None) || !validate(SocketOperation.None)) { _startCallback = callback; return; @@ -93,14 +95,14 @@ namespace Ice throw _exception; } - if(!initialize(IceInternal.SocketOperation.None) || !validate(IceInternal.SocketOperation.None)) + if(!initialize(SocketOperation.None) || !validate(SocketOperation.None)) { // // Wait for the connection to be validated. // while(_state <= StateNotValidated) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } if(_state >= StateClosing) @@ -135,7 +137,7 @@ namespace Ice if(_acmLastActivity > -1) { - _acmLastActivity = IceInternal.Time.currentMonotonicTimeMillis(); + _acmLastActivity = Time.currentMonotonicTimeMillis(); } setState(StateActive); } @@ -179,29 +181,31 @@ namespace Ice } } - public void close(bool force) + public void close(ConnectionClose mode) { lock(this) { - if(force) + if(mode == ConnectionClose.Forcefully) + { + setState(StateClosed, new ConnectionManuallyClosedException(false)); + } + else if(mode == ConnectionClose.Gracefully) { - setState(StateClosed, new ForcedCloseConnectionException()); + setState(StateClosing, new ConnectionManuallyClosedException(true)); } else { + Debug.Assert(mode == ConnectionClose.GracefullyWithWait); + // - // If we do a graceful shutdown, then we wait until all - // outstanding requests have been completed. Otherwise, - // the CloseConnectionException will cause all outstanding - // requests to be retried, regardless of whether the - // server has processed them or not. + // Wait until all outstanding requests have been completed. // while(_asyncRequests.Count != 0) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } - setState(StateClosing, new CloseConnectionException()); + setState(StateClosing, new ConnectionManuallyClosedException(true)); } } } @@ -221,7 +225,7 @@ namespace Ice // threads operating in this connection object, connection // destruction is considered as not yet finished. // - if(!System.Threading.Monitor.TryEnter(this)) + if(!Monitor.TryEnter(this)) { return false; } @@ -238,7 +242,7 @@ namespace Ice } finally { - System.Threading.Monitor.Exit(this); + Monitor.Exit(this); } } @@ -260,7 +264,7 @@ namespace Ice { while(_state < StateHolding || _dispatchCount > 0) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } } } @@ -277,7 +281,7 @@ namespace Ice // while(_state < StateFinished || _dispatchCount > 0) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } Debug.Assert(_state == StateFinished); @@ -315,7 +319,7 @@ namespace Ice } } - public void monitor(long now, IceInternal.ACMConfig acm) + public void monitor(long now, ACMConfig acm) { lock(this) { @@ -328,13 +332,13 @@ namespace Ice // We send a heartbeat if there was no activity in the last // (timeout / 4) period. Sending a heartbeat sooner than // really needed is safer to ensure that the receiver will - // receive in time the heartbeat. Sending the heartbeat if + // receive the heartbeat in time. Sending the heartbeat if // there was no activity in the last (timeout / 2) period // isn't enough since monitor() is called only every (timeout // / 2) period. // // Note that this doesn't imply that we are sending 4 heartbeats - // per timeout period because the monitor() method is sill only + // per timeout period because the monitor() method is still only // called every (timeout / 2) period. // if(acm.heartbeat == ACMHeartbeat.HeartbeatAlways || @@ -343,11 +347,11 @@ namespace Ice { if(acm.heartbeat != ACMHeartbeat.HeartbeatOnInvocation || _dispatchCount > 0) { - heartbeat(); + sendHeartbeatNow(); } } - if(_readStream.size() > IceInternal.Protocol.headerSize || !_writeStream.isEmpty()) + if(_readStream.size() > Protocol.headerSize || !_writeStream.isEmpty()) { // // If writing or reading, nothing to do, the connection @@ -382,21 +386,21 @@ namespace Ice } } - public bool sendAsyncRequest(IceInternal.OutgoingAsyncBase og, bool compress, bool response, - int batchRequestNum, out Ice.AsyncCallback sentCallback) + public int sendAsyncRequest(OutgoingAsyncBase og, bool compress, bool response, + int batchRequestNum) { - IceInternal.BasicStream os = og.getOs(); + OutputStream os = og.getOs(); lock(this) { + // + // If the exception is closed before we even have a chance + // to send our request, we always try to send the request + // again. + // if(_exception != null) { - // - // If the connection is closed before we even have a chance - // to send our request, we always try to send the request - // again. - // - throw new IceInternal.RetryException(_exception); + throw new RetryException(_exception); } Debug.Assert(_state > StateNotValidated); @@ -413,7 +417,6 @@ namespace Ice // This will throw if the request is canceled. // og.cancelable(this); - int requestId = 0; if(response) { @@ -430,23 +433,22 @@ namespace Ice // // Fill in the request ID. // - os.pos(IceInternal.Protocol.headerSize); + os.pos(Protocol.headerSize); os.writeInt(requestId); } else if(batchRequestNum > 0) { - os.pos(IceInternal.Protocol.headerSize); + os.pos(Protocol.headerSize); os.writeInt(batchRequestNum); } og.attachRemoteObserver(initConnectionInfo(), _endpoint, requestId); - bool sent; + int status = OutgoingAsyncBase.AsyncStatusQueued; try { - OutgoingMessage msg = new OutgoingMessage(og, os, compress, requestId); - sent = sendMessage(msg); - sentCallback = msg.sentCallback; + OutgoingMessage message = new OutgoingMessage(og, os, compress, requestId); + status = sendMessage(message); } catch(LocalException ex) { @@ -462,52 +464,95 @@ namespace Ice // _asyncRequests[requestId] = og; } - return sent; + return status; } } - public IceInternal.BatchRequestQueue getBatchRequestQueue() + public BatchRequestQueue getBatchRequestQueue() { return _batchRequestQueue; } - public void flushBatchRequests() + public void flushBatchRequests(CompressBatch compressBatch) { - end_flushBatchRequests(begin_flushBatchRequests()); + flushBatchRequestsAsync(compressBatch).Wait(); } - public AsyncResult begin_flushBatchRequests() + private class ConnectionFlushBatchCompletionCallback : AsyncResultCompletionCallback { - return begin_flushBatchRequestsInternal(null, null); + public ConnectionFlushBatchCompletionCallback(Connection connection, + Communicator communicator, + Instance instance, + string op, + object cookie, + AsyncCallback callback) + : base(communicator, instance, op, cookie, callback) + { + _connection = connection; + } + + public override Connection getConnection() + { + return _connection; + } + + protected override AsyncCallback getCompletedCallback() + { + return (AsyncResult result) => + { + try + { + result.throwLocalException(); + } + catch(Exception ex) + { + if(exceptionCallback_ != null) + { + exceptionCallback_.Invoke(ex); + } + } + }; + } + + private Connection _connection; } - public AsyncResult begin_flushBatchRequests(AsyncCallback cb, object cookie) + public Task flushBatchRequestsAsync(CompressBatch compressBatch, + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()) { - return begin_flushBatchRequestsInternal(cb, cookie); + var completed = new FlushBatchTaskCompletionCallback(progress, cancel); + var outgoing = new ConnectionFlushBatchAsync(this, _instance, completed); + outgoing.invoke(_flushBatchRequests_name, compressBatch); + return completed.Task; } - public void end_flushBatchRequests(AsyncResult r) + public AsyncResult begin_flushBatchRequests(CompressBatch compressBatch, + AsyncCallback cb = null, + object cookie = null) { - IceInternal.ConnectionFlushBatch outAsync = - IceInternal.ConnectionFlushBatch.check(r, this, __flushBatchRequests_name); - outAsync.wait(); + var result = new ConnectionFlushBatchCompletionCallback(this, _communicator, _instance, + _flushBatchRequests_name, cookie, cb); + var outgoing = new ConnectionFlushBatchAsync(this, _instance, result); + outgoing.invoke(_flushBatchRequests_name, compressBatch); + return result; } - private const string __flushBatchRequests_name = "flushBatchRequests"; - - private AsyncResult begin_flushBatchRequestsInternal(AsyncCallback cb, object cookie) + public void end_flushBatchRequests(AsyncResult r) { - IceInternal.ConnectionFlushBatch result = - new IceInternal.ConnectionFlushBatch(this, _communicator, _instance, __flushBatchRequests_name, cookie); - if(cb != null) + if(r != null && r.getConnection() != this) { - result.whenCompletedWithAsyncCallback(cb); + const string msg = "Connection for call to end_" + _flushBatchRequests_name + + " does not match connection that was used to call corresponding begin_" + + _flushBatchRequests_name + " method"; + throw new ArgumentException(msg); } - result.invoke(); - return result; + AsyncResultI.check(r, _flushBatchRequests_name).wait(); } - public void setCallback(ConnectionCallback callback) + private const string _flushBatchRequests_name = "flushBatchRequests"; + + public void setCloseCallback(CloseCallback callback) { lock(this) { @@ -519,7 +564,7 @@ namespace Ice { try { - callback.closed(this); + callback(this); } catch(System.Exception ex) { @@ -530,11 +575,162 @@ namespace Ice } else { - _callback = callback; + _closeCallback = callback; } } } + public void setHeartbeatCallback(HeartbeatCallback callback) + { + lock(this) + { + _heartbeatCallback = callback; + } + } + + public void heartbeat() + { + heartbeatAsync().Wait(); + } + + private class HeartbeatCompletionCallback : AsyncResultCompletionCallback + { + public HeartbeatCompletionCallback(Ice.Connection connection, + Ice.Communicator communicator, + Instance instance, + object cookie, + Ice.AsyncCallback callback) + : base(communicator, instance, "heartbeat", cookie, callback) + { + _connection = connection; + } + + public override Ice.Connection getConnection() + { + return _connection; + } + + protected override Ice.AsyncCallback getCompletedCallback() + { + return (Ice.AsyncResult result) => + { + try + { + result.throwLocalException(); + } + catch(Ice.Exception ex) + { + if(exceptionCallback_ != null) + { + exceptionCallback_.Invoke(ex); + } + } + }; + } + + private Ice.Connection _connection; + } + + private class HeartbeatTaskCompletionCallback : TaskCompletionCallback<object> + { + public HeartbeatTaskCompletionCallback(System.IProgress<bool> progress, + CancellationToken cancellationToken) : + base(progress, cancellationToken) + { + } + + public override bool handleResponse(bool ok, OutgoingAsyncBase og) + { + SetResult(null); + return false; + } + } + + private class HeartbeatAsync : OutgoingAsyncBase + { + public HeartbeatAsync(Ice.ConnectionI connection, + Instance instance, + OutgoingAsyncCompletionCallback completionCallback) : + base(instance, completionCallback) + { + _connection = connection; + } + + public void invoke() + { + try + { + os_.writeBlob(IceInternal.Protocol.magic); + ProtocolVersion.ice_write(os_, Ice.Util.currentProtocol); + EncodingVersion.ice_write(os_, Ice.Util.currentProtocolEncoding); + os_.writeByte(IceInternal.Protocol.validateConnectionMsg); + os_.writeByte((byte)0); + os_.writeInt(IceInternal.Protocol.headerSize); // Message size. + + int status = _connection.sendAsyncRequest(this, false, false, 0); + + if((status & AsyncStatusSent) != 0) + { + sentSynchronously_ = true; + if((status & AsyncStatusInvokeSentCallback) != 0) + { + invokeSent(); + } + } + } + catch(RetryException ex) + { + try + { + throw ex.get(); + } + catch(Ice.LocalException ee) + { + if(exception(ee)) + { + invokeExceptionAsync(); + } + } + } + catch(Ice.Exception ex) + { + if(exception(ex)) + { + invokeExceptionAsync(); + } + } + } + + private readonly Ice.ConnectionI _connection; + } + + public Task heartbeatAsync(IProgress<bool> progress = null, CancellationToken cancel = new CancellationToken()) + { + var completed = new HeartbeatTaskCompletionCallback(progress, cancel); + var outgoing = new HeartbeatAsync(this, _instance, completed); + outgoing.invoke(); + return completed.Task; + } + + public AsyncResult begin_heartbeat(AsyncCallback cb = null, object cookie = null) + { + var result = new HeartbeatCompletionCallback(this, _communicator, _instance, cookie, cb); + var outgoing = new HeartbeatAsync(this, _instance, result); + outgoing.invoke(); + return result; + } + + public void end_heartbeat(AsyncResult r) + { + if(r != null && r.getConnection() != this) + { + const string msg = "Connection for call to end_heartbeat does not match connection that was used " + + "to call corresponding begin_heartbeat method"; + throw new ArgumentException(msg); + } + AsyncResultI.check(r, "heartbeat").wait(); + } + public void setACM(Optional<int> timeout, Optional<ACMClose> close, Optional<ACMHeartbeat> heartbeat) { lock(this) @@ -556,7 +752,7 @@ namespace Ice } else if(_state == StateActive && _acmLastActivity == -1) { - _acmLastActivity = IceInternal.Time.currentMonotonicTimeMillis(); + _acmLastActivity = Time.currentMonotonicTimeMillis(); } if(_state == StateActive) @@ -574,7 +770,7 @@ namespace Ice } } - public void asyncRequestCanceled(IceInternal.OutgoingAsyncBase outAsync, Ice.LocalException ex) + public void asyncRequestCanceled(OutgoingAsyncBase outAsync, LocalException ex) { // // NOTE: This isn't called from a thread pool thread. @@ -587,59 +783,58 @@ namespace Ice return; // The request has already been or will be shortly notified of the failure. } - LinkedListNode<OutgoingMessage> p; - for(p = _sendStreams.First; p != null; p = p.Next) + + OutgoingMessage o = _sendStreams.FirstOrDefault(m => m.outAsync == outAsync); + if(o != null) { - OutgoingMessage o = p.Value; - if(o.outAsync == outAsync) + if(o.requestId > 0) { - if(o.requestId > 0) - { - _asyncRequests.Remove(o.requestId); - } + _asyncRequests.Remove(o.requestId); + } - if(ex is Ice.ConnectionTimeoutException) + if(ex is ConnectionTimeoutException) + { + setState(StateClosed, ex); + } + else + { + // + // If the request is being sent, don't remove it from the send streams, + // it will be removed once the sending is finished. + // + if(o == _sendStreams.First.Value) { - setState(StateClosed, ex); + o.canceled(); } else { - // - // If the request is being sent, don't remove it from the send streams, - // it will be removed once the sending is finished. - // o.canceled(); - if(o != _sendStreams.First.Value) - { - _sendStreams.Remove(p); - } - Ice.AsyncCallback cb = outAsync.completed(ex); - if(cb != null) - { - outAsync.invokeCompletedAsync(cb); - } + _sendStreams.Remove(o); + } + if(outAsync.exception(ex)) + { + outAsync.invokeExceptionAsync(); } - return; } + return; } - if(outAsync is IceInternal.OutgoingAsync) + if(outAsync is OutgoingAsync) { - foreach(KeyValuePair<int, IceInternal.OutgoingAsyncBase> kvp in _asyncRequests) + foreach(KeyValuePair<int, OutgoingAsyncBase> kvp in _asyncRequests) { if(kvp.Value == outAsync) { - if(ex is Ice.ConnectionTimeoutException) + if(ex is ConnectionTimeoutException) { setState(StateClosed, ex); } else { _asyncRequests.Remove(kvp.Key); - Ice.AsyncCallback cb = outAsync.completed(ex); - if(cb != null) + if(outAsync.exception(ex)) { - outAsync.invokeCompletedAsync(cb); + outAsync.invokeExceptionAsync(); } } return; @@ -649,7 +844,7 @@ namespace Ice } } - public void sendResponse(int requestId, IceInternal.BasicStream os, byte compressFlag, bool amd) + public void sendResponse(int requestId, OutputStream os, byte compressFlag, bool amd) { lock(this) { @@ -663,7 +858,7 @@ namespace Ice { reap(); } - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); } if(_state >= StateClosed) @@ -672,7 +867,7 @@ namespace Ice throw _exception; } - sendMessage(new OutgoingMessage(os, compressFlag != 0, true)); + sendMessage(new OutgoingMessage(os, compressFlag > 0, true)); if(_state == StateClosing && _dispatchCount == 0) { @@ -700,7 +895,7 @@ namespace Ice { reap(); } - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); } if(_state >= StateClosed) @@ -721,7 +916,7 @@ namespace Ice } } - public bool systemException(int requestId, Ice.SystemException ex, bool amd) + public bool systemException(int requestId, SystemException ex, bool amd) { return false; // System exceptions aren't marshalled. } @@ -747,18 +942,18 @@ namespace Ice { reap(); } - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); } } } } - public IceInternal.EndpointI endpoint() + public EndpointI endpoint() { return _endpoint; // No mutex protection necessary, _endpoint is immutable. } - public IceInternal.Connector connector() + public Connector connector() { return _connector; // No mutex protection necessary, _endpoint is immutable. } @@ -828,7 +1023,7 @@ namespace Ice try { - if((operation & IceInternal.SocketOperation.Write) != 0) + if((operation & SocketOperation.Write) != 0) { if(_observer != null) { @@ -843,7 +1038,7 @@ namespace Ice _sendStreams.First.Value.isSent = true; } } - else if((operation & IceInternal.SocketOperation.Read) != 0) + else if((operation & SocketOperation.Read) != 0) { if(_observer != null && !_readHeader) { @@ -853,7 +1048,7 @@ namespace Ice completedSynchronously = _transceiver.startRead(_readStream.getBuffer(), cb, this); } } - catch(Ice.LocalException ex) + catch(LocalException ex) { setState(StateClosed, ex); return false; @@ -865,7 +1060,7 @@ namespace Ice { try { - if((operation & IceInternal.SocketOperation.Write) != 0) + if((operation & SocketOperation.Write) != 0) { IceInternal.Buffer buf = _writeStream.getBuffer(); int start = buf.b.position(); @@ -891,7 +1086,7 @@ namespace Ice observerFinishWrite(_writeStream.getBuffer()); } } - else if((operation & IceInternal.SocketOperation.Read) != 0) + else if((operation & SocketOperation.Read) != 0) { IceInternal.Buffer buf = _readStream.getBuffer(); int start = buf.b.position(); @@ -922,21 +1117,21 @@ namespace Ice } } } - catch(Ice.LocalException ex) + catch(LocalException ex) { setState(StateClosed, ex); } return _state < StateClosed; } - public override void message(ref IceInternal.ThreadPoolCurrent current) + public override void message(ref ThreadPoolCurrent current) { StartCallback startCB = null; Queue<OutgoingMessage> sentCBs = null; MessageInfo info = new MessageInfo(); int dispatchCount = 0; - IceInternal.ThreadPoolMessage msg = new IceInternal.ThreadPoolMessage(this); + ThreadPoolMessage msg = new ThreadPoolMessage(this); try { lock(this) @@ -956,22 +1151,22 @@ namespace Ice { unscheduleTimeout(current.operation); - int writeOp = IceInternal.SocketOperation.None; - int readOp = IceInternal.SocketOperation.None; - if((readyOp & IceInternal.SocketOperation.Write) != 0) + int writeOp = SocketOperation.None; + int readOp = SocketOperation.None; + if((readyOp & SocketOperation.Write) != 0) { if(_observer != null) { observerStartWrite(_writeStream.getBuffer()); } writeOp = write(_writeStream.getBuffer()); - if(_observer != null && (writeOp & IceInternal.SocketOperation.Write) == 0) + if(_observer != null && (writeOp & SocketOperation.Write) == 0) { observerFinishWrite(_writeStream.getBuffer()); } } - while((readyOp & IceInternal.SocketOperation.Read) != 0) + while((readyOp & SocketOperation.Read) != 0) { IceInternal.Buffer buf = _readStream.getBuffer(); @@ -981,7 +1176,7 @@ namespace Ice } readOp = read(buf); - if((readOp & IceInternal.SocketOperation.Read) != 0) + if((readOp & SocketOperation.Read) != 0) { break; } @@ -997,16 +1192,16 @@ namespace Ice if(_observer != null) { - _observer.receivedBytes(IceInternal.Protocol.headerSize); + _observer.receivedBytes(Protocol.headerSize); } int pos = _readStream.pos(); - if(pos < IceInternal.Protocol.headerSize) + if(pos < Protocol.headerSize) { // // This situation is possible for small UDP packets. // - throw new Ice.IllegalMessageSizeException(); + throw new IllegalMessageSizeException(); } _readStream.pos(0); @@ -1015,35 +1210,35 @@ namespace Ice m[1] = _readStream.readByte(); m[2] = _readStream.readByte(); m[3] = _readStream.readByte(); - if(m[0] != IceInternal.Protocol.magic[0] || m[1] != IceInternal.Protocol.magic[1] || - m[2] != IceInternal.Protocol.magic[2] || m[3] != IceInternal.Protocol.magic[3]) + if(m[0] != Protocol.magic[0] || m[1] != Protocol.magic[1] || + m[2] != Protocol.magic[2] || m[3] != Protocol.magic[3]) { - Ice.BadMagicException ex = new Ice.BadMagicException(); + BadMagicException ex = new BadMagicException(); ex.badMagic = m; throw ex; } ProtocolVersion pv = new ProtocolVersion(); - pv.read__(_readStream); - IceInternal.Protocol.checkSupportedProtocol(pv); + pv.ice_readMembers(_readStream); + Protocol.checkSupportedProtocol(pv); EncodingVersion ev = new EncodingVersion(); - ev.read__(_readStream); - IceInternal.Protocol.checkSupportedProtocolEncoding(ev); + ev.ice_readMembers(_readStream); + Protocol.checkSupportedProtocolEncoding(ev); _readStream.readByte(); // messageType _readStream.readByte(); // compress int size = _readStream.readInt(); - if(size < IceInternal.Protocol.headerSize) + if(size < Protocol.headerSize) { - throw new Ice.IllegalMessageSizeException(); + throw new IllegalMessageSizeException(); } if(size > _messageSizeMax) { - IceInternal.Ex.throwMemoryLimitException(size, _messageSizeMax); + Ex.throwMemoryLimitException(size, _messageSizeMax); } if(size > _readStream.size()) { - _readStream.resize(size, true); + _readStream.resize(size); } _readStream.pos(pos); } @@ -1052,7 +1247,7 @@ namespace Ice { if(_endpoint.datagram()) { - throw new Ice.DatagramLimitException(); // The message was truncated. + throw new DatagramLimitException(); // The message was truncated. } continue; } @@ -1110,13 +1305,13 @@ namespace Ice // We parse messages first, if we receive a close // connection message we won't send more messages. // - if((readyOp & IceInternal.SocketOperation.Read) != 0) + if((readyOp & SocketOperation.Read) != 0) { newOp |= parseMessage(ref info); dispatchCount += info.messageDispatchCount; } - if((readyOp & IceInternal.SocketOperation.Write) != 0) + if((readyOp & SocketOperation.Write) != 0) { newOp |= sendNextMessage(out sentCBs); if(sentCBs != null) @@ -1134,7 +1329,7 @@ namespace Ice if(_acmLastActivity > -1) { - _acmLastActivity = IceInternal.Time.currentMonotonicTimeMillis(); + _acmLastActivity = Time.currentMonotonicTimeMillis(); } if(dispatchCount == 0) @@ -1150,9 +1345,9 @@ namespace Ice { if(_warnUdp) { - _logger.warning("maximum datagram size of " + _readStream.pos() + " exceeded"); + _logger.warning(string.Format("maximum datagram size of {0} exceeded", _readStream.pos())); } - _readStream.resize(IceInternal.Protocol.headerSize, true); + _readStream.resize(Protocol.headerSize); _readStream.pos(0); _readHeader = true; return; @@ -1168,10 +1363,9 @@ namespace Ice { if(_warn) { - String s = "datagram connection exception:\n" + ex + '\n' + _desc; - _logger.warning(s); + _logger.warning(string.Format("datagram connection exception:\n{0}\n{1}", ex, _desc)); } - _readStream.resize(IceInternal.Protocol.headerSize, true); + _readStream.resize(Protocol.headerSize); _readStream.pos(0); _readHeader = true; } @@ -1182,7 +1376,7 @@ namespace Ice return; } - IceInternal.ThreadPoolCurrent c = current; + ThreadPoolCurrent c = current; _threadPool.dispatch(() => { dispatch(startCB, sentCBs, info); @@ -1218,17 +1412,16 @@ namespace Ice { foreach(OutgoingMessage m in sentCBs) { - if(m.sentCallback != null) + if(m.invokeSent) { - m.outAsync.invokeSent(m.sentCallback); + m.outAsync.invokeSent(); } if(m.receivedReply) { - IceInternal.OutgoingAsync outAsync = (IceInternal.OutgoingAsync)m.outAsync; - Ice.AsyncCallback cb = outAsync.completed(); - if(cb != null) + OutgoingAsync outAsync = (OutgoingAsync)m.outAsync; + if(outAsync.response()) { - outAsync.invokeCompleted(cb); + outAsync.invokeResponse(); } } } @@ -1241,7 +1434,7 @@ namespace Ice // if(info.outAsync != null) { - info.outAsync.invokeCompleted(info.completedCallback); + info.outAsync.invokeResponse(); ++dispatchedCount; } @@ -1249,7 +1442,7 @@ namespace Ice { try { - info.heartbeatCallback.heartbeat(this); + info.heartbeatCallback(this); } catch(System.Exception ex) { @@ -1305,18 +1498,18 @@ namespace Ice { reap(); } - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); } } } } - public override void finished(ref IceInternal.ThreadPoolCurrent current) + public override void finished(ref ThreadPoolCurrent current) { lock(this) { Debug.Assert(_state == StateClosed); - unscheduleTimeout(IceInternal.SocketOperation.Read | IceInternal.SocketOperation.Write); + unscheduleTimeout(SocketOperation.Read | SocketOperation.Write); } // @@ -1324,7 +1517,8 @@ namespace Ice // to call code that will potentially block (this avoids promoting a new leader and // unecessary thread creation, especially if this is called on shutdown). // - if(_startCallback == null && _sendStreams.Count == 0 && _asyncRequests.Count == 0 && _callback == null) + if(_startCallback == null && _sendStreams.Count == 0 && _asyncRequests.Count == 0 && + _closeCallback == null && _heartbeatCallback == null) { finish(); return; @@ -1369,7 +1563,7 @@ namespace Ice // Trace the cause of unexpected connection closures // if(!(_exception is CloseConnectionException || - _exception is ForcedCloseConnectionException || + _exception is ConnectionManuallyClosedException || _exception is ConnectionTimeoutException || _exception is CommunicatorDestroyedException || _exception is ObjectAdapterDeactivatedException)) @@ -1406,40 +1600,38 @@ namespace Ice // if(message.isSent || message.receivedReply) { - if(message.sent() && message.sentCallback != null) + if(message.sent() && message.invokeSent) { - message.outAsync.invokeSent(message.sentCallback); + message.outAsync.invokeSent(); } if(message.receivedReply) { - IceInternal.OutgoingAsync outAsync = (IceInternal.OutgoingAsync)message.outAsync; - Ice.AsyncCallback cb = outAsync.completed(); - if(cb != null) + OutgoingAsync outAsync = (OutgoingAsync)message.outAsync; + if(outAsync.response()) { - outAsync.invokeCompleted(cb); + outAsync.invokeResponse(); } } _sendStreams.RemoveFirst(); } } - foreach(OutgoingMessage m in _sendStreams) + foreach (OutgoingMessage o in _sendStreams) { - m.completed(_exception); - if(m.requestId > 0) // Make sure finished isn't called twice. + o.completed(_exception); + if(o.requestId > 0) // Make sure finished isn't called twice. { - _asyncRequests.Remove(m.requestId); + _asyncRequests.Remove(o.requestId); } } - _sendStreams.Clear(); + _sendStreams.Clear(); // Must be cleared before _requests because of Outgoing* references in OutgoingMessage } - foreach(IceInternal.OutgoingAsyncBase o in _asyncRequests.Values) + foreach(OutgoingAsyncBase o in _asyncRequests.Values) { - Ice.AsyncCallback cb = o.completed(_exception); - if(cb != null) + if(o.exception(_exception)) { - o.invokeCompleted(cb); + o.invokeException(); } } _asyncRequests.Clear(); @@ -1453,19 +1645,21 @@ namespace Ice _readStream.getBuffer().clear(); _incomingCache = null; - if(_callback != null) + if(_closeCallback != null) { try { - _callback.closed(this); + _closeCallback(this); } catch(System.Exception ex) { _logger.error("connection callback exception:\n" + ex + '\n' + _desc); } - _callback = null; + _closeCallback = null; } + _heartbeatCallback = null; + // // This must be done last as this will cause waitUntilFinished() to return (and communicator // objects such as the timer might be destroyed too). @@ -1555,12 +1749,11 @@ namespace Ice static ConnectionI() { - _compressionSupported = IceInternal.BasicStream.compressible(); + _compressionSupported = IceInternal.BZip2.supported(); } - internal ConnectionI(Communicator communicator, IceInternal.Instance instance, - IceInternal.ACMMonitor monitor, IceInternal.Transceiver transceiver, - IceInternal.Connector connector, IceInternal.EndpointI endpoint, ObjectAdapterI adapter) + internal ConnectionI(Communicator communicator, Instance instance, ACMMonitor monitor, Transceiver transceiver, + Connector connector, EndpointI endpoint, ObjectAdapterI adapter) { _communicator = communicator; _instance = instance; @@ -1584,7 +1777,7 @@ namespace Ice _cacheBuffers = instance.cacheMessageBuffers() > 0; if(_monitor != null && _monitor.getACM().timeout > 0) { - _acmLastActivity = IceInternal.Time.currentMonotonicTimeMillis(); + _acmLastActivity = Time.currentMonotonicTimeMillis(); } else { @@ -1592,11 +1785,11 @@ namespace Ice } _nextRequestId = 1; _messageSizeMax = adapter != null ? adapter.messageSizeMax() : instance.messageSizeMax(); - _batchRequestQueue = new IceInternal.BatchRequestQueue(instance, _endpoint.datagram()); - _readStream = new IceInternal.BasicStream(instance, Util.currentProtocolEncoding); + _batchRequestQueue = new BatchRequestQueue(instance, _endpoint.datagram()); + _readStream = new InputStream(instance, Util.currentProtocolEncoding); _readHeader = false; _readStreamPos = -1; - _writeStream = new IceInternal.BasicStream(instance, Util.currentProtocolEncoding); + _writeStream = new OutputStream(instance, Util.currentProtocolEncoding); _writeStreamPos = -1; _dispatchCount = 0; _state = StateNotInitialized; @@ -1678,7 +1871,7 @@ namespace Ice // Don't warn about certain expected exceptions. // if(!(_exception is CloseConnectionException || - _exception is ForcedCloseConnectionException || + _exception is ConnectionManuallyClosedException || _exception is ConnectionTimeoutException || _exception is CommunicatorDestroyedException || _exception is ObjectAdapterDeactivatedException || @@ -1751,7 +1944,7 @@ namespace Ice { return; } - _threadPool.register(this, IceInternal.SocketOperation.Read); + _threadPool.register(this, SocketOperation.Read); break; } @@ -1767,7 +1960,7 @@ namespace Ice } if(_state == StateActive) { - _threadPool.unregister(this, IceInternal.SocketOperation.Read); + _threadPool.unregister(this, SocketOperation.Read); } break; } @@ -1807,7 +2000,7 @@ namespace Ice } } } - catch(Ice.LocalException ex) + catch(LocalException ex) { _logger.error("unexpected connection exception:\n" + ex + "\n" + _transceiver.ToString()); } @@ -1824,7 +2017,7 @@ namespace Ice { if(_acmLastActivity > -1) { - _acmLastActivity = IceInternal.Time.currentMonotonicTimeMillis(); + _acmLastActivity = Time.currentMonotonicTimeMillis(); } _monitor.add(this); } @@ -1857,19 +2050,19 @@ namespace Ice if(_observer != null && state == StateClosed && _exception != null) { if(!(_exception is CloseConnectionException || - _exception is ForcedCloseConnectionException || + _exception is ConnectionManuallyClosedException || _exception is ConnectionTimeoutException || _exception is CommunicatorDestroyedException || _exception is ObjectAdapterDeactivatedException || (_exception is ConnectionLostException && _state >= StateClosing))) { - _observer.failed(_exception.ice_name()); + _observer.failed(_exception.ice_id()); } } } _state = state; - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); if(_state == StateClosing && _dispatchCount == 0) { @@ -1886,8 +2079,7 @@ namespace Ice private void initiateShutdown() { - Debug.Assert(_state == StateClosing); - Debug.Assert(_dispatchCount == 0); + Debug.Assert(_state == StateClosing && _dispatchCount == 0); if(_shutdownInitiated) { @@ -1900,20 +2092,20 @@ namespace Ice // // Before we shut down, we send a close connection message. // - IceInternal.BasicStream os = new IceInternal.BasicStream(_instance, Util.currentProtocolEncoding); - os.writeBlob(IceInternal.Protocol.magic); - Ice.Util.currentProtocol.write__(os); - Ice.Util.currentProtocolEncoding.write__(os); - os.writeByte(IceInternal.Protocol.closeConnectionMsg); + OutputStream os = new OutputStream(_instance, Util.currentProtocolEncoding); + os.writeBlob(Protocol.magic); + Util.currentProtocol.ice_writeMembers(os); + Util.currentProtocolEncoding.ice_writeMembers(os); + os.writeByte(Protocol.closeConnectionMsg); os.writeByte(_compressionSupported ? (byte)1 : (byte)0); - os.writeInt(IceInternal.Protocol.headerSize); // Message size. + os.writeInt(Protocol.headerSize); // Message size. - if(sendMessage(new OutgoingMessage(os, false, false))) + if((sendMessage(new OutgoingMessage(os, false, false)) & OutgoingAsyncBase.AsyncStatusSent) != 0) { setState(StateClosingPending); // - // Notify the the transceiver of the graceful connection closure. + // Notify the transceiver of the graceful connection closure. // int op = _transceiver.closing(true, _exception); if(op != 0) @@ -1925,25 +2117,24 @@ namespace Ice } } - private void heartbeat() + private void sendHeartbeatNow() { Debug.Assert(_state == StateActive); if(!_endpoint.datagram()) { - IceInternal.BasicStream os = new IceInternal.BasicStream(_instance, Util.currentProtocolEncoding); - os.writeBlob(IceInternal.Protocol.magic); - Ice.Util.currentProtocol.write__(os); - Ice.Util.currentProtocolEncoding.write__(os); - os.writeByte(IceInternal.Protocol.validateConnectionMsg); - os.writeByte((byte)0); - os.writeInt(IceInternal.Protocol.headerSize); // Message size. + OutputStream os = new OutputStream(_instance, Util.currentProtocolEncoding); + os.writeBlob(Protocol.magic); + Util.currentProtocol.ice_writeMembers(os); + Util.currentProtocolEncoding.ice_writeMembers(os); + os.writeByte(Protocol.validateConnectionMsg); + os.writeByte(0); + os.writeInt(Protocol.headerSize); // Message size. try { - OutgoingMessage message = new OutgoingMessage(os, false, false); - sendMessage(message); + sendMessage(new OutgoingMessage(os, false, false)); } - catch(Ice.LocalException ex) + catch(LocalException ex) { setState(StateClosed, ex); Debug.Assert(_exception != null); @@ -1954,7 +2145,7 @@ namespace Ice private bool initialize(int operation) { int s = _transceiver.initialize(_readStream.getBuffer(), _writeStream.getBuffer(), ref _hasMoreData); - if(s != IceInternal.SocketOperation.None) + if(s != SocketOperation.None) { scheduleTimeout(s); _threadPool.update(this, operation, s); @@ -1979,13 +2170,13 @@ namespace Ice { if(_writeStream.size() == 0) { - _writeStream.writeBlob(IceInternal.Protocol.magic); - Ice.Util.currentProtocol.write__(_writeStream); - Ice.Util.currentProtocolEncoding.write__(_writeStream); - _writeStream.writeByte(IceInternal.Protocol.validateConnectionMsg); - _writeStream.writeByte((byte)0); // Compression status (always zero for validate connection). - _writeStream.writeInt(IceInternal.Protocol.headerSize); // Message size. - IceInternal.TraceUtil.traceSend(_writeStream, _logger, _traceLevels); + _writeStream.writeBlob(Protocol.magic); + Util.currentProtocol.ice_writeMembers(_writeStream); + Util.currentProtocolEncoding.ice_writeMembers(_writeStream); + _writeStream.writeByte(Protocol.validateConnectionMsg); + _writeStream.writeByte(0); // Compression status (always zero for validate connection). + _writeStream.writeInt(Protocol.headerSize); // Message size. + TraceUtil.traceSend(_writeStream, _logger, _traceLevels); _writeStream.prepareWrite(); } @@ -2014,7 +2205,7 @@ namespace Ice { if(_readStream.size() == 0) { - _readStream.resize(IceInternal.Protocol.headerSize, true); + _readStream.resize(Protocol.headerSize); _readStream.pos(0); } @@ -2039,11 +2230,11 @@ namespace Ice observerFinishRead(_readStream.getBuffer()); } - Debug.Assert(_readStream.pos() == IceInternal.Protocol.headerSize); + Debug.Assert(_readStream.pos() == Protocol.headerSize); _readStream.pos(0); byte[] m = _readStream.readBlob(4); - if(m[0] != IceInternal.Protocol.magic[0] || m[1] != IceInternal.Protocol.magic[1] || - m[2] != IceInternal.Protocol.magic[2] || m[3] != IceInternal.Protocol.magic[3]) + if(m[0] != Protocol.magic[0] || m[1] != Protocol.magic[1] || + m[2] != Protocol.magic[2] || m[3] != Protocol.magic[3]) { BadMagicException ex = new BadMagicException(); ex.badMagic = m; @@ -2051,34 +2242,34 @@ namespace Ice } ProtocolVersion pv = new ProtocolVersion(); - pv.read__(_readStream); - IceInternal.Protocol.checkSupportedProtocol(pv); + pv.ice_readMembers(_readStream); + Protocol.checkSupportedProtocol(pv); EncodingVersion ev = new EncodingVersion(); - ev.read__(_readStream); - IceInternal.Protocol.checkSupportedProtocolEncoding(ev); + ev.ice_readMembers(_readStream); + Protocol.checkSupportedProtocolEncoding(ev); byte messageType = _readStream.readByte(); - if(messageType != IceInternal.Protocol.validateConnectionMsg) + if(messageType != Protocol.validateConnectionMsg) { throw new ConnectionNotValidatedException(); } _readStream.readByte(); // Ignore compression status for validate connection. int size = _readStream.readInt(); - if(size != IceInternal.Protocol.headerSize) + if(size != Protocol.headerSize) { throw new IllegalMessageSizeException(); } - IceInternal.TraceUtil.traceRecv(_readStream, _logger, _traceLevels); + TraceUtil.traceRecv(_readStream, _logger, _traceLevels); _validated = true; } } - _writeStream.resize(0, false); + _writeStream.resize(0); _writeStream.pos(0); - _readStream.resize(IceInternal.Protocol.headerSize, true); + _readStream.resize(Protocol.headerSize); _readStream.pos(0); _readHeader = true; @@ -2114,14 +2305,14 @@ namespace Ice if(_sendStreams.Count == 0) { - return IceInternal.SocketOperation.None; + return SocketOperation.None; } else if(_state == StateClosingPending && _writeStream.pos() == 0) { // Message wasn't sent, empty the _writeStream, we're not going to send more data. OutgoingMessage message = _sendStreams.First.Value; _writeStream.swap(message.stream); - return IceInternal.SocketOperation.None; + return SocketOperation.None; } Debug.Assert(!_writeStream.isEmpty() && _writeStream.pos() == _writeStream.size()); @@ -2161,7 +2352,7 @@ namespace Ice // if(_state >= StateClosingPending) { - return IceInternal.SocketOperation.None; + return SocketOperation.None; } // @@ -2169,20 +2360,13 @@ namespace Ice // message = _sendStreams.First.Value; Debug.Assert(!message.prepared); - IceInternal.BasicStream stream = message.stream; + OutputStream stream = message.stream; message.stream = doCompress(message.stream, message.compress); message.stream.prepareWrite(); message.prepared = true; - if(message.outAsync != null) - { - IceInternal.TraceUtil.trace("sending asynchronous request", stream, _logger, _traceLevels); - } - else - { - IceInternal.TraceUtil.traceSend(stream, _logger, _traceLevels); - } + TraceUtil.traceSend(stream, _logger, _traceLevels); _writeStream.swap(message.stream); // @@ -2220,14 +2404,14 @@ namespace Ice } } } - catch(Ice.LocalException ex) + catch(LocalException ex) { setState(StateClosed, ex); } - return IceInternal.SocketOperation.None; + return SocketOperation.None; } - private bool sendMessage(OutgoingMessage message) + private int sendMessage(OutgoingMessage message) { Debug.Assert(_state < StateClosed); @@ -2235,7 +2419,7 @@ namespace Ice { message.adopt(); _sendStreams.AddLast(message); - return false; + return OutgoingAsyncBase.AsyncStatusQueued; } // @@ -2246,20 +2430,13 @@ namespace Ice Debug.Assert(!message.prepared); - IceInternal.BasicStream stream = message.stream; + OutputStream stream = message.stream; message.stream = doCompress(stream, message.compress); message.stream.prepareWrite(); message.prepared = true; - if(message.outAsync != null) - { - IceInternal.TraceUtil.trace("sending asynchronous request", stream, _logger, _traceLevels); - } - else - { - IceInternal.TraceUtil.traceSend(stream, _logger, _traceLevels); - } + TraceUtil.traceSend(stream, _logger, _traceLevels); // // Send the message without blocking. @@ -2276,13 +2453,17 @@ namespace Ice observerFinishWrite(message.stream.getBuffer()); } - message.sent(); + int status = OutgoingAsyncBase.AsyncStatusSent; + if(message.sent()) + { + status = status | OutgoingAsyncBase.AsyncStatusInvokeSentCallback; + } if(_acmLastActivity > -1) { - _acmLastActivity = IceInternal.Time.currentMonotonicTimeMillis(); + _acmLastActivity = Time.currentMonotonicTimeMillis(); } - return true; + return status; } message.adopt(); @@ -2291,10 +2472,10 @@ namespace Ice _sendStreams.AddLast(message); scheduleTimeout(op); _threadPool.register(this, op); - return false; + return OutgoingAsyncBase.AsyncStatusQueued; } - private IceInternal.BasicStream doCompress(IceInternal.BasicStream uncompressed, bool compress) + private OutputStream doCompress(OutputStream uncompressed, bool compress) { if(_compressionSupported) { @@ -2303,14 +2484,18 @@ namespace Ice // // Do compression. // - IceInternal.BasicStream cstream = null; - if(uncompressed.compress(ref cstream, IceInternal.Protocol.headerSize, _compressionLevel)) + IceInternal.Buffer cbuf = BZip2.compress(uncompressed.getBuffer(), Protocol.headerSize, + _compressionLevel); + if(cbuf != null) { + OutputStream cstream = + new OutputStream(uncompressed.instance(), uncompressed.getEncoding(), cbuf, true); + // // Set compression status. // cstream.pos(9); - cstream.writeByte((byte)2); + cstream.writeByte(2); // // Write the size of the compressed stream into the header. @@ -2323,7 +2508,7 @@ namespace Ice // uncompressed stream -- we need this to trace requests correctly. // uncompressed.pos(9); - uncompressed.writeByte((byte)2); + uncompressed.writeByte(2); uncompressed.writeInt(cstream.size()); return cstream; @@ -2345,15 +2530,14 @@ namespace Ice private struct MessageInfo { - public IceInternal.BasicStream stream; + public InputStream stream; public int invokeNum; public int requestId; public byte compress; - public IceInternal.ServantManager servantManager; + public ServantManager servantManager; public ObjectAdapter adapter; - public IceInternal.OutgoingAsyncBase outAsync; - public Ice.AsyncCallback completedCallback; - public ConnectionCallback heartbeatCallback; + public OutgoingAsyncBase outAsync; + public HeartbeatCallback heartbeatCallback; public int messageDispatchCount; } @@ -2361,9 +2545,9 @@ namespace Ice { Debug.Assert(_state > StateNotValidated && _state < StateClosed); - info.stream = new IceInternal.BasicStream(_instance, Util.currentProtocolEncoding); + info.stream = new InputStream(_instance, Util.currentProtocolEncoding); _readStream.swap(info.stream); - _readStream.resize(IceInternal.Protocol.headerSize, true); + _readStream.resize(Protocol.headerSize); _readStream.pos(0); _readHeader = true; @@ -2385,11 +2569,13 @@ namespace Ice info.stream.pos(8); byte messageType = info.stream.readByte(); info.compress = info.stream.readByte(); - if(info.compress == (byte)2) + if(info.compress == 2) { if(_compressionSupported) { - info.stream = info.stream.uncompress(IceInternal.Protocol.headerSize, _messageSizeMax); + IceInternal.Buffer ubuf = BZip2.uncompress(info.stream.getBuffer(), Protocol.headerSize, + _messageSizeMax); + info.stream = new InputStream(info.stream.instance(), info.stream.getEncoding(), ubuf, true); } else { @@ -2398,13 +2584,13 @@ namespace Ice throw ex; } } - info.stream.pos(IceInternal.Protocol.headerSize); + info.stream.pos(Protocol.headerSize); switch(messageType) { - case IceInternal.Protocol.closeConnectionMsg: + case Protocol.closeConnectionMsg: { - IceInternal.TraceUtil.traceRecv(info.stream, _logger, _traceLevels); + TraceUtil.traceRecv(info.stream, _logger, _traceLevels); if(_endpoint.datagram()) { if(_warn) @@ -2417,7 +2603,7 @@ namespace Ice setState(StateClosingPending, new CloseConnectionException()); // - // Notify the the transceiver of the graceful connection closure. + // Notify the transceiver of the graceful connection closure. // int op = _transceiver.closing(false, _exception); if(op != 0) @@ -2429,17 +2615,17 @@ namespace Ice break; } - case IceInternal.Protocol.requestMsg: + case Protocol.requestMsg: { if(_state >= StateClosing) { - IceInternal.TraceUtil.trace("received request during closing\n" + - "(ignored by server, client will retry)", info.stream, _logger, - _traceLevels); + TraceUtil.trace("received request during closing\n" + + "(ignored by server, client will retry)", info.stream, _logger, + _traceLevels); } else { - IceInternal.TraceUtil.traceRecv(info.stream, _logger, _traceLevels); + TraceUtil.traceRecv(info.stream, _logger, _traceLevels); info.requestId = info.stream.readInt(); info.invokeNum = 1; info.servantManager = _servantManager; @@ -2449,17 +2635,17 @@ namespace Ice break; } - case IceInternal.Protocol.requestBatchMsg: + case Protocol.requestBatchMsg: { if(_state >= StateClosing) { - IceInternal.TraceUtil.trace("received batch request during closing\n" + - "(ignored by server, client will retry)", info.stream, _logger, - _traceLevels); + TraceUtil.trace("received batch request during closing\n" + + "(ignored by server, client will retry)", info.stream, _logger, + _traceLevels); } else { - IceInternal.TraceUtil.traceRecv(info.stream, _logger, _traceLevels); + TraceUtil.traceRecv(info.stream, _logger, _traceLevels); info.invokeNum = info.stream.readInt(); if(info.invokeNum < 0) { @@ -2473,16 +2659,15 @@ namespace Ice break; } - case IceInternal.Protocol.replyMsg: + case Protocol.replyMsg: { - IceInternal.TraceUtil.traceRecv(info.stream, _logger, _traceLevels); + TraceUtil.traceRecv(info.stream, _logger, _traceLevels); info.requestId = info.stream.readInt(); - IceInternal.OutgoingAsyncBase outAsync = null; - if(_asyncRequests.TryGetValue(info.requestId, out outAsync)) + if(_asyncRequests.TryGetValue(info.requestId, out info.outAsync)) { _asyncRequests.Remove(info.requestId); - outAsync.getIs().swap(info.stream); + info.outAsync.getIs().swap(info.stream); // // If we just received the reply for a request which isn't acknowledge as @@ -2490,30 +2675,29 @@ namespace Ice // will be processed once the write callback is invoked for the message. // OutgoingMessage message = _sendStreams.Count > 0 ? _sendStreams.First.Value : null; - if(message != null && message.outAsync == outAsync) + if(message != null && message.outAsync == info.outAsync) { message.receivedReply = true; } + else if(info.outAsync.response()) + { + ++info.messageDispatchCount; + } else { - info.completedCallback = outAsync.completed(); - if(info.completedCallback != null) - { - info.outAsync = outAsync; - ++info.messageDispatchCount; - } + info.outAsync = null; } - System.Threading.Monitor.PulseAll(this); // Notify threads blocked in close(false) + Monitor.PulseAll(this); // Notify threads blocked in close() } break; } - case IceInternal.Protocol.validateConnectionMsg: + case Protocol.validateConnectionMsg: { - IceInternal.TraceUtil.traceRecv(info.stream, _logger, _traceLevels); - if(_callback != null) + TraceUtil.traceRecv(info.stream, _logger, _traceLevels); + if(_heartbeatCallback != null) { - info.heartbeatCallback = _callback; + info.heartbeatCallback = _heartbeatCallback; ++info.messageDispatchCount; } break; @@ -2521,8 +2705,8 @@ namespace Ice default: { - IceInternal.TraceUtil.trace("received unknown message\n(invalid, closing connection)", - info.stream, _logger, _traceLevels); + TraceUtil.trace("received unknown message\n(invalid, closing connection)", + info.stream, _logger, _traceLevels); throw new UnknownMessageException(); } } @@ -2542,18 +2726,18 @@ namespace Ice } } - return _state == StateHolding ? IceInternal.SocketOperation.None : IceInternal.SocketOperation.Read; + return _state == StateHolding ? SocketOperation.None : SocketOperation.Read; } - private void invokeAll(IceInternal.BasicStream stream, int invokeNum, int requestId, byte compress, - IceInternal.ServantManager servantManager, ObjectAdapter adapter) + private void invokeAll(InputStream stream, int invokeNum, int requestId, byte compress, + ServantManager servantManager, ObjectAdapter adapter) { // // Note: In contrast to other private or protected methods, this // operation must be called *without* the mutex locked. // - IceInternal.Incoming inc = null; + Incoming inc = null; try { while(invokeNum > 0) @@ -2597,7 +2781,7 @@ namespace Ice int timeout; if(_state < StateActive) { - IceInternal.DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides(); + DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides(); if(defaultsAndOverrides.overrideConnectTimeout) { timeout = defaultsAndOverrides.overrideConnectTimeoutValue; @@ -2611,13 +2795,13 @@ namespace Ice { if(_readHeader) // No timeout for reading the header. { - status &= ~IceInternal.SocketOperation.Read; + status &= ~SocketOperation.Read; } timeout = _endpoint.timeout(); } else { - IceInternal.DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides(); + DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides(); if(defaultsAndOverrides.overrideCloseTimeout) { timeout = defaultsAndOverrides.overrideCloseTimeoutValue; @@ -2633,7 +2817,7 @@ namespace Ice return; } - if((status & IceInternal.SocketOperation.Read) != 0) + if((status & SocketOperation.Read) != 0) { if(_readTimeoutScheduled) { @@ -2642,7 +2826,7 @@ namespace Ice _timer.schedule(_readTimeout, timeout); _readTimeoutScheduled = true; } - if((status & (IceInternal.SocketOperation.Write | IceInternal.SocketOperation.Connect)) != 0) + if((status & (SocketOperation.Write | SocketOperation.Connect)) != 0) { if(_writeTimeoutScheduled) { @@ -2655,12 +2839,12 @@ namespace Ice private void unscheduleTimeout(int status) { - if((status & IceInternal.SocketOperation.Read) != 0 && _readTimeoutScheduled) + if((status & SocketOperation.Read) != 0 && _readTimeoutScheduled) { _timer.cancel(_readTimeout); _readTimeoutScheduled = false; } - if((status & (IceInternal.SocketOperation.Write | IceInternal.SocketOperation.Connect)) != 0 && + if((status & (SocketOperation.Write | SocketOperation.Connect)) != 0 && _writeTimeoutScheduled) { _timer.cancel(_writeTimeout); @@ -2679,13 +2863,16 @@ namespace Ice { _info = _transceiver.getInfo(); } - catch(Ice.LocalException) + catch(LocalException) { _info = new ConnectionInfo(); } - _info.connectionId = _endpoint.connectionId(); - _info.adapterName = _adapter != null ? _adapter.getName() : ""; - _info.incoming = _connector == null; + for(ConnectionInfo info = _info; info != null; info = info.underlying) + { + info.connectionId = _endpoint.connectionId(); + info.adapterName = _adapter != null ? _adapter.getName() : ""; + info.incoming = _connector == null; + } return _info; } @@ -2755,9 +2942,9 @@ namespace Ice _writeStreamPos = -1; } - private IceInternal.Incoming getIncoming(ObjectAdapter adapter, bool response, byte compress, int requestId) + private Incoming getIncoming(ObjectAdapter adapter, bool response, byte compress, int requestId) { - IceInternal.Incoming inc = null; + Incoming inc = null; if(_cacheBuffers) { @@ -2765,7 +2952,7 @@ namespace Ice { if(_incomingCache == null) { - inc = new IceInternal.Incoming(_instance, this, this, adapter, response, compress, requestId); + inc = new Incoming(_instance, this, this, adapter, response, compress, requestId); } else { @@ -2778,24 +2965,20 @@ namespace Ice } else { - inc = new IceInternal.Incoming(_instance, this, this, adapter, response, compress, requestId); + inc = new Incoming(_instance, this, this, adapter, response, compress, requestId); } return inc; } - private void reclaimIncoming(IceInternal.Incoming inc) + internal void reclaimIncoming(Incoming inc) { - if(_cacheBuffers) + if(_cacheBuffers && inc.reclaim()) { lock(_incomingCacheMutex) { inc.next = _incomingCache; _incomingCache = inc; - // - // Clear references to Ice objects as soon as possible. - // - _incomingCache.reclaim(); } } } @@ -2850,28 +3033,24 @@ namespace Ice private class OutgoingMessage { - internal OutgoingMessage(IceInternal.BasicStream stream, bool compress, bool adopt) + internal OutgoingMessage(OutputStream stream, bool compress, bool adopt) { this.stream = stream; this.compress = compress; - this._adopt = adopt; - this.isSent = false; - this.requestId = 0; + _adopt = adopt; } - internal OutgoingMessage(IceInternal.OutgoingAsyncBase outAsync, IceInternal.BasicStream stream, - bool compress, int requestId) + internal OutgoingMessage(OutgoingAsyncBase outAsync, OutputStream stream, bool compress, int requestId) { + this.outAsync = outAsync; this.stream = stream; this.compress = compress; - this.outAsync = outAsync; this.requestId = requestId; - this.isSent = false; } internal void canceled() { - Debug.Assert(outAsync != null); + Debug.Assert(outAsync != null); // Only requests can timeout. outAsync = null; } @@ -2879,8 +3058,7 @@ namespace Ice { if(_adopt) { - IceInternal.BasicStream stream = new IceInternal.BasicStream(this.stream.instance(), - Util.currentProtocolEncoding); + OutputStream stream = new OutputStream(this.stream.instance(), Util.currentProtocolEncoding); stream.swap(this.stream); this.stream = stream; _adopt = false; @@ -2889,56 +3067,58 @@ namespace Ice internal bool sent() { + stream = null; if(outAsync != null) { - sentCallback = outAsync.sent(); + invokeSent = outAsync.sent(); + return invokeSent ||receivedReply; } - return sentCallback != null || receivedReply; + return false; } internal void completed(LocalException ex) { if(outAsync != null) { - Ice.AsyncCallback cb = outAsync.completed(ex); - if(cb != null) + if(outAsync.exception(ex)) { - outAsync.invokeCompleted(cb); + outAsync.invokeException(); } } + stream = null; } - internal IceInternal.BasicStream stream; - internal IceInternal.OutgoingAsyncBase outAsync; - internal bool receivedReply; + internal OutputStream stream; + internal OutgoingAsyncBase outAsync; internal bool compress; internal int requestId; internal bool _adopt; internal bool prepared; internal bool isSent; - internal Ice.AsyncCallback sentCallback = null; + internal bool invokeSent; + internal bool receivedReply; } private Communicator _communicator; - private IceInternal.Instance _instance; - private IceInternal.ACMMonitor _monitor; - private IceInternal.Transceiver _transceiver; + private Instance _instance; + private ACMMonitor _monitor; + private Transceiver _transceiver; private string _desc; private string _type; - private IceInternal.Connector _connector; - private IceInternal.EndpointI _endpoint; + private Connector _connector; + private EndpointI _endpoint; private ObjectAdapter _adapter; - private IceInternal.ServantManager _servantManager; + private ServantManager _servantManager; private Logger _logger; - private IceInternal.TraceLevels _traceLevels; + private TraceLevels _traceLevels; private IceInternal.ThreadPool _threadPool; private IceInternal.Timer _timer; - private IceInternal.TimerTask _writeTimeout; + private TimerTask _writeTimeout; private bool _writeTimeoutScheduled; - private IceInternal.TimerTask _readTimeout; + private TimerTask _readTimeout; private bool _readTimeoutScheduled; private StartCallback _startCallback = null; @@ -2952,19 +3132,18 @@ namespace Ice private int _nextRequestId; - private Dictionary<int, IceInternal.OutgoingAsyncBase> _asyncRequests = - new Dictionary<int, IceInternal.OutgoingAsyncBase>(); + private Dictionary<int, OutgoingAsyncBase> _asyncRequests = new Dictionary<int, OutgoingAsyncBase>(); private LocalException _exception; private readonly int _messageSizeMax; - private IceInternal.BatchRequestQueue _batchRequestQueue; + private BatchRequestQueue _batchRequestQueue; private LinkedList<OutgoingMessage> _sendStreams = new LinkedList<OutgoingMessage>(); - private IceInternal.BasicStream _readStream; + private InputStream _readStream; private bool _readHeader; - private IceInternal.BasicStream _writeStream; + private OutputStream _writeStream; private ConnectionObserver _observer; private int _readStreamPos; @@ -2977,16 +3156,17 @@ namespace Ice private bool _initialized = false; private bool _validated = false; - private IceInternal.Incoming _incomingCache; + private Incoming _incomingCache; private object _incomingCacheMutex = new object(); private static bool _compressionSupported; private bool _cacheBuffers; - private Ice.ConnectionInfo _info; + private ConnectionInfo _info; - private Ice.ConnectionCallback _callback; + private CloseCallback _closeCallback; + private HeartbeatCallback _heartbeatCallback; private static ConnectionState[] connectionStateMap = new ConnectionState[] { ConnectionState.ConnectionStateValidating, // StateNotInitialized diff --git a/csharp/src/Ice/ConnectionRequestHandler.cs b/csharp/src/Ice/ConnectionRequestHandler.cs index 2cc8d18b9e1..cb598be294b 100644 --- a/csharp/src/Ice/ConnectionRequestHandler.cs +++ b/csharp/src/Ice/ConnectionRequestHandler.cs @@ -7,11 +7,6 @@ // // ********************************************************************** -using System; -using System.Diagnostics; -using System.Collections.Generic; -using Ice.Instrumentation; - namespace IceInternal { public class ConnectionRequestHandler : RequestHandler @@ -41,9 +36,9 @@ namespace IceInternal return this; } - public bool sendAsyncRequest(ProxyOutgoingAsyncBase outAsync, out Ice.AsyncCallback sentCallback) + public int sendAsyncRequest(ProxyOutgoingAsyncBase outAsync) { - return outAsync.invokeRemote(_connection, _compress, _response, out sentCallback); + return outAsync.invokeRemote(_connection, _compress, _response); } public void asyncRequestCanceled(OutgoingAsyncBase outAsync, Ice.LocalException ex) diff --git a/csharp/src/Ice/Connector.cs b/csharp/src/Ice/Connector.cs index b5c99d90f88..7f2f600b472 100644 --- a/csharp/src/Ice/Connector.cs +++ b/csharp/src/Ice/Connector.cs @@ -9,10 +9,6 @@ namespace IceInternal { - - using System; - using System.Net.Sockets; - public interface Connector { // diff --git a/csharp/src/Ice/DefaultsAndOverrides.cs b/csharp/src/Ice/DefaultsAndOverrides.cs index 3408d69b0af..17232c701dd 100644 --- a/csharp/src/Ice/DefaultsAndOverrides.cs +++ b/csharp/src/Ice/DefaultsAndOverrides.cs @@ -13,7 +13,6 @@ using System.Text; namespace IceInternal { - public sealed class DefaultsAndOverrides { internal DefaultsAndOverrides(Ice.Properties properties, Ice.Logger logger) @@ -107,28 +106,22 @@ namespace IceInternal overrideCloseTimeoutValue = -1; } -#if COMPACT - overrideCompress = false; - overrideCompressValue = false; -#else val = properties.getProperty("Ice.Override.Compress"); if(val.Length > 0) { overrideCompress = true; overrideCompressValue = properties.getPropertyAsInt("Ice.Override.Compress") > 0; - if(!BasicStream.compressible() && overrideCompressValue) + if(!BZip2.supported() && overrideCompressValue) { - string lib = AssemblyUtil.runtime_ == AssemblyUtil.Runtime.Mono ? "bzip2 library" : "bzip2.dll"; - Console.Error.WriteLine("warning: " + lib + " not found, Ice.Override.Compress ignored."); + Console.Error.WriteLine("warning: bzip2.dll not found, Ice.Override.Compress ignored."); overrideCompressValue = false; } } else { - overrideCompress = !BasicStream.compressible(); + overrideCompress = !BZip2.supported(); overrideCompressValue = false; } -#endif val = properties.getProperty("Ice.Override.Secure"); if(val.Length > 0) diff --git a/csharp/src/Ice/DictionaryBase.cs b/csharp/src/Ice/DictionaryBase.cs deleted file mode 100644 index 84ab9109f0d..00000000000 --- a/csharp/src/Ice/DictionaryBase.cs +++ /dev/null @@ -1,355 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -using System; -using System.Collections.Generic; - -namespace IceInternal -{ -#if !SILVERLIGHT - [Serializable] -#endif - public abstract class DictionaryBase<KT, VT> : System.Collections.IDictionary - { - protected Dictionary<KT, VT> dict_; - - public DictionaryBase() - { - dict_ = new Dictionary<KT, VT>(); - } - - public int Count - { - get - { - return dict_.Count; - } - } - - public void Clear() - { - dict_.Clear(); - } - - public void CopyTo(System.Array a__, int index) - { - if(a__ == null) - { - throw new ArgumentNullException("a__", "Cannot copy to null array"); - } - if(index < 0) - { - throw new ArgumentException("Array index cannot be less than zero", "index"); - } - if(index >= a__.Length) - { - throw new ArgumentException("Array index must less than array length"); - } - if(dict_.Count > a__.Length - index) - { - throw new ArgumentException("Insufficient room in target array beyond index"); - } - if(a__.Rank > 1) - { - throw new ArgumentException("Cannot copy to multidimensional array", "a__"); - } - Type t = a__.GetType().GetElementType(); - if(!t.IsAssignableFrom(typeof(System.Collections.DictionaryEntry))) - { - throw new ArgumentException("Cannot assign DictionaryEntry to target array", "a__"); - } - - IEnumerator<KeyValuePair<KT, VT>> e = dict_.GetEnumerator(); - while(e.MoveNext()) - { - a__.SetValue(new System.Collections.DictionaryEntry(e.Current.Key, e.Current.Value), index++); - } - } - - public override bool Equals(object other) - { - if(object.ReferenceEquals(this, other)) - { - return true; - } - if(other == null) - { - return false; - } - - try - { - DictionaryBase<KT, VT> d2 = (DictionaryBase<KT, VT>)other; - - if(dict_.Count != d2.dict_.Count) - { - return false; - } - if(Count == 0) - { - return true; - } - - // - // Compare both sets of keys. Keys are unique and non-null. - // - Dictionary<KT, VT>.KeyCollection keys1 = dict_.Keys; - Dictionary<KT, VT>.KeyCollection keys2 = d2.dict_.Keys; - KT[] ka1 = new KT[dict_.Count]; - KT[] ka2 = new KT[d2.dict_.Count]; - keys1.CopyTo(ka1, 0); - keys2.CopyTo(ka2, 0); - Array.Sort(ka1); - Array.Sort(ka2); - - for(int i = 0; i < ka1.Length; ++i) - { - if(!Equals(ka1[i], ka2[i])) - { - return false; - } - if(!Equals(dict_[ka1[i]], d2.dict_[ka1[i]])) - { - return false; - } - } - - return true; - } - catch(System.Exception) - { - return false; - } - } - - public static bool operator==(DictionaryBase<KT, VT> lhs__, DictionaryBase<KT, VT> rhs__) - { - return Equals(lhs__, rhs__); - } - - public static bool operator!=(DictionaryBase<KT, VT> lhs__, DictionaryBase<KT, VT> rhs__) - { - return !Equals(lhs__, rhs__); - } - - public override int GetHashCode() - { - int h = 5381; - foreach(KeyValuePair<KT, VT> kvp in dict_) - { - IceInternal.HashUtil.hashAdd(ref h, kvp.Key); - IceInternal.HashUtil.hashAdd(ref h, kvp.Value); - } - return h; - } - - public class CEnumerator : System.Collections.IDictionaryEnumerator - { - public CEnumerator(IEnumerator<KeyValuePair<KT, VT>> e) - { - _e = e; - } - - public bool MoveNext() - { - return _e.MoveNext(); - } - - public object Current - { - get - { - return new System.Collections.DictionaryEntry(_e.Current.Key, _e.Current.Value); - } - } - - public System.Collections.DictionaryEntry Entry - { - get - { - return new System.Collections.DictionaryEntry(_e.Current.Key, _e.Current.Value); - } - } - - public object Key - { - get - { - return _e.Current.Key; - } - } - - public object Value - { - get - { - return _e.Current.Value; - } - } - - public void Reset() - { - _e.Reset(); - } - - private IEnumerator<KeyValuePair<KT, VT>> _e; - } - - public System.Collections.IEnumerator GetEnumerator() - { - return new CEnumerator(dict_.GetEnumerator()); - } - - public bool IsFixedSize - { - get - { - return false; - } - } - - public bool IsReadOnly - { - get - { - return false; - } - } - - public bool IsSynchronized - { - get - { - return false; - } - } - - public object SyncRoot - { - get - { - return this; - } - } - - public VT this[KT key] - { - get - { - return dict_[key]; - } - set - { - dict_[key] = value; - } - } - - public System.Collections.ICollection Keys - { - get - { - return dict_.Keys; - } - } - - public System.Collections.ICollection Values - { - get - { - return dict_.Values; - } - } - - public void Add(KT key, VT value) - { - try - { - dict_.Add(key, value); - } - catch(ArgumentException) - { - // Ignore. - } - } - - public void Remove(KT key) - { - dict_.Remove(key); - } - - public bool Contains(KT key) - { - return dict_.ContainsKey(key); - } - - public void Add(object key, object value) - { - checkKeyType(key); - checkValueType(value); - Add((KT)key, (VT)value); - } - - public void Remove(object key) - { - checkKeyType(key); - Remove((KT)key); - } - - public bool Contains(object key) - { - return dict_.ContainsKey((KT)key); - } - - System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() - { - return new CEnumerator(dict_.GetEnumerator()); - } - - public object this[object key] - { - get - { - checkKeyType(key); - return dict_[(KT)key]; - } - set - { - checkKeyType(key); - checkValueType(value); - dict_[(KT)key] = (VT)value; - } - } - - private void checkKeyType(object o) - { - if(o != null && !(o is KT)) - { - throw new ArgumentException("Cannot use a key of type " + o.GetType().ToString() - + " for a dictionary with key type " + typeof(KT).ToString()); - } - } - - private void checkValueType(object o) - { - if(o != null && !(o is KT)) - { - throw new ArgumentException("Cannot use a value of type " + o.GetType().ToString() - + " for a dictionary with value type " + typeof(VT).ToString()); - } - } - } -} - -namespace Ice -{ - [Obsolete("This class is deprecated.")] - public abstract class DictionaryBase<KT, VT> : IceInternal.DictionaryBase<KT, VT> - { - } -} diff --git a/csharp/src/Ice/DispatchInterceptor.cs b/csharp/src/Ice/DispatchInterceptor.cs index fe1041dc422..5626f01e309 100644 --- a/csharp/src/Ice/DispatchInterceptor.cs +++ b/csharp/src/Ice/DispatchInterceptor.cs @@ -7,8 +7,6 @@ // // ********************************************************************** -using System.Diagnostics; - namespace Ice { /// <summary> @@ -19,50 +17,21 @@ namespace Ice /// A dispatch interceptor is useful particularly to automatically retry requests /// that have failed due to a recoverable error condition. /// </summary> - public abstract class DispatchInterceptor : Ice.ObjectImpl + public abstract class DispatchInterceptor : ObjectImpl { /// <summary> /// Called by the Ice run time to dispatch an incoming request. The implementation /// of <code>dispatch</code> must dispatch the request to the actual servant. /// </summary> /// <param name="request">The details of the incoming request.</param> - /// <returns>For synchronous dispatch, the return value must be whatever is - /// returned ice_dispatch. For asynchronous dispatch, the return - /// value must be DispatchAsync.</returns> - public abstract DispatchStatus + /// <returns>The task if dispatched asynchronously, null otherwise.</returns> + public abstract System.Threading.Tasks.Task<OutputStream> dispatch(Request request); - public override DispatchStatus - dispatch__(IceInternal.Incoming inc, Current current) + public override System.Threading.Tasks.Task<OutputStream> + iceDispatch(IceInternal.Incoming inc, Current current) { - try - { - DispatchStatus status = dispatch(inc); - if(status != DispatchStatus.DispatchAsync) - { - // - // Make sure 'inc' owns the connection etc. - // - inc.killAsync(); - } - return status; - } - catch(ResponseSentException) - { - return DispatchStatus.DispatchAsync; - } - catch(System.Exception) - { - try - { - inc.killAsync(); - throw; - } - catch(ResponseSentException) - { - return DispatchStatus.DispatchAsync; - } - } + return dispatch(inc); } } } diff --git a/csharp/src/Ice/EndpointFactory.cs b/csharp/src/Ice/EndpointFactory.cs index 7ffc76f3574..3bc4e979ea4 100644 --- a/csharp/src/Ice/EndpointFactory.cs +++ b/csharp/src/Ice/EndpointFactory.cs @@ -16,10 +16,10 @@ namespace IceInternal short type(); string protocol(); EndpointI create(List<string> args, bool oaEndpoint); - EndpointI read(BasicStream s); + EndpointI read(Ice.InputStream s); void destroy(); - EndpointFactory clone(ProtocolInstance instance); + EndpointFactory clone(ProtocolInstance instance, EndpointFactory del); } } diff --git a/csharp/src/Ice/EndpointFactoryManager.cs b/csharp/src/Ice/EndpointFactoryManager.cs index 9f34564f9c4..7dc55c990b5 100644 --- a/csharp/src/Ice/EndpointFactoryManager.cs +++ b/csharp/src/Ice/EndpointFactoryManager.cs @@ -9,16 +9,14 @@ namespace IceInternal { - using System.Collections.Generic; using System.Diagnostics; - using System.Text.RegularExpressions; public sealed class EndpointFactoryManager { internal EndpointFactoryManager(Instance instance) { - instance_ = instance; + _instance = instance; _factories = new List<EndpointFactory>(); } @@ -28,7 +26,7 @@ namespace IceInternal { for(int i = 0; i < _factories.Count; i++) { - EndpointFactory f = (EndpointFactory)_factories[i]; + EndpointFactory f = _factories[i]; if(f.type() == factory.type()) { Debug.Assert(false); @@ -44,7 +42,7 @@ namespace IceInternal { for(int i = 0; i < _factories.Count; i++) { - EndpointFactory f = (EndpointFactory)_factories[i]; + EndpointFactory f = _factories[i]; if(f.type() == type) { return f; @@ -77,7 +75,7 @@ namespace IceInternal if(protocol.Equals("default")) { - protocol = instance_.defaultsAndOverrides().defaultProtocol; + protocol = _instance.defaultsAndOverrides().defaultProtocol; } EndpointFactory factory = null; @@ -109,7 +107,7 @@ namespace IceInternal /* EndpointI e = f.create(s.Substring(m.Index + m.Length), oaEndpoint); - BasicStream bs = new BasicStream(instance_, true); + BasicStream bs = new BasicStream(_instance, true); e.streamWrite(bs); Buffer buf = bs.getBuffer(); buf.b.position(0); @@ -142,16 +140,16 @@ namespace IceInternal // and ask the factory to read the endpoint data from that stream to create // the actual endpoint. // - BasicStream bs = new BasicStream(instance_, Ice.Util.currentProtocolEncoding); - bs.writeShort(ue.type()); - ue.streamWrite(bs); - Buffer buf = bs.getBuffer(); - buf.b.position(0); - buf.b.limit(buf.size()); - bs.readShort(); // type - bs.startReadEncaps(); - EndpointI e = factory.read(bs); - bs.endReadEncaps(); + Ice.OutputStream os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + os.writeShort(ue.type()); + ue.streamWrite(os); + Ice.InputStream iss = + new Ice.InputStream(_instance, Ice.Util.currentProtocolEncoding, os.getBuffer(), true); + iss.pos(0); + iss.readShort(); // type + iss.startEncapsulation(); + EndpointI e = factory.read(iss); + iss.endEncapsulation(); return e; } return ue; // Endpoint is opaque, but we don't have a factory for its type. @@ -160,7 +158,7 @@ namespace IceInternal return null; } - public EndpointI read(BasicStream s) + public EndpointI read(Ice.InputStream s) { lock(this) { @@ -169,7 +167,7 @@ namespace IceInternal EndpointFactory factory = get(type); EndpointI e = null; - s.startReadEncaps(); + s.startEncapsulation(); if(factory != null) { @@ -180,7 +178,7 @@ namespace IceInternal e = new OpaqueEndpointI(type, s); } - s.endReadEncaps(); + s.endEncapsulation(); return e; } @@ -196,7 +194,7 @@ namespace IceInternal _factories.Clear(); } - private readonly Instance instance_; + private readonly Instance _instance; private readonly List<EndpointFactory> _factories; } diff --git a/csharp/src/Ice/EndpointHostResolver.cs b/csharp/src/Ice/EndpointHostResolver.cs index f0c05af8989..11e35c7b8c7 100644 --- a/csharp/src/Ice/EndpointHostResolver.cs +++ b/csharp/src/Ice/EndpointHostResolver.cs @@ -7,10 +7,8 @@ // // ********************************************************************** -#if !SILVERLIGHT namespace IceInternal { - using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; @@ -25,16 +23,8 @@ namespace IceInternal _preferIPv6 = instance.preferIPv6(); _thread = new HelperThread(this); updateObserver(); - if(instance.initializationData().properties.getProperty("Ice.ThreadPriority").Length > 0) - { - ThreadPriority priority = IceInternal.Util.stringToThreadPriority( - instance.initializationData().properties.getProperty("Ice.ThreadPriority")); - _thread.Start(priority); - } - else - { - _thread.Start(ThreadPriority.Normal); - } + _thread.Start(Util.stringToThreadPriority( + instance.initializationData().properties.getProperty("Ice.ThreadPriority"))); } public void resolve(string host, int port, Ice.EndpointSelectionType selType, IPEndpointI endpoint, @@ -85,7 +75,7 @@ namespace IceInternal } _queue.AddLast(entry); - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } } @@ -95,7 +85,7 @@ namespace IceInternal { Debug.Assert(!_destroyed); _destroyed = true; - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } } @@ -118,7 +108,7 @@ namespace IceInternal { while(!_destroyed && _queue.Count == 0) { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } if(_destroyed) @@ -133,7 +123,7 @@ namespace IceInternal if(threadObserver != null) { - threadObserver.stateChanged(Ice.Instrumentation.ThreadState.ThreadStateIdle, + threadObserver.stateChanged(Ice.Instrumentation.ThreadState.ThreadStateIdle, Ice.Instrumentation.ThreadState.ThreadStateInUseForOther); } @@ -151,19 +141,21 @@ namespace IceInternal } } - r.callback.connectors(r.endpoint.connectors(Network.getAddresses(r.host, - r.port, - protocol, - r.selType, - _preferIPv6, - true), - networkProxy)); + List<EndPoint> addrs = Network.getAddresses(r.host, r.port, protocol, r.selType, _preferIPv6, true); + if(r.observer != null) + { + r.observer.detach(); + r.observer = null; + } + + r.callback.connectors(r.endpoint.connectors(addrs, networkProxy)); } catch(Ice.LocalException ex) { if(r.observer != null) { - r.observer.failed(ex.ice_name()); + r.observer.failed(ex.ice_id()); + r.observer.detach(); } r.callback.exception(ex); } @@ -171,13 +163,9 @@ namespace IceInternal { if(threadObserver != null) { - threadObserver.stateChanged(Ice.Instrumentation.ThreadState.ThreadStateInUseForOther, + threadObserver.stateChanged(Ice.Instrumentation.ThreadState.ThreadStateInUseForOther, Ice.Instrumentation.ThreadState.ThreadStateIdle); } - if(r.observer != null) - { - r.observer.detach(); - } } } @@ -186,7 +174,7 @@ namespace IceInternal Ice.CommunicatorDestroyedException ex = new Ice.CommunicatorDestroyedException(); if(entry.observer != null) { - entry.observer.failed(ex.ice_name()); + entry.observer.failed(ex.ice_id()); entry.observer.detach(); } entry.callback.exception(ex); @@ -207,16 +195,16 @@ namespace IceInternal Ice.Instrumentation.CommunicatorObserver obsv = _instance.initializationData().observer; if(obsv != null) { - _observer = obsv.getThreadObserver("Communicator", - _thread.getName(), - Ice.Instrumentation.ThreadState.ThreadStateIdle, + _observer = obsv.getThreadObserver("Communicator", + _thread.getName(), + Ice.Instrumentation.ThreadState.ThreadStateIdle, _observer); if(_observer != null) { _observer.attach(); } } - } + } } private class ResolveEntry @@ -289,4 +277,3 @@ namespace IceInternal private HelperThread _thread; } } -#endif diff --git a/csharp/src/Ice/EndpointI.cs b/csharp/src/Ice/EndpointI.cs index 2729dc03935..8d1e8aeb60a 100644 --- a/csharp/src/Ice/EndpointI.cs +++ b/csharp/src/Ice/EndpointI.cs @@ -12,7 +12,6 @@ namespace IceInternal using System.Collections.Generic; using System.Diagnostics; - using System.Net; using System; public interface EndpointI_connectors @@ -21,7 +20,7 @@ namespace IceInternal void exception(Ice.LocalException ex); } - public abstract class EndpointI : Ice.Endpoint, System.IComparable<EndpointI> + public abstract class EndpointI : Ice.Endpoint, IComparable<EndpointI> { public override string ToString() { @@ -60,7 +59,13 @@ namespace IceInternal // // Marshal the endpoint. // - public abstract void streamWrite(BasicStream s); + virtual public void streamWrite(Ice.OutputStream s) + { + s.startEncapsulation(); + streamWriteImpl(s); + s.endEncapsulation(); + } + public abstract void streamWriteImpl(Ice.OutputStream s); // // Return the endpoint type. diff --git a/csharp/src/Ice/EventHandler.cs b/csharp/src/Ice/EventHandler.cs index e45a29d7a5e..486c665f27d 100644 --- a/csharp/src/Ice/EventHandler.cs +++ b/csharp/src/Ice/EventHandler.cs @@ -10,8 +10,6 @@ namespace IceInternal { -using System; - public abstract class EventHandler { // diff --git a/csharp/src/Ice/Exception.cs b/csharp/src/Ice/Exception.cs index 1b3859ffeb0..7bed0aa2c6f 100644 --- a/csharp/src/Ice/Exception.cs +++ b/csharp/src/Ice/Exception.cs @@ -7,7 +7,7 @@ // // ********************************************************************** -using System.Diagnostics; +using System; using System.Globalization; using System.Runtime.Serialization; @@ -35,10 +35,8 @@ namespace Ice /// <summary> /// Base class for Ice exceptions. /// </summary> -#if !SILVERLIGHT - [System.Serializable] -#endif - public abstract class Exception : System.Exception, System.ICloneable + [Serializable] + public abstract class Exception : System.Exception, ICloneable { /// <summary> /// Creates and returns a copy of this exception. @@ -61,20 +59,29 @@ namespace Ice /// <param name="ex">The inner exception.</param> public Exception(System.Exception ex) : base("", ex) {} -#if !SILVERLIGHT /// <summary> /// Initializes a new instance of the exception with serialized data. /// </summary> /// <param name="info">Holds the serialized object data about the exception being thrown.</param> /// <param name="context">Contains contextual information about the source or destination.</param> protected Exception(SerializationInfo info, StreamingContext context) : base(info, context) {} -#endif /// <summary> + /// ice_name() is deprecated, use ice_id() instead. /// Returns the name of this exception. /// </summary> /// <returns>The name of this exception.</returns> - public abstract string ice_name(); + [Obsolete("ice_name() is deprecated, use ice_id() instead.")] + public string ice_name() + { + return ice_id().Substring(2); + } + + /// <summary> + /// Returns the type id of this exception. + /// </summary> + /// <returns>The type id of this exception.</returns> + public abstract string ice_id(); /// <summary> /// Returns a string representation of this exception, including @@ -121,9 +128,7 @@ namespace Ice /// <summary> /// Base class for local exceptions. /// </summary> -#if !SILVERLIGHT - [System.Serializable] -#endif + [Serializable] public abstract class LocalException : Exception { /// <summary> @@ -138,22 +143,18 @@ namespace Ice /// <param name="ex">The inner exception.</param> public LocalException(System.Exception ex) : base(ex) {} -#if !SILVERLIGHT /// <summary> /// Initializes a new instance of the exception with serialized data. /// </summary> /// <param name="info">Holds the serialized object data about the exception being thrown.</param> /// <param name="context">Contains contextual information about the source or destination.</param> protected LocalException(SerializationInfo info, StreamingContext context) : base(info, context) {} -#endif } /// <summary> /// Base class for Ice run-time exceptions. /// </summary> -#if !SILVERLIGHT - [System.Serializable] -#endif + [Serializable] public abstract class SystemException : Exception { /// <summary> @@ -168,22 +169,18 @@ namespace Ice /// <param name="ex">The inner exception.</param> public SystemException(System.Exception ex) : base(ex) {} -#if !SILVERLIGHT /// <summary> /// Initializes a new instance of the exception with serialized data. /// </summary> /// <param name="info">Holds the serialized object data about the exception being thrown.</param> /// <param name="context">Contains contextual information about the source or destination.</param> protected SystemException(SerializationInfo info, StreamingContext context) : base(info, context) {} -#endif } /// <summary> /// Base class for Slice user exceptions. /// </summary> -#if !SILVERLIGHT - [System.Serializable] -#endif + [Serializable] public abstract class UserException : Exception { /// <summary> @@ -198,66 +195,40 @@ namespace Ice /// <param name="ex">The inner exception.</param> public UserException(System.Exception ex) : base(ex) {} -#if !SILVERLIGHT /// <summary> /// Initializes a new instance of the exception with serialized data. /// </summary> /// <param name="info">Holds the serialized object data about the exception being thrown.</param> /// <param name="context">Contains contextual information about the source or destination.</param> protected UserException(SerializationInfo info, StreamingContext context) : base(info, context) {} -#endif - - public virtual void write__(IceInternal.BasicStream os__) - { - os__.startWriteException(null); - writeImpl__(os__); - os__.endWriteException(); - } - - public virtual void read__(IceInternal.BasicStream is__) - { - is__.startReadException(); - readImpl__(is__); - is__.endReadException(false); - } - public virtual void write__(OutputStream os__) + public virtual void iceWrite(OutputStream ostr) { - os__.startException(null); - writeImpl__(os__); - os__.endException(); + ostr.startException(null); + iceWriteImpl(ostr); + ostr.endException(); } - public virtual void read__(InputStream is__) + public virtual void iceRead(InputStream istr) { - is__.startException(); - readImpl__(is__); - is__.endException(false); + istr.startException(); + iceReadImpl(istr); + istr.endException(false); } - public virtual bool usesClasses__() + public virtual bool iceUsesClasses() { return false; } - protected abstract void writeImpl__(IceInternal.BasicStream os__); - protected abstract void readImpl__(IceInternal.BasicStream is__); - - protected virtual void writeImpl__(OutputStream os__) - { - throw new MarshalException("exception was not generated with stream support"); - } - - protected virtual void readImpl__(InputStream is__) - { - throw new MarshalException("exception was not generated with stream support"); - } + protected abstract void iceWriteImpl(OutputStream ostr); + protected abstract void iceReadImpl(InputStream istr); } } namespace IceInternal { - public class RetryException : System.Exception + public class RetryException : Exception { public RetryException(Ice.LocalException ex) { diff --git a/csharp/src/Ice/HashSet.cs b/csharp/src/Ice/HashSet.cs deleted file mode 100644 index cf600d702b1..00000000000 --- a/csharp/src/Ice/HashSet.cs +++ /dev/null @@ -1,114 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -#if COMPACT - -// -// System.Collections.Generic.HashSet is not available in the .NET Compact Framework. -// This class is a minimal implementation that provides only the methods required by -// Ice internals. -// -using System; -using System.Collections.Generic; - -namespace IceInternal -{ - public class HashSet<T> : ICollection<T> - { - public HashSet() - { - entries_ = new Dictionary<T, bool>(); - } - - public HashSet(int capacity) - { - entries_ = new Dictionary<T, bool>(capacity); - } - - void ICollection<T>.Add(T item) - { - try - { - entries_.Add(item, false); - } - catch(ArgumentException) - { - // Item already present. - } - } - - public bool Add(T item) - { - try - { - entries_.Add(item, false); - } - catch(ArgumentException) - { - return false; // Item already present. - } - return true; - } - - public void Clear() - { - entries_.Clear(); - } - - public bool Contains(T item) - { - return entries_.ContainsKey(item); - } - - public void CopyTo(T[] a, int idx) - { - entries_.Keys.CopyTo(a, idx); - } - - public void CopyTo(T[] a) - { - entries_.Keys.CopyTo(a, 0); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return entries_.Keys.GetEnumerator(); - } - - public IEnumerator<T> GetEnumerator() - { - return entries_.Keys.GetEnumerator(); - } - - public bool Remove(T item) - { - return entries_.Remove(item); - } - - public int Count - { - get - { - return entries_.Count; - } - } - - public bool IsReadOnly - { - get - { - return false; - } - } - - private Dictionary<T, bool> entries_; - } -} - -#endif diff --git a/csharp/src/Ice/HttpParser.cs b/csharp/src/Ice/HttpParser.cs index 8a55088e10a..d941af018ef 100644 --- a/csharp/src/Ice/HttpParser.cs +++ b/csharp/src/Ice/HttpParser.cs @@ -9,7 +9,6 @@ namespace IceInternal { - using System; using System.Diagnostics; using System.Collections.Generic; using System.Text; @@ -55,7 +54,7 @@ namespace IceInternal Response }; - internal int isCompleteMessage(IceInternal.ByteBuffer buf, int begin, int end) + internal int isCompleteMessage(ByteBuffer buf, int begin, int end) { byte[] raw = buf.rawBytes(); int p = begin; @@ -100,7 +99,7 @@ namespace IceInternal return -1; } - internal bool parse(IceInternal.ByteBuffer buf, int begin, int end) + internal bool parse(ByteBuffer buf, int begin, int end) { byte[] raw = buf.rawBytes(); int p = begin; @@ -544,7 +543,7 @@ namespace IceInternal _versionMinor = 0; } _versionMinor *= 10; - _versionMinor += (int)(c - '0'); + _versionMinor += (c - '0'); break; } case State.Response: @@ -602,7 +601,7 @@ namespace IceInternal _status = 0; } _status *= 10; - _status += (int)(c - '0'); + _status += (c - '0'); break; } case State.ResponseReasonStart: diff --git a/csharp/src/Ice/IPEndpointI.cs b/csharp/src/Ice/IPEndpointI.cs index 7110ffc5eea..16fa7944a27 100644 --- a/csharp/src/Ice/IPEndpointI.cs +++ b/csharp/src/Ice/IPEndpointI.cs @@ -11,7 +11,6 @@ namespace IceInternal { using System.Collections.Generic; - using System.Diagnostics; using System.Globalization; using System.Net; using System; @@ -38,7 +37,7 @@ namespace IceInternal _hashInitialized = false; } - public IPEndpointI(ProtocolInstance instance, BasicStream s) + public IPEndpointI(ProtocolInstance instance, Ice.InputStream s) { instance_ = instance; host_ = s.readString(); @@ -80,13 +79,6 @@ namespace IceInternal return info; } - public override void streamWrite(BasicStream s) - { - s.startWriteEncaps(); - streamWriteImpl(s); - s.endWriteEncaps(); - } - public override short type() { return instance_.type(); @@ -121,11 +113,7 @@ namespace IceInternal public override void connectors_async(Ice.EndpointSelectionType selType, EndpointI_connectors callback) { -#if SILVERLIGHT - callback.connectors(connectors(selType)); -#else instance_.resolve(host_, port_, selType, this, callback); -#endif } public override List<EndpointI> expand() @@ -167,15 +155,6 @@ namespace IceInternal return connectors; } -#if SILVERLIGHT - public List<Connector> connectors(Ice.EndpointSelectionType selType) - { - return connectors(Network.getAddresses(host_, port_, instance_.protocolSupport(), selType, - instance_.preferIPv6(), false), - instance_.networkProxy()); - } -#endif - public override string options() { // @@ -262,17 +241,7 @@ namespace IceInternal return string.Compare(connectionId_, p.connectionId_, StringComparison.Ordinal); } - public string host() - { - return host_; - } - - public int port() - { - return port_; - } - - public virtual void streamWriteImpl(BasicStream s) + public override void streamWriteImpl(Ice.OutputStream s) { s.writeString(host_); s.writeInt(port_); @@ -356,9 +325,9 @@ namespace IceInternal try { - port_ = System.Int32.Parse(argument, CultureInfo.InvariantCulture); + port_ = int.Parse(argument, CultureInfo.InvariantCulture); } - catch(System.FormatException ex) + catch(FormatException ex) { Ice.EndpointParseException e = new Ice.EndpointParseException(ex); e.str = "invalid port value `" + argument + "' in endpoint " + endpoint; diff --git a/csharp/src/Ice/ImplicitContextI.cs b/csharp/src/Ice/ImplicitContextI.cs index d6498f5ae1c..67262f2b955 100644 --- a/csharp/src/Ice/ImplicitContextI.cs +++ b/csharp/src/Ice/ImplicitContextI.cs @@ -9,7 +9,6 @@ namespace Ice { - using System.Collections; using System.Collections.Generic; using System.Threading; @@ -34,8 +33,7 @@ namespace Ice } else { - throw new Ice.InitializationException( - "'" + kind + "' is not a valid value for Ice.ImplicitContext"); + throw new InitializationException("'" + kind + "' is not a valid value for Ice.ImplicitContext"); } } @@ -46,8 +44,7 @@ namespace Ice public abstract string put(string key, string value); public abstract string remove(string key); - abstract public void write(Dictionary<string, string> prxContext, - IceInternal.BasicStream os); + abstract public void write(Dictionary<string, string> prxContext, OutputStream os); abstract internal Dictionary<string, string> combine(Dictionary<string, string> prxContext); } @@ -158,7 +155,7 @@ namespace Ice } } - public override void write(Dictionary<string, string> prxContext, IceInternal.BasicStream os) + public override void write(Dictionary<string, string> prxContext, OutputStream os) { if(prxContext.Count == 0) { @@ -211,7 +208,7 @@ namespace Ice { if(_map.ContainsKey(currentThread)) { - threadContext = (Dictionary<string, string>)_map[currentThread]; + threadContext = _map[currentThread]; } } @@ -345,7 +342,7 @@ namespace Ice return val; } - public override void write(Dictionary<string, string> prxContext, IceInternal.BasicStream os) + public override void write(Dictionary<string, string> prxContext, OutputStream os) { Dictionary<string, string> threadContext = null; lock(this) diff --git a/csharp/src/Ice/Incoming.cs b/csharp/src/Ice/Incoming.cs index 05c935004b6..1b1a15ba824 100644 --- a/csharp/src/Ice/Incoming.cs +++ b/csharp/src/Ice/Incoming.cs @@ -7,302 +7,551 @@ // // ********************************************************************** -namespace IceInternal +namespace Ice +{ + +public interface MarshaledResult { + OutputStream getOutputStream(Current current); +}; + +} +namespace IceInternal +{ + using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Globalization; + using System.Threading.Tasks; - public class IncomingBase + public class Incoming : Ice.Request { - protected internal IncomingBase(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, - Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) + public Incoming(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, + Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) + { + _instance = instance; + _responseHandler = handler; + _response = response; + _compress = compress; + + _current = new Ice.Current(); + _current.id = new Ice.Identity(); + _current.adapter = adapter; + _current.con = connection; + _current.requestId = requestId; + + _cookie = null; + } + + // + // These functions allow this object to be reused, rather than reallocated. + // + public void reset(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, + Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) + { + _instance = instance; + _responseHandler = handler; + _response = response; + _compress = compress; + + // + // Don't recycle the Current object, because servants may keep a reference to it. + // + _current = new Ice.Current(); + _current.id = new Ice.Identity(); + _current.adapter = adapter; + _current.con = connection; + _current.requestId = requestId; + + Debug.Assert(_cookie == null); + + _inParamPos = -1; + } + + public bool reclaim() { - instance_ = instance; - responseHandler_ = handler; - response_ = response; - compress_ = compress; - if(response_) + if(_responseHandler != null) // Async dispatch not ready for being reclaimed! { - os_ = new BasicStream(instance, Ice.Util.currentProtocolEncoding); + return false; } - current_ = new Ice.Current(); - current_.id = new Ice.Identity(); - current_.adapter = adapter; - current_.con = connection; - current_.requestId = requestId; + _current = null; + _servant = null; + _locator = null; + _cookie = null; + + //_observer = null; + Debug.Assert(_observer == null); + + _os = null; + _is = null; + + //_responseHandler = null; + Debug.Assert(_responseHandler == null); - cookie_ = null; + _inParamPos = -1; + + return true; } - protected internal IncomingBase(IncomingBase inc) // Adopts the argument. It must not be used afterwards. + public Ice.Current getCurrent() { + return _current; + } + + public void invoke(ServantManager servantManager, Ice.InputStream stream) + { + _is = stream; + + int start = _is.pos(); + // - // We don't change current_ as it's exposed by Ice::Request. + // Read the current. // - current_ = inc.current_; + _current.id.ice_readMembers(_is); // - // Deep copy + // For compatibility with the old FacetPath. // - if(inc.interceptorAsyncCallbackList_ != null) + string[] facetPath = _is.readStringSeq(); + if(facetPath.Length > 0) { - // - // Copy, not just reference - // - interceptorAsyncCallbackList_ = - new List<Ice.DispatchInterceptorAsyncCallback>(inc.interceptorAsyncCallbackList_); + if(facetPath.Length > 1) + { + throw new Ice.MarshalException(); + } + _current.facet = facetPath[0]; + } + else + { + _current.facet = ""; } - adopt(inc); - } - - internal void - adopt(IncomingBase inc) - { - instance_ = inc.instance_; - //inc.instance_ = null; // Don't reset instance_. + _current.operation = _is.readString(); + _current.mode = (Ice.OperationMode)_is.readByte(); + _current.ctx = new Dictionary<string, string>(); + int sz = _is.readSize(); + while(sz-- > 0) + { + string first = _is.readString(); + string second = _is.readString(); + _current.ctx[first] = second; + } - observer_ = inc.observer_; - inc.observer_ = null; + Ice.Instrumentation.CommunicatorObserver obsv = _instance.initializationData().observer; + if(obsv != null) + { + // Read the encapsulation size. + int size = _is.readInt(); + _is.pos(_is.pos() - 4); - servant_ = inc.servant_; - inc.servant_ = null; + _observer = obsv.getDispatchObserver(_current, _is.pos() - start + size); + if(_observer != null) + { + _observer.attach(); + } + } - locator_ = inc.locator_; - inc.locator_ = null; + // + // Don't put the code above into the try block below. Exceptions + // in the code above are considered fatal, and must propagate to + // the caller of this operation. + // - cookie_ = inc.cookie_; - inc.cookie_ = null; + if(servantManager != null) + { + _servant = servantManager.findServant(_current.id, _current.facet); + if(_servant == null) + { + _locator = servantManager.findServantLocator(_current.id.category); + if(_locator == null && _current.id.category.Length > 0) + { + _locator = servantManager.findServantLocator(""); + } - response_ = inc.response_; - inc.response_ = false; + if(_locator != null) + { + Debug.Assert(_locator != null); + try + { + _servant = _locator.locate(_current, out _cookie); + } + catch(Exception ex) + { + skipReadParams(); // Required for batch requests. + handleException(ex, false); + return; + } + } + } + } - compress_ = inc.compress_; - inc.compress_ = 0; + if(_servant == null) + { + try + { + if(servantManager != null && servantManager.hasServant(_current.id)) + { + throw new Ice.FacetNotExistException(_current.id, _current.facet, _current.operation); + } + else + { + throw new Ice.ObjectNotExistException(_current.id, _current.facet, _current.operation); + } + } + catch(Exception ex) + { + skipReadParams(); // Required for batch requests + handleException(ex, false); + return; + } + } - // - // Adopt the stream - it creates less garbage. - // - os_ = inc.os_; - inc.os_ = null; + try + { + Task<Ice.OutputStream> task = _servant.iceDispatch(this, _current); + if(task == null) + { + completed(null, false); + } + else + { + if(task.IsCompleted) + { + _os = task.GetAwaiter().GetResult(); // Get the response + completed(null, false); + } + else + { + task.ContinueWith((Task<Ice.OutputStream> t) => + { + try + { + _os = t.GetAwaiter().GetResult(); + completed(null, true); // true = asynchronous + } + catch(Exception ex) + { + completed(ex, true); // true = asynchronous + } + }, TaskContinuationOptions.ExecuteSynchronously); + } + } + } + catch(Exception ex) + { + completed(ex, false); + } + } - responseHandler_ = inc.responseHandler_; - inc.responseHandler_ = null; + public Task<Ice.OutputStream> setResult(Ice.OutputStream os) + { + _os = os; + return null; // Response is cached in the Incoming to not have to create unecessary Task } - public BasicStream startWriteParams__(Ice.FormatType format) + public Task<Ice.OutputStream> setMarshaledResult<T>(T result) where T : Ice.MarshaledResult { - if(!response_) + if(result == null) { - throw new Ice.MarshalException("can't marshal out parameters for oneway dispatch"); + _os = default(T).getOutputStream(_current); } - - Debug.Assert(os_.size() == Protocol.headerSize + 4); // Reply status position. - os_.writeByte((byte)0); - os_.startWriteEncaps(current_.encoding, format); - return os_; + else + { + _os = result.getOutputStream(_current); + } + return null; // Response is cached in the Incoming to not have to create unecessary Task } - public void endWriteParams__(bool ok) + public Task<Ice.OutputStream> setResultTask<R>(Task<R> task, Action<Ice.OutputStream, R> write) { - if(!ok && observer_ != null) + if(task == null) { - observer_.userException(); + _os = startWriteParams(); + write(_os, default(R)); + endWriteParams(_os); + return null; // Response is cached in the Incoming to not have to create unecessary Task } - - if(response_) + else { - int save = os_.pos(); - os_.pos(Protocol.headerSize + 4); // Reply status position. - os_.writeByte(ok ? ReplyStatus.replyOK : ReplyStatus.replyUserException); - os_.pos(save); - os_.endWriteEncaps(); + return task.ContinueWith((Task<R> t) => + { + var result = t.GetAwaiter().GetResult(); + var os = startWriteParams(); + write(os, result); + endWriteParams(os); + return Task.FromResult(os); + }, TaskContinuationOptions.ExecuteSynchronously).Unwrap(); } } - public void writeEmptyParams__() + public Task<Ice.OutputStream> setResultTask(Task task) { - if(response_) + if(task == null) + { + _os = writeEmptyParams(); + return null; + } + else { - Debug.Assert(os_.size() == Protocol.headerSize + 4); // Reply status position. - os_.writeByte(ReplyStatus.replyOK); - os_.writeEmptyEncaps(current_.encoding); + return task.ContinueWith((Task t) => + { + t.GetAwaiter().GetResult(); + return Task.FromResult(writeEmptyParams()); + }, TaskContinuationOptions.ExecuteSynchronously).Unwrap(); } } - public void writeParamEncaps__(byte[] v, bool ok) + public Task<Ice.OutputStream> setMarshaledResultTask<T>(Task<T> task) where T : Ice.MarshaledResult { - if(!ok && observer_ != null) + if(task == null) + { + _os = default(T).getOutputStream(_current); + return null; // Response is cached in the Incoming to not have to create unecessary Task + } + else { - observer_.userException(); + return task.ContinueWith((Task<T> t) => + { + return Task.FromResult(t.GetAwaiter().GetResult().getOutputStream(_current)); + }, TaskContinuationOptions.ExecuteSynchronously).Unwrap(); } + } - if(response_) + public void completed(Exception exc, bool amd) + { + try { - Debug.Assert(os_.size() == Protocol.headerSize + 4); // Reply status position. - os_.writeByte(ok ? ReplyStatus.replyOK : ReplyStatus.replyUserException); - if(v == null || v.Length == 0) + if(_locator != null) + { + Debug.Assert(_locator != null && _servant != null); + try + { + _locator.finished(_current, _servant, _cookie); + } + catch(Exception ex) + { + handleException(ex, amd); + return; + } + } + + Debug.Assert(_responseHandler != null); + + if(exc != null) { - os_.writeEmptyEncaps(current_.encoding); + handleException(exc, amd); + } + else if(_response) + { + if(_observer != null) + { + _observer.reply(_os.size() - Protocol.headerSize - 4); + } + _responseHandler.sendResponse(_current.requestId, _os, _compress, amd); } else { - os_.writeEncaps(v); + _responseHandler.sendNoResponse(); } } + catch(Ice.LocalException ex) + { + _responseHandler.invokeException(_current.requestId, ex, 1, amd); + } + finally + { + if(_observer != null) + { + _observer.detach(); + _observer = null; + } + _responseHandler = null; + } } - public void writeUserException__(Ice.UserException ex, Ice.FormatType format) + public void startOver() { - BasicStream os__ = startWriteParams__(format); - os__.writeUserException(ex); - endWriteParams__(false); + if(_inParamPos == -1) + { + // + // That's the first startOver, so almost nothing to do + // + _inParamPos = _is.pos(); + } + else + { + // + // Let's rewind _is, reset _os + // + _is.pos(_inParamPos); + _os = null; + } } - // - // These functions allow this object to be reused, rather than reallocated. - // - public virtual void reset(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, - Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) + public void skipReadParams() { - instance_ = instance; + // + // Remember the encoding used by the input parameters, we'll + // encode the response parameters with the same encoding. + // + _current.encoding = _is.skipEncapsulation(); + } + public Ice.InputStream startReadParams() + { // - // Don't recycle the Current object, because servants may keep a reference to it. + // Remember the encoding used by the input parameters, we'll + // encode the response parameters with the same encoding. // - current_ = new Ice.Current(); - current_.id = new Ice.Identity(); - current_.adapter = adapter; - current_.con = connection; - current_.requestId = requestId; + _current.encoding = _is.startEncapsulation(); + return _is; + } - Debug.Assert(cookie_ == null); + public void endReadParams() + { + _is.endEncapsulation(); + } - response_ = response; + public void readEmptyParams() + { + _current.encoding = _is.skipEmptyEncapsulation(); + } - compress_ = compress; + public byte[] readParamEncaps() + { + return _is.readEncapsulation(out _current.encoding); + } - if(response_ && os_ == null) - { - os_ = new BasicStream(instance, Ice.Util.currentProtocolEncoding); - } + public void setFormat(Ice.FormatType format) + { + _format = format; + } - responseHandler_ = handler; - interceptorAsyncCallbackList_ = null; + static public Ice.OutputStream createResponseOutputStream(Ice.Current current) + { + var os = new Ice.OutputStream(current.adapter.getCommunicator(), Ice.Util.currentProtocolEncoding); + os.writeBlob(Protocol.replyHdr); + os.writeInt(current.requestId); + os.writeByte(ReplyStatus.replyOK); + return os; } - public virtual void reclaim() + public Ice.OutputStream startWriteParams() { - servant_ = null; + if(!_response) + { + throw new Ice.MarshalException("can't marshal out parameters for oneway dispatch"); + } - locator_ = null; + var os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + os.writeBlob(Protocol.replyHdr); + os.writeInt(_current.requestId); + os.writeByte(ReplyStatus.replyOK); + os.startEncapsulation(_current.encoding, _format); + return os; + } - cookie_ = null; + public void endWriteParams(Ice.OutputStream os) + { + if(_response) + { + os.endEncapsulation(); + } + } - observer_ = null; + public Ice.OutputStream writeEmptyParams() + { + if(_response) + { + var os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + os.writeBlob(Protocol.replyHdr); + os.writeInt(_current.requestId); + os.writeByte(ReplyStatus.replyOK); + os.writeEmptyEncapsulation(_current.encoding); + return os; + } + else + { + return null; + } + } - if(os_ != null) + public Ice.OutputStream writeParamEncaps(byte[] v, bool ok) + { + if(!ok && _observer != null) { - os_.reset(); + _observer.userException(); } - interceptorAsyncCallbackList_ = null; + if(_response) + { + var os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + os.writeBlob(Protocol.replyHdr); + os.writeInt(_current.requestId); + os.writeByte(ok ? ReplyStatus.replyOK : ReplyStatus.replyUserException); + if(v == null || v.Length == 0) + { + os.writeEmptyEncapsulation(_current.encoding); + } + else + { + os.writeEncapsulation(v); + } + return os; + } + else + { + return null; + } } - protected internal void warning__(System.Exception ex) + private void warning(Exception ex) { - Debug.Assert(instance_ != null); + Debug.Assert(_instance != null); using(StringWriter sw = new StringWriter(CultureInfo.CurrentCulture)) { IceUtilInternal.OutputBase output = new IceUtilInternal.OutputBase(sw); + Ice.ToStringMode toStringMode = _instance.toStringMode(); output.setUseTab(false); output.print("dispatch exception:"); - output.print("\nidentity: " + instance_.identityToString(current_.id)); - output.print("\nfacet: " + IceUtilInternal.StringUtil.escapeString(current_.facet, "")); - output.print("\noperation: " + current_.operation); - if(current_.con != null) + output.print("\nidentity: " + Ice.Util.identityToString(_current.id, toStringMode)); + output.print("\nfacet: " + IceUtilInternal.StringUtil.escapeString(_current.facet, "", toStringMode)); + output.print("\noperation: " + _current.operation); + if(_current.con != null) { try { - Ice.ConnectionInfo connInfo = current_.con.getInfo(); - if(connInfo is Ice.IPConnectionInfo) + for(Ice.ConnectionInfo p = _current.con.getInfo(); p != null; p = p.underlying) { - Ice.IPConnectionInfo ipConnInfo = (Ice.IPConnectionInfo)connInfo; - output.print("\nremote host: " + ipConnInfo.remoteAddress + " remote port: " + - ipConnInfo.remotePort.ToString()); + Ice.IPConnectionInfo ipinfo = p as Ice.IPConnectionInfo; + output.print("\nremote host: " + ipinfo.remoteAddress + " remote port: " + ipinfo.remotePort); } } catch(Ice.LocalException) { - // Ignore. } } output.print("\n"); output.print(ex.ToString()); - instance_.initializationData().logger.warning(sw.ToString()); + _instance.initializationData().logger.warning(sw.ToString()); } } - protected bool servantLocatorFinished__(bool amd) + private void handleException(Exception exc, bool amd) { - Debug.Assert(locator_ != null && servant_ != null); - try - { - locator_.finished(current_, servant_, cookie_); - return true; - } - catch(Ice.UserException ex) - { - Debug.Assert(responseHandler_ != null); - - if(observer_ != null) - { - observer_.userException(); - } + Debug.Assert(_responseHandler != null); - // - // The operation may have already marshaled a reply; we must overwrite that reply. - // - if(response_) - { - os_.resize(Protocol.headerSize + 4, false); // Reply status position. - os_.writeByte(ReplyStatus.replyUserException); - os_.startWriteEncaps(current_.encoding, Ice.FormatType.DefaultFormat); - os_.writeUserException(ex); - os_.endWriteEncaps(); - if(observer_ != null) - { - observer_.reply(os_.size() - Protocol.headerSize - 4); - } - responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); - } - else - { - responseHandler_.sendNoResponse(); - } - - if(observer_ != null) + if(exc is Ice.SystemException) + { + if(_responseHandler.systemException(_current.requestId, (Ice.SystemException)exc, amd)) { - observer_.detach(); - observer_ = null; + return; } - responseHandler_ = null; - } - catch(System.Exception ex) - { - handleException__(ex, amd); } - return false; - } - - protected internal void handleException__(System.Exception exc, bool amd) - { - Debug.Assert(responseHandler_ != null); try { @@ -312,632 +561,282 @@ namespace IceInternal { if(ex.id == null || ex.id.name == null || ex.id.name.Length == 0) { - ex.id = current_.id; + ex.id = _current.id; } if(ex.facet == null || ex.facet.Length == 0) { - ex.facet = current_.facet; + ex.facet = _current.facet; } if(ex.operation == null || ex.operation.Length == 0) { - ex.operation = current_.operation; + ex.operation = _current.operation; } - if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 1) + if(_instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 1) { - warning__(ex); + warning(ex); } - if(observer_ != null) + if(_observer != null) { - observer_.failed(ex.ice_name()); + _observer.failed(ex.ice_id()); } - if(response_) + if(_response) { - os_.resize(Protocol.headerSize + 4, false); // Reply status position. + _os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + _os.writeBlob(Protocol.replyHdr); + _os.writeInt(_current.requestId); if(ex is Ice.ObjectNotExistException) { - os_.writeByte(ReplyStatus.replyObjectNotExist); + _os.writeByte(ReplyStatus.replyObjectNotExist); } else if(ex is Ice.FacetNotExistException) { - os_.writeByte(ReplyStatus.replyFacetNotExist); + _os.writeByte(ReplyStatus.replyFacetNotExist); } else if(ex is Ice.OperationNotExistException) { - os_.writeByte(ReplyStatus.replyOperationNotExist); + _os.writeByte(ReplyStatus.replyOperationNotExist); } else { Debug.Assert(false); } - ex.id.write__(os_); + ex.id.ice_writeMembers(_os); // // For compatibility with the old FacetPath. // if(ex.facet == null || ex.facet.Length == 0) { - os_.writeStringSeq(null); + _os.writeStringSeq(null); } else { string[] facetPath2 = { ex.facet }; - os_.writeStringSeq(facetPath2); + _os.writeStringSeq(facetPath2); } - os_.writeString(ex.operation); + _os.writeString(ex.operation); - if(observer_ != null) + if(_observer != null) { - observer_.reply(os_.size() - Protocol.headerSize - 4); + _observer.reply(_os.size() - Protocol.headerSize - 4); } - responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); + _responseHandler.sendResponse(_current.requestId, _os, _compress, amd); } else { - responseHandler_.sendNoResponse(); + _responseHandler.sendNoResponse(); } } catch(Ice.UnknownLocalException ex) { - if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + if(_instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { - warning__(ex); + warning(ex); } - if(observer_ != null) + if(_observer != null) { - observer_.failed(ex.ice_name()); + _observer.failed(ex.ice_id()); } - if(response_) + if(_response) { - os_.resize(Protocol.headerSize + 4, false); // Reply status position. - os_.writeByte(ReplyStatus.replyUnknownLocalException); - os_.writeString(ex.unknown); - if(observer_ != null) + _os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + _os.writeBlob(Protocol.replyHdr); + _os.writeInt(_current.requestId); + _os.writeByte(ReplyStatus.replyUnknownLocalException); + _os.writeString(ex.unknown); + if(_observer != null) { - observer_.reply(os_.size() - Protocol.headerSize - 4); + _observer.reply(_os.size() - Protocol.headerSize - 4); } - responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); + _responseHandler.sendResponse(_current.requestId, _os, _compress, amd); } else { - responseHandler_.sendNoResponse(); + _responseHandler.sendNoResponse(); } } catch(Ice.UnknownUserException ex) { - if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + if(_instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { - warning__(ex); + warning(ex); } - if(observer_ != null) + if(_observer != null) { - observer_.failed(ex.ice_name()); + _observer.failed(ex.ice_id()); } - if(response_) + if(_response) { - os_.resize(Protocol.headerSize + 4, false); // Reply status position. - os_.writeByte(ReplyStatus.replyUnknownUserException); - os_.writeString(ex.unknown); - if(observer_ != null) + _os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + _os.writeBlob(Protocol.replyHdr); + _os.writeInt(_current.requestId); + _os.writeByte(ReplyStatus.replyUnknownUserException); + _os.writeString(ex.unknown); + if(_observer != null) { - observer_.reply(os_.size() - Protocol.headerSize - 4); + _observer.reply(_os.size() - Protocol.headerSize - 4); } - responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); + Debug.Assert(_responseHandler != null && _current != null); + _responseHandler.sendResponse(_current.requestId, _os, _compress, amd); } else { - responseHandler_.sendNoResponse(); + _responseHandler.sendNoResponse(); } } catch(Ice.UnknownException ex) { - if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + if(_instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { - warning__(ex); + warning(ex); } - if(observer_ != null) + if(_observer != null) { - observer_.failed(ex.ice_name()); + _observer.failed(ex.ice_id()); } - if(response_) + if(_response) { - os_.resize(Protocol.headerSize + 4, false); // Reply status position. - os_.writeByte(ReplyStatus.replyUnknownException); - os_.writeString(ex.unknown); - if(observer_ != null) + _os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + _os.writeBlob(Protocol.replyHdr); + _os.writeInt(_current.requestId); + _os.writeByte(ReplyStatus.replyUnknownException); + _os.writeString(ex.unknown); + if(_observer != null) { - observer_.reply(os_.size() - Protocol.headerSize - 4); + _observer.reply(_os.size() - Protocol.headerSize - 4); } - responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); + _responseHandler.sendResponse(_current.requestId, _os, _compress, amd); } else { - responseHandler_.sendNoResponse(); + _responseHandler.sendNoResponse(); } } catch(Ice.UserException ex) { - if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) - { - warning__(ex); - } - - if(observer_ != null) + if(_observer != null) { - observer_.failed(ex.ice_name()); + _observer.userException(); } - if(response_) + if(_response) { - os_.resize(Protocol.headerSize + 4, false); // Reply status position. - os_.writeByte(ReplyStatus.replyUnknownUserException); - os_.writeString(ex.ice_name() + "\n" + ex.StackTrace); - if(observer_ != null) + _os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + _os.writeBlob(Protocol.replyHdr); + _os.writeInt(_current.requestId); + _os.writeByte(ReplyStatus.replyUserException); + _os.startEncapsulation(_current.encoding, _format); + _os.writeException(ex); + _os.endEncapsulation(); + if(_observer != null) { - observer_.reply(os_.size() - Protocol.headerSize - 4); + _observer.reply(_os.size() - Protocol.headerSize - 4); } - responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); + _responseHandler.sendResponse(_current.requestId, _os, _compress, false); } else { - responseHandler_.sendNoResponse(); + _responseHandler.sendNoResponse(); } } catch(Ice.Exception ex) { - if(ex is Ice.SystemException) - { - if(responseHandler_.systemException(current_.requestId, (Ice.SystemException)ex, amd)) - { - return; - } - } - - if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + if(_instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { - warning__(ex); + warning(ex); } - if(observer_ != null) + if(_observer != null) { - observer_.failed(ex.ice_name()); + _observer.failed(ex.ice_id()); } - if(response_) + if(_response) { - os_.resize(Protocol.headerSize + 4, false); // Reply status position. - os_.writeByte(ReplyStatus.replyUnknownLocalException); - os_.writeString(ex.ice_name() + "\n" + ex.StackTrace); - if(observer_ != null) + _os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + _os.writeBlob(Protocol.replyHdr); + _os.writeInt(_current.requestId); + _os.writeByte(ReplyStatus.replyUnknownLocalException); + _os.writeString(ex.ice_id() + "\n" + ex.StackTrace); + if(_observer != null) { - observer_.reply(os_.size() - Protocol.headerSize - 4); + _observer.reply(_os.size() - Protocol.headerSize - 4); } - responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); + _responseHandler.sendResponse(_current.requestId, _os, _compress, amd); } else { - responseHandler_.sendNoResponse(); + _responseHandler.sendNoResponse(); } } - catch(System.Exception ex) + catch(Exception ex) { - if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + if(_instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { - warning__(ex); + warning(ex); } - if(observer_ != null) + if(_observer != null) { - observer_.failed(ex.GetType().FullName); + _observer.failed(ex.GetType().FullName); } - if(response_) + if(_response) { - os_.resize(Protocol.headerSize + 4, false); // Reply status position. - os_.writeByte(ReplyStatus.replyUnknownException); - os_.writeString(ex.ToString()); - if(observer_ != null) + _os = new Ice.OutputStream(_instance, Ice.Util.currentProtocolEncoding); + _os.writeBlob(Protocol.replyHdr); + _os.writeInt(_current.requestId); + _os.writeByte(ReplyStatus.replyUnknownException); + _os.writeString(ex.ToString()); + if(_observer != null) { - observer_.reply(os_.size() - Protocol.headerSize - 4); + _observer.reply(_os.size() - Protocol.headerSize - 4); } - responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); + _responseHandler.sendResponse(_current.requestId, _os, _compress, amd); } else { - responseHandler_.sendNoResponse(); + _responseHandler.sendNoResponse(); } } - if(observer_ != null) + if(_observer != null) { - observer_.detach(); - observer_ = null; + _observer.detach(); + _observer = null; } - responseHandler_ = null; + _responseHandler = null; } - protected internal Instance instance_; - protected internal Ice.Current current_; - protected internal Ice.Object servant_; - protected internal Ice.ServantLocator locator_; - protected internal System.Object cookie_; - protected internal Ice.Instrumentation.DispatchObserver observer_; - - protected internal bool response_; - protected internal byte compress_; + private Instance _instance; + private Ice.Current _current; + private Ice.Object _servant; + private Ice.ServantLocator _locator; + private object _cookie; + private Ice.Instrumentation.DispatchObserver _observer; + private ResponseHandler _responseHandler; - protected internal BasicStream os_; + private bool _response; + private byte _compress; + private Ice.FormatType _format = Ice.FormatType.DefaultFormat; - protected ResponseHandler responseHandler_; + private Ice.OutputStream _os; + private Ice.InputStream _is; - protected List<Ice.DispatchInterceptorAsyncCallback> interceptorAsyncCallbackList_; - } - - sealed public class Incoming : IncomingBase, Ice.Request - { - public Incoming(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, - Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) - : base(instance, handler, connection, adapter, response, compress, requestId) - { - // - // Prepare the response if necessary. - // - if(response) - { - os_.writeBlob(IceInternal.Protocol.replyHdr); - - // - // Add the request ID. - // - os_.writeInt(requestId); - } - } - - public Ice.Current - getCurrent() - { - return current_; - } - - // - // These functions allow this object to be reused, rather than reallocated. - // - public override void reset(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, - Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) - { - _cb = null; - _inParamPos = -1; - - base.reset(instance, handler, connection, adapter, response, compress, requestId); - - // - // Prepare the response if necessary. - // - if(response) - { - os_.writeBlob(IceInternal.Protocol.replyHdr); - - // - // Add the request ID. - // - os_.writeInt(requestId); - } - } - - public override void reclaim() - { - _cb = null; - _inParamPos = -1; - - base.reclaim(); - } - - public void invoke(ServantManager servantManager, BasicStream stream) - { - _is = stream; - - int start = _is.pos(); - - // - // Read the current. - // - current_.id.read__(_is); - - // - // For compatibility with the old FacetPath. - // - string[] facetPath = _is.readStringSeq(); - if(facetPath.Length > 0) - { - if(facetPath.Length > 1) - { - throw new Ice.MarshalException(); - } - current_.facet = facetPath[0]; - } - else - { - current_.facet = ""; - } - - current_.operation = _is.readString(); - current_.mode = (Ice.OperationMode)(int)_is.readByte(); - current_.ctx = new Dictionary<string, string>(); - int sz = _is.readSize(); - while(sz-- > 0) - { - string first = _is.readString(); - string second = _is.readString(); - current_.ctx[first] = second; - } - - Ice.Instrumentation.CommunicatorObserver obsv = instance_.initializationData().observer; - if(obsv != null) - { - // Read the encapsulation size. - int size = _is.readInt(); - _is.pos(_is.pos() - 4); - - observer_ = obsv.getDispatchObserver(current_, _is.pos() - start + size); - if(observer_ != null) - { - observer_.attach(); - } - } - - // - // Don't put the code above into the try block below. Exceptions - // in the code above are considered fatal, and must propagate to - // the caller of this operation. - // - - if(servantManager != null) - { - servant_ = servantManager.findServant(current_.id, current_.facet); - if(servant_ == null) - { - locator_ = servantManager.findServantLocator(current_.id.category); - if(locator_ == null && current_.id.category.Length > 0) - { - locator_ = servantManager.findServantLocator(""); - } - - if(locator_ != null) - { - try - { - servant_ = locator_.locate(current_, out cookie_); - } - catch(Ice.UserException ex) - { - Ice.EncodingVersion encoding = _is.skipEncaps(); // Required for batch requests. - - if(observer_ != null) - { - observer_.userException(); - } - - if(response_) - { - os_.writeByte(ReplyStatus.replyUserException); - os_.startWriteEncaps(encoding, Ice.FormatType.DefaultFormat); - os_.writeUserException(ex); - os_.endWriteEncaps(); - if(observer_ != null) - { - observer_.reply(os_.size() - Protocol.headerSize - 4); - } - responseHandler_.sendResponse(current_.requestId, os_, compress_, false); - } - else - { - responseHandler_.sendNoResponse(); - } - - if(observer_ != null) - { - observer_.detach(); - observer_ = null; - } - responseHandler_ = null; - return; - } - catch(System.Exception ex) - { - _is.skipEncaps(); // Required for batch requests. - handleException__(ex, false); - return; - } - } - } - } - - try - { - if(servant_ != null) - { - // - // DispatchAsync is a "pseudo dispatch status", used internally only - // to indicate async dispatch. - // - if(servant_.dispatch__(this, current_) == Ice.DispatchStatus.DispatchAsync) - { - // - // If this was an asynchronous dispatch, we're done here. - // - return; - } - - if(locator_ != null && !servantLocatorFinished__(false)) - { - return; - } - } - else - { - // - // Skip the input parameters, this is required for reading - // the next batch request if dispatching batch requests. - // - _is.skipEncaps(); - - if(servantManager != null && servantManager.hasServant(current_.id)) - { - throw new Ice.FacetNotExistException(current_.id, current_.facet, current_.operation); - } - else - { - throw new Ice.ObjectNotExistException(current_.id, current_.facet, current_.operation); - } - } - } - catch(System.Exception ex) - { - if(servant_ != null && locator_ != null && !servantLocatorFinished__(false)) - { - return; - } - handleException__(ex, false); - return; - } - - // - // Don't put the code below into the try block above. Exceptions - // in the code below are considered fatal, and must propagate to - // the caller of this operation. - // - - Debug.Assert(responseHandler_ != null); - - if(response_) - { - if(observer_ != null) - { - observer_.reply(os_.size() - Protocol.headerSize - 4); - } - responseHandler_.sendResponse(current_.requestId, os_, compress_, false); - } - else - { - responseHandler_.sendNoResponse(); - } - - if(observer_ != null) - { - observer_.detach(); - observer_ = null; - } - responseHandler_ = null; - } - - public void push(Ice.DispatchInterceptorAsyncCallback cb) - { - if(interceptorAsyncCallbackList_ == null) - { - interceptorAsyncCallbackList_ = new List<Ice.DispatchInterceptorAsyncCallback>(); - } - - interceptorAsyncCallbackList_.Insert(0, cb); - } - - public void pop() - { - Debug.Assert(interceptorAsyncCallbackList_ != null); - interceptorAsyncCallbackList_.RemoveAt(0); - } - - public void startOver() - { - if(_inParamPos == -1) - { - // - // That's the first startOver, so almost nothing to do - // - _inParamPos = _is.pos(); - } - else - { - killAsync(); - - // - // Let's rewind _is and clean-up os_ - // - _is.pos(_inParamPos); - if(response_) - { - os_.resize(Protocol.headerSize + 4, false); - } - } - } - - public void killAsync() - { - // - // Always runs in the dispatch thread - // - if(_cb != null) - { - // - // May raise ResponseSentException - // - _cb.deactivate__(this); - _cb = null; - } - } - - public BasicStream startReadParams() - { - // - // Remember the encoding used by the input parameters, we'll - // encode the response parameters with the same encoding. - // - current_.encoding = _is.startReadEncaps(); - return _is; - } - - public void endReadParams() - { - _is.endReadEncaps(); - } - - public void readEmptyParams() - { - current_.encoding = _is.skipEmptyEncaps(); - } - - public byte[] readParamEncaps() - { - return _is.readEncaps(out current_.encoding); - } - - internal void setActive(IncomingAsync cb) - { - Debug.Assert(_cb == null); - _cb = cb; - } - - internal bool isRetriable() - { - return _inParamPos != -1; - } + private int _inParamPos = -1; public Incoming next; // For use by Connection. - - private BasicStream _is; - - private IncomingAsync _cb; - private int _inParamPos = -1; } - } diff --git a/csharp/src/Ice/IncomingAsync.cs b/csharp/src/Ice/IncomingAsync.cs deleted file mode 100644 index 6a553b73f4c..00000000000 --- a/csharp/src/Ice/IncomingAsync.cs +++ /dev/null @@ -1,247 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -namespace IceInternal -{ - - using System.Diagnostics; - - public class IncomingAsync : IncomingBase, Ice.AMDCallback - { - public IncomingAsync(Incoming inc) - : base(inc) - { - _retriable = inc.isRetriable(); - if(_retriable) - { - inc.setActive(this); - _active = true; - } - } - - virtual public void ice_exception(System.Exception ex) - { - // - // Only call exception__ if this incoming is not retriable or if - // all the interceptors return true and no response has been sent - // yet. - // - - if(_retriable) - { - try - { - if(interceptorAsyncCallbackList_ != null) - { - foreach(Ice.DispatchInterceptorAsyncCallback cb in interceptorAsyncCallbackList_) - { - if(cb.exception(ex) == false) - { - return; - } - } - } - } - catch(System.Exception) - { - return; - } - - lock(this) - { - if(!_active) - { - return; - } - _active = false; - } - } - - if(responseHandler_ != null) - { - exception__(ex); - } - else - { - // - // Response has already been sent. - // - if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) - { - warning__(ex); - } - } - } - - internal void deactivate__(Incoming inc) - { - Debug.Assert(_retriable); - - lock(this) - { - if(!_active) - { - // - // Since __deactivate can only be called on an active object, - // this means the response has already been sent (see validateXXX below) - // - throw new Ice.ResponseSentException(); - } - _active = false; - } - inc.adopt(this); - } - - protected void response__() - { - try - { - if(locator_ != null && !servantLocatorFinished__(true)) - { - return; - } - - Debug.Assert(responseHandler_ != null); - - if(response_) - { - if(observer_ != null) - { - observer_.reply(os_.size() - Protocol.headerSize - 4); - } - responseHandler_.sendResponse(current_.requestId, os_, compress_, true); - } - else - { - responseHandler_.sendNoResponse(); - } - - if(observer_ != null) - { - observer_.detach(); - observer_ = null; - } - responseHandler_ = null; - } - catch(Ice.LocalException ex) - { - responseHandler_.invokeException(current_.requestId, ex, 1, true); - } - } - - protected internal void exception__(System.Exception exc) - { - try - { - if(locator_ != null && !servantLocatorFinished__(true)) - { - return; - } - - handleException__(exc, true); - } - catch(Ice.LocalException ex) - { - responseHandler_.invokeException(current_.requestId, ex, 1, true); - } - } - - protected internal BasicStream getOs__() - { - return os_; - } - - protected bool validateResponse__(bool ok) - { - // - // Only returns true if this incoming is not retriable or if all - // the interceptors return true and no response has been sent - // yet. Upon getting a true return value, the caller should send - // the response. - // - - if(_retriable) - { - try - { - if(interceptorAsyncCallbackList_ != null) - { - foreach(Ice.DispatchInterceptorAsyncCallback cb in interceptorAsyncCallbackList_) - { - if(cb.response(ok) == false) - { - return false; - } - } - } - } - catch(System.Exception) - { - return false; - } - - lock(this) - { - if(!_active) - { - return false; - } - _active = false; - } - } - return true; - } - - private readonly bool _retriable; - private bool _active = false; // only meaningful when _retriable == true - } -} - -namespace Ice -{ - - /// <summary> - /// Callback interface for Blobject AMD servants. - /// </summary> - public interface AMD_Object_ice_invoke : Ice.AMDCallback - { - /// <summary> - /// Indicates to the Ice run time that an operation - /// completed. - /// </summary> - /// <param name="ok">True indicates that the operation - /// completed successfully; false indicates that the - /// operation raised a user exception.</param> - /// <param name="outEncaps">The encoded out-parameters for the operation or, - /// if ok is false, the encoded user exception.</param> - void ice_response(bool ok, byte[] outEncaps); - } - - sealed class _AMD_Object_ice_invoke : IceInternal.IncomingAsync, AMD_Object_ice_invoke - { - public _AMD_Object_ice_invoke(IceInternal.Incoming inc) - : base(inc) - { - } - - public void ice_response(bool ok, byte[] outEncaps) - { - try - { - writeParamEncaps__(outEncaps, ok); - } - catch(Ice.LocalException ex) - { - exception__(ex); - return; - } - response__(); - } - } -} diff --git a/csharp/src/Ice/InputStream.cs b/csharp/src/Ice/InputStream.cs new file mode 100644 index 00000000000..9c6cca1c2df --- /dev/null +++ b/csharp/src/Ice/InputStream.cs @@ -0,0 +1,4030 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +namespace Ice +{ + + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Runtime.Serialization; + using System.Runtime.Serialization.Formatters.Binary; + using Protocol = IceInternal.Protocol; + + /// <summary> + /// After a call to readPendingValues(), delegates are called to supply the + /// unmarshaled class instances. + /// </summary> + /// <param name="obj">The unmarshaled instance.</param> + public delegate void ReadValueCallback(Value obj); + + /// <summary> + /// A ClassResolver translates a Slice type Id into a type using + /// an implementation-defined algorithm. + /// </summary> + /// <param name="id">A Slice type Id corresponding to a Slice value or user exception.</param> + public delegate System.Type ClassResolver(string id); + + /// <summary> + /// Throws a UserException corresponding to the given Slice type Id, such as "::Module::MyException". + /// If the implementation does not throw an exception, the Ice run time will fall back + /// to using its default behavior for instantiating the user exception. + /// </summary> + /// <param name="id">A Slice type Id corresponding to a Slice user exception.</param> + public delegate void UserExceptionFactory(string id); + + /// <summary> + /// Interface for input streams used to extract Slice types from a sequence of bytes. + /// </summary> + public class InputStream + { + + /// <summary> + /// Constructing an InputStream without providing a communicator means the stream will + /// use the default encoding version. A communicator is required in order to unmarshal + /// proxies. You can supply a communicator later by calling initialize(). + /// </summary> + public InputStream() + { + initialize(Util.currentEncoding); + _buf = new IceInternal.Buffer(); + } + + /// <summary> + /// Constructing an InputStream without providing a communicator means the stream will + /// use the default encoding version. A communicator is required in order to unmarshal + /// proxies. You can supply a communicator later by calling initialize(). + /// </summary> + /// <param name="data">The byte array containing encoded Slice types.</param> + public InputStream(byte[] data) + { + initialize(Util.currentEncoding); + _buf = new IceInternal.Buffer(data); + } + + public InputStream(IceInternal.ByteBuffer buf) + { + initialize(Util.currentEncoding); + _buf = new IceInternal.Buffer(buf); + } + + public InputStream(IceInternal.Buffer buf) : + this(buf, false) + { + } + + public InputStream(IceInternal.Buffer buf, bool adopt) + { + initialize(Util.currentEncoding); + _buf = new IceInternal.Buffer(buf, adopt); + } + + /// <summary> + /// This constructor uses the communicator's default encoding version. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + public InputStream(Communicator communicator) + { + initialize(communicator); + _buf = new IceInternal.Buffer(); + } + + /// <summary> + /// This constructor uses the communicator's default encoding version. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + /// <param name="data">The byte array containing encoded Slice types.</param> + public InputStream(Communicator communicator, byte[] data) + { + initialize(communicator); + _buf = new IceInternal.Buffer(data); + } + + public InputStream(Communicator communicator, IceInternal.ByteBuffer buf) + { + initialize(communicator); + _buf = new IceInternal.Buffer(buf); + } + + public InputStream(Communicator communicator, IceInternal.Buffer buf) : + this(communicator, buf, false) + { + } + + public InputStream(Communicator communicator, IceInternal.Buffer buf, bool adopt) + { + initialize(communicator); + _buf = new IceInternal.Buffer(buf, adopt); + } + + /// <summary> + /// This constructor uses the given encoding version. + /// </summary> + /// <param name="encoding">The desired encoding version.</param> + public InputStream(EncodingVersion encoding) + { + initialize(encoding); + _buf = new IceInternal.Buffer(); + } + + /// <summary> + /// This constructor uses the given encoding version. + /// </summary> + /// <param name="encoding">The desired encoding version.</param> + /// <param name="data">The byte array containing encoded Slice types.</param> + public InputStream(EncodingVersion encoding, byte[] data) + { + initialize(encoding); + _buf = new IceInternal.Buffer(data); + } + + public InputStream(EncodingVersion encoding, IceInternal.ByteBuffer buf) + { + initialize(encoding); + _buf = new IceInternal.Buffer(buf); + } + + public InputStream(EncodingVersion encoding, IceInternal.Buffer buf) : + this(encoding, buf, false) + { + } + + public InputStream(EncodingVersion encoding, IceInternal.Buffer buf, bool adopt) + { + initialize(encoding); + _buf = new IceInternal.Buffer(buf, adopt); + } + + /// <summary> + /// This constructor uses the given encoding version. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + /// <param name="encoding">The desired encoding version.</param> + public InputStream(Communicator communicator, EncodingVersion encoding) + { + initialize(communicator, encoding); + _buf = new IceInternal.Buffer(); + } + + /// <summary> + /// This constructor uses the given encoding version. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + /// <param name="encoding">The desired encoding version.</param> + /// <param name="data">The byte array containing encoded Slice types.</param> + public InputStream(Communicator communicator, EncodingVersion encoding, byte[] data) + { + initialize(communicator, encoding); + _buf = new IceInternal.Buffer(data); + } + + public InputStream(Communicator communicator, EncodingVersion encoding, IceInternal.ByteBuffer buf) + { + initialize(communicator, encoding); + _buf = new IceInternal.Buffer(buf); + } + + public InputStream(Communicator communicator, EncodingVersion encoding, IceInternal.Buffer buf) : + this(communicator, encoding, buf, false) + { + } + + public InputStream(Communicator communicator, EncodingVersion encoding, IceInternal.Buffer buf, bool adopt) + { + initialize(communicator, encoding); + _buf = new IceInternal.Buffer(buf, adopt); + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding) + { + initialize(instance, encoding); + _buf = new IceInternal.Buffer(); + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding, byte[] data) + { + initialize(instance, encoding); + _buf = new IceInternal.Buffer(data); + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding, IceInternal.ByteBuffer buf) + { + initialize(instance, encoding); + _buf = new IceInternal.Buffer(buf); + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding, IceInternal.Buffer buf) : + this(instance, encoding, buf, false) + { + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding, IceInternal.Buffer buf, bool adopt) + { + initialize(instance, encoding); + _buf = new IceInternal.Buffer(buf, adopt); + } + + /// <summary> + /// Initializes the stream to use the communicator's default encoding version. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + public void initialize(Communicator communicator) + { + Debug.Assert(communicator != null); + IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, instance.defaultsAndOverrides().defaultEncoding); + } + + /// <summary> + /// Initializes the stream to use the given communicator and encoding version. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + /// <param name="encoding">The desired encoding version.</param> + public void initialize(Communicator communicator, EncodingVersion encoding) + { + Debug.Assert(communicator != null); + IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, encoding); + } + + private void initialize(IceInternal.Instance instance, EncodingVersion encoding) + { + initialize(encoding); + + _instance = instance; + _traceSlicing = _instance.traceLevels().slicing > 0; + + _valueFactoryManager = _instance.initializationData().valueFactoryManager; + _logger = _instance.initializationData().logger; + _classResolver = _instance.resolveClass; + } + + private void initialize(EncodingVersion encoding) + { + _instance = null; + _encoding = encoding; + _encapsStack = null; + _encapsCache = null; + _traceSlicing = false; + _closure = null; + _sliceValues = true; + _startSeq = -1; + _minSeqSize = 0; + } + + /// <summary> + /// Resets this stream. This method allows the stream to be reused, to avoid creating + /// unnecessary garbage. + /// </summary> + public void reset() + { + _buf.reset(); + clear(); + } + + /// <summary> + /// Releases any data retained by encapsulations. Internally calls clear(). + /// </summary> + public void clear() + { + if(_encapsStack != null) + { + Debug.Assert(_encapsStack.next == null); + _encapsStack.next = _encapsCache; + _encapsCache = _encapsStack; + _encapsStack = null; + _encapsCache.reset(); + } + + _startSeq = -1; + _sliceValues = true; + } + + /// <summary> + /// Sets the value factory manager to use when marshaling value instances. If the stream + /// was initialized with a communicator, the communicator's value factory manager will + /// be used by default. + /// </summary> + /// <param name="vfm">The value factory manager.</param> + public void setValueFactoryManager(ValueFactoryManager vfm) + { + _valueFactoryManager = vfm; + } + + /// <summary> + /// Sets the logger to use when logging trace messages. If the stream + /// was initialized with a communicator, the communicator's logger will + /// be used by default. + /// </summary> + /// <param name="logger">The logger to use for logging trace messages.</param> + public void setLogger(Logger logger) + { + _logger = logger; + } + + /// <summary> + /// Sets the compact ID resolver to use when unmarshaling value and exception + /// instances. If the stream was initialized with a communicator, the communicator's + /// resolver will be used by default. + /// </summary> + /// <param name="r">The compact ID resolver.</param> + public void setCompactIdResolver(CompactIdResolver r) + { + _compactIdResolver = r; + } + + /// <summary> + /// Sets the class resolver, which the stream will use when attempting to unmarshal + /// a value or exception. If the stream was initialized with a communicator, the communicator's + /// resolver will be used by default. + /// </summary> + /// <param name="r">The class resolver.</param> + public void setClassResolver(ClassResolver r) + { + _classResolver = r; + } + + /// <summary> + /// Determines the behavior of the stream when extracting instances of Slice classes. + /// An instance is "sliced" when a factory cannot be found for a Slice type ID. + /// The stream's default behavior is to slice instances. + /// </summary> + /// <param name="b">If true (the default), slicing is enabled; if false, + /// slicing is disabled. If slicing is disabled and the stream encounters a Slice type ID + /// during decoding for which no value factory is installed, it raises NoValueFactoryException. + /// </param> + public void setSliceValues(bool b) + { + _sliceValues = b; + } + + /// <summary> + /// Determines whether the stream logs messages about slicing instances of Slice values. + /// </summary> + /// <param name="b">True to enable logging, false to disable logging.</param> + public void setTraceSlicing(bool b) + { + _traceSlicing = b; + } + + /// <summary> + /// Retrieves the closure object associated with this stream. + /// </summary> + /// <returns>The closure object.</returns> + public object getClosure() + { + return _closure; + } + + /// <summary> + /// Associates a closure object with this stream. + /// </summary> + /// <param name="p">The new closure object.</param> + /// <returns>The previous closure object, or null.</returns> + public object setClosure(object p) + { + object prev = _closure; + _closure = p; + return prev; + } + + public IceInternal.Instance instance() + { + return _instance; + } + + /// <summary> + /// Swaps the contents of one stream with another. + /// </summary> + /// <param name="other">The other stream.</param> + public void swap(InputStream other) + { + Debug.Assert(_instance == other._instance); + + IceInternal.Buffer tmpBuf = other._buf; + other._buf = _buf; + _buf = tmpBuf; + + EncodingVersion tmpEncoding = other._encoding; + other._encoding = _encoding; + _encoding = tmpEncoding; + + bool tmpTraceSlicing = other._traceSlicing; + other._traceSlicing = _traceSlicing; + _traceSlicing = tmpTraceSlicing; + + object tmpClosure = other._closure; + other._closure = _closure; + _closure = tmpClosure; + + bool tmpSliceValues = other._sliceValues; + other._sliceValues = _sliceValues; + _sliceValues = tmpSliceValues; + + // + // Swap is never called for InputStreams that have encapsulations being read. However, + // encapsulations might still be set in case un-marshalling failed. We just + // reset the encapsulations if there are still some set. + // + resetEncapsulation(); + other.resetEncapsulation(); + + int tmpStartSeq = other._startSeq; + other._startSeq = _startSeq; + _startSeq = tmpStartSeq; + + int tmpMinSeqSize = other._minSeqSize; + other._minSeqSize = _minSeqSize; + _minSeqSize = tmpMinSeqSize; + + ValueFactoryManager tmpVfm = other._valueFactoryManager; + other._valueFactoryManager = _valueFactoryManager; + _valueFactoryManager = tmpVfm; + + Logger tmpLogger = other._logger; + other._logger = _logger; + _logger = tmpLogger; + + CompactIdResolver tmpCompactIdResolver = other._compactIdResolver; + other._compactIdResolver = _compactIdResolver; + _compactIdResolver = tmpCompactIdResolver; + + ClassResolver tmpClassResolver = other._classResolver; + other._classResolver = _classResolver; + _classResolver = tmpClassResolver; + } + + private void resetEncapsulation() + { + _encapsStack = null; + } + + /// <summary> + /// Resizes the stream to a new size. + /// </summary> + /// <param name="sz">The new size.</param> + public void resize(int sz) + { + _buf.resize(sz, true); + _buf.b.position(sz); + } + + public IceInternal.Buffer getBuffer() + { + return _buf; + } + + /// <summary> + /// Marks the start of a class instance. + /// </summary> + public void startValue() + { + Debug.Assert(_encapsStack != null && _encapsStack.decoder != null); + _encapsStack.decoder.startInstance(SliceType.ValueSlice); + } + + /// <summary> + /// Marks the end of a class instance. + /// </summary> + /// <param name="preserve">True if unknown slices should be preserved, false otherwise.</param> + /// <returns>A SlicedData object containing the preserved slices for unknown types.</returns> + public SlicedData endValue(bool preserve) + { + Debug.Assert(_encapsStack != null && _encapsStack.decoder != null); + return _encapsStack.decoder.endInstance(preserve); + } + + /// <summary> + /// Marks the start of a user exception. + /// </summary> + public void startException() + { + Debug.Assert(_encapsStack != null && _encapsStack.decoder != null); + _encapsStack.decoder.startInstance(SliceType.ExceptionSlice); + } + + /// <summary> + /// Marks the end of a user exception. + /// </summary> + /// <param name="preserve">True if unknown slices should be preserved, false otherwise.</param> + /// <returns>A SlicedData object containing the preserved slices for unknown types.</returns> + public SlicedData endException(bool preserve) + { + Debug.Assert(_encapsStack != null && _encapsStack.decoder != null); + return _encapsStack.decoder.endInstance(preserve); + } + + /// <summary> + /// Reads the start of an encapsulation. + /// </summary> + /// <returns>The encapsulation encoding version.</returns> + public EncodingVersion startEncapsulation() + { + Encaps curr = _encapsCache; + if(curr != null) + { + curr.reset(); + _encapsCache = _encapsCache.next; + } + else + { + curr = new Encaps(); + } + curr.next = _encapsStack; + _encapsStack = curr; + + _encapsStack.start = _buf.b.position(); + + // + // I don't use readSize() for encapsulations, because when creating an encapsulation, + // I must know in advance how many bytes the size information will require in the data + // stream. If I use an Int, it is always 4 bytes. For readSize(), it could be 1 or 5 bytes. + // + int sz = readInt(); + if(sz < 6) + { + throw new UnmarshalOutOfBoundsException(); + } + if(sz - 4 > _buf.b.remaining()) + { + throw new UnmarshalOutOfBoundsException(); + } + _encapsStack.sz = sz; + + EncodingVersion encoding = new EncodingVersion(); + encoding.ice_readMembers(this); + Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported. + _encapsStack.setEncoding(encoding); + + return encoding; + } + + /// <summary> + /// Ends the previous encapsulation. + /// </summary> + public void endEncapsulation() + { + Debug.Assert(_encapsStack != null); + + if(!_encapsStack.encoding_1_0) + { + skipOptionals(); + if(_buf.b.position() != _encapsStack.start + _encapsStack.sz) + { + throw new EncapsulationException(); + } + } + else if(_buf.b.position() != _encapsStack.start + _encapsStack.sz) + { + if(_buf.b.position() + 1 != _encapsStack.start + _encapsStack.sz) + { + throw new EncapsulationException(); + } + + // + // Ice version < 3.3 had a bug where user exceptions with + // class members could be encoded with a trailing byte + // when dispatched with AMD. So we tolerate an extra byte + // in the encapsulation. + // + try + { + _buf.b.get(); + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + Encaps curr = _encapsStack; + _encapsStack = curr.next; + curr.next = _encapsCache; + _encapsCache = curr; + _encapsCache.reset(); + } + + /// <summary> + /// Skips an empty encapsulation. + /// </summary> + /// <returns>The encapsulation's encoding version.</returns> + public EncodingVersion skipEmptyEncapsulation() + { + int sz = readInt(); + if(sz < 6) + { + throw new EncapsulationException(); + } + if(sz - 4 > _buf.b.remaining()) + { + throw new UnmarshalOutOfBoundsException(); + } + + var encoding = new EncodingVersion(); + encoding.ice_readMembers(this); + Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported. + + if(encoding.Equals(Util.Encoding_1_0)) + { + if(sz != 6) + { + throw new EncapsulationException(); + } + } + else + { + // Skip the optional content of the encapsulation if we are expecting an + // empty encapsulation. + _buf.b.position(_buf.b.position() + sz - 6); + } + return encoding; + } + + /// <summary> + /// Returns a blob of bytes representing an encapsulation. The encapsulation's encoding version + /// is returned in the argument. + /// </summary> + /// <param name="encoding">The encapsulation's encoding version.</param> + /// <returns>The encoded encapsulation.</returns> + public byte[] readEncapsulation(out EncodingVersion encoding) + { + int sz = readInt(); + if(sz < 6) + { + throw new UnmarshalOutOfBoundsException(); + } + + if(sz - 4 > _buf.b.remaining()) + { + throw new UnmarshalOutOfBoundsException(); + } + + encoding = new EncodingVersion(); + encoding.ice_readMembers(this); + _buf.b.position(_buf.b.position() - 6); + + byte[] v = new byte[sz]; + try + { + _buf.b.get(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Determines the current encoding version. + /// </summary> + /// <returns>The encoding version.</returns> + public EncodingVersion getEncoding() + { + return _encapsStack != null ? _encapsStack.encoding : _encoding; + } + + /// <summary> + /// Determines the size of the current encapsulation, excluding the encapsulation header. + /// </summary> + /// <returns>The size of the encapsulated data.</returns> + public int getEncapsulationSize() + { + Debug.Assert(_encapsStack != null); + return _encapsStack.sz - 6; + } + + /// <summary> + /// Skips over an encapsulation. + /// </summary> + /// <returns>The encoding version of the skipped encapsulation.</returns> + public EncodingVersion skipEncapsulation() + { + int sz = readInt(); + if(sz < 6) + { + throw new UnmarshalOutOfBoundsException(); + } + EncodingVersion encoding = new EncodingVersion(); + encoding.ice_readMembers(this); + try + { + _buf.b.position(_buf.b.position() + sz - 6); + } + catch(ArgumentOutOfRangeException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + return encoding; + } + + /// <summary> + /// Reads the start of a class instance or exception slice. + /// </summary> + /// <returns>The Slice type ID for this slice.</returns> + public string startSlice() // Returns type ID of next slice + { + Debug.Assert(_encapsStack != null && _encapsStack.decoder != null); + return _encapsStack.decoder.startSlice(); + } + + /// <summary> + /// Indicates that the end of a class instance or exception slice has been reached. + /// </summary> + public void endSlice() + { + Debug.Assert(_encapsStack != null && _encapsStack.decoder != null); + _encapsStack.decoder.endSlice(); + } + + /// <summary> + /// Skips over a class instance or exception slice. + /// </summary> + public void skipSlice() + { + Debug.Assert(_encapsStack != null && _encapsStack.decoder != null); + _encapsStack.decoder.skipSlice(); + } + + /// <summary> + /// Indicates that unmarshaling is complete, except for any class instances. The application must call this + /// method only if the stream actually contains class instances. Calling readPendingValues triggers the + /// calls to the ReadValueCallback delegates to inform the application that unmarshaling of an instance + /// is complete. + /// </summary> + public void readPendingValues() + { + if(_encapsStack != null && _encapsStack.decoder != null) + { + _encapsStack.decoder.readPendingValues(); + } + else if(_encapsStack != null ? _encapsStack.encoding_1_0 : _encoding.Equals(Util.Encoding_1_0)) + { + // + // If using the 1.0 encoding and no instances were read, we + // still read an empty sequence of pending instances if + // requested (i.e.: if this is called). + // + // This is required by the 1.0 encoding, even if no instances + // are written we do marshal an empty sequence if marshaled + // data types use classes. + // + skipSize(); + } + } + + /// <summary> + /// Extracts a size from the stream. + /// </summary> + /// <returns>The extracted size.</returns> + public int readSize() + { + try + { + byte b = _buf.b.get(); + if(b == 255) + { + int v = _buf.b.getInt(); + if(v < 0) + { + throw new UnmarshalOutOfBoundsException(); + } + return v; + } + else + { + return b; // byte is unsigned + } + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Reads and validates a sequence size. + /// </summary> + /// <returns>The extracted size.</returns> + public int readAndCheckSeqSize(int minSize) + { + int sz = readSize(); + + if(sz == 0) + { + return 0; + } + + // + // The _startSeq variable points to the start of the sequence for which + // we expect to read at least _minSeqSize bytes from the stream. + // + // If not initialized or if we already read more data than _minSeqSize, + // we reset _startSeq and _minSeqSize for this sequence (possibly a + // top-level sequence or enclosed sequence it doesn't really matter). + // + // Otherwise, we are reading an enclosed sequence and we have to bump + // _minSeqSize by the minimum size that this sequence will require on + // the stream. + // + // The goal of this check is to ensure that when we start un-marshalling + // a new sequence, we check the minimal size of this new sequence against + // the estimated remaining buffer size. This estimatation is based on + // the minimum size of the enclosing sequences, it's _minSeqSize. + // + if(_startSeq == -1 || _buf.b.position() > (_startSeq + _minSeqSize)) + { + _startSeq = _buf.b.position(); + _minSeqSize = sz * minSize; + } + else + { + _minSeqSize += sz * minSize; + } + + // + // If there isn't enough data to read on the stream for the sequence (and + // possibly enclosed sequences), something is wrong with the marshalled + // data: it's claiming having more data that what is possible to read. + // + if(_startSeq + _minSeqSize > _buf.size()) + { + throw new UnmarshalOutOfBoundsException(); + } + + return sz; + } + + /// <summary> + /// Reads a blob of bytes from the stream. The length of the given array determines how many bytes are read. + /// </summary> + /// <param name="v">Bytes from the stream.</param> + public void readBlob(byte[] v) + { + try + { + _buf.b.get(v); + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Reads a blob of bytes from the stream. + /// </summary> + /// <param name="sz">The number of bytes to read.</param> + /// <returns>The requested bytes as a byte array.</returns> + public byte[] readBlob(int sz) + { + if(_buf.b.remaining() < sz) + { + throw new UnmarshalOutOfBoundsException(); + } + byte[] v = new byte[sz]; + try + { + _buf.b.get(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Determine if an optional value is available for reading. + /// </summary> + /// <param name="tag">The tag associated with the value.</param> + /// <param name="expectedFormat">The optional format for the value.</param> + /// <returns>True if the value is present, false otherwise.</returns> + public bool readOptional(int tag, OptionalFormat expectedFormat) + { + Debug.Assert(_encapsStack != null); + if(_encapsStack.decoder != null) + { + return _encapsStack.decoder.readOptional(tag, expectedFormat); + } + else + { + return readOptImpl(tag, expectedFormat); + } + } + + /// <summary> + /// Extracts a byte value from the stream. + /// </summary> + /// <returns>The extracted byte.</returns> + public byte readByte() + { + try + { + return _buf.b.get(); + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts an optional byte value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<byte> readByte(int tag) + { + if(readOptional(tag, OptionalFormat.F1)) + { + return new Optional<byte>(readByte()); + } + else + { + return new Optional<byte>(); + } + } + + /// <summary> + /// Extracts an optional byte value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readByte(int tag, out bool isset, out byte v) + { + if(isset = readOptional(tag, OptionalFormat.F1)) + { + v = readByte(); + } + else + { + v = 0; + } + } + + /// <summary> + /// Extracts a sequence of byte values from the stream. + /// </summary> + /// <returns>The extracted byte sequence.</returns> + public byte[] readByteSeq() + { + try + { + int sz = readAndCheckSeqSize(1); + byte[] v = new byte[sz]; + _buf.b.get(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of byte values from the stream. + /// </summary> + /// <param name="l">The extracted byte sequence as a list.</param> + public void readByteSeq(out List<byte> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new List<byte>(readByteSeq()); + } + + /// <summary> + /// Extracts a sequence of byte values from the stream. + /// </summary> + /// <param name="l">The extracted byte sequence as a linked list.</param> + public void readByteSeq(out LinkedList<byte> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new LinkedList<byte>(readByteSeq()); + } + + /// <summary> + /// Extracts a sequence of byte values from the stream. + /// </summary> + /// <param name="l">The extracted byte sequence as a queue.</param> + public void readByteSeq(out Queue<byte> l) + { + // + // Reading into an array and copy-constructing the + // queue is faster than constructing the queue + // and adding to it one element at a time. + // + l = new Queue<byte>(readByteSeq()); + } + + /// <summary> + /// Extracts a sequence of byte values from the stream. + /// </summary> + /// <param name="l">The extracted byte sequence as a stack.</param> + public void readByteSeq(out Stack<byte> l) + { + // + // Reverse the contents by copying into an array first + // because the stack is marshaled in top-to-bottom order. + // + byte[] array = readByteSeq(); + Array.Reverse(array); + l = new Stack<byte>(array); + } + + /// <summary> + /// Extracts an optional byte sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<byte[]> readByteSeq(int tag) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + return new Optional<byte[]>(readByteSeq()); + } + else + { + return new Optional<byte[]>(); + } + } + + /// <summary> + /// Extracts an optional byte sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readByteSeq(int tag, out bool isset, out byte[] v) + { + if(isset = readOptional(tag, OptionalFormat.VSize)) + { + v = readByteSeq(); + } + else + { + v = null; + } + } + + /// <summary> + /// Extracts a serializable object from the stream. + /// </summary> + /// <returns>The serializable object.</returns> + public object readSerializable() + { + int sz = readAndCheckSeqSize(1); + if(sz == 0) + { + return null; + } + try + { + var f = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All, _instance)); + return f.Deserialize(new IceInternal.InputStreamWrapper(sz, this)); + } + catch(System.Exception ex) + { + throw new MarshalException("cannot deserialize object:", ex); + } + } + + /// <summary> + /// Extracts a boolean value from the stream. + /// </summary> + /// <returns>The extracted boolean.</returns> + public bool readBool() + { + try + { + return _buf.b.get() == 1; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts an optional boolean value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<bool> readBool(int tag) + { + if(readOptional(tag, OptionalFormat.F1)) + { + return new Optional<bool>(readBool()); + } + else + { + return new Optional<bool>(); + } + } + + /// <summary> + /// Extracts an optional boolean value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readBool(int tag, out bool isset, out bool v) + { + if(isset = readOptional(tag, OptionalFormat.F1)) + { + v = readBool(); + } + else + { + v = false; + } + } + + /// <summary> + /// Extracts a sequence of boolean values from the stream. + /// </summary> + /// <returns>The extracted boolean sequence.</returns> + public bool[] readBoolSeq() + { + try + { + int sz = readAndCheckSeqSize(1); + bool[] v = new bool[sz]; + _buf.b.getBoolSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of boolean values from the stream. + /// </summary> + /// <param name="l">The extracted boolean sequence as a list.</param> + public void readBoolSeq(out List<bool> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new List<bool>(readBoolSeq()); + } + + /// <summary> + /// Extracts a sequence of boolean values from the stream. + /// </summary> + /// <param name="l">The extracted boolean sequence as a linked list.</param> + public void readBoolSeq(out LinkedList<bool> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new LinkedList<bool>(readBoolSeq()); + } + + /// <summary> + /// Extracts a sequence of boolean values from the stream. + /// </summary> + /// <param name="l">The extracted boolean sequence as a queue.</param> + public void readBoolSeq(out Queue<bool> l) + { + // + // Reading into an array and copy-constructing the + // queue is faster than constructing the queue + // and adding to it one element at a time. + // + l = new Queue<bool>(readBoolSeq()); + } + + /// <summary> + /// Extracts a sequence of boolean values from the stream. + /// </summary> + /// <param name="l">The extracted boolean sequence as a stack.</param> + public void readBoolSeq(out Stack<bool> l) + { + // + // Reverse the contents by copying into an array first + // because the stack is marshaled in top-to-bottom order. + // + bool[] array = readBoolSeq(); + Array.Reverse(array); + l = new Stack<bool>(array); + } + + /// <summary> + /// Extracts an optional boolean sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<bool[]> readBoolSeq(int tag) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + return new Optional<bool[]>(readBoolSeq()); + } + else + { + return new Optional<bool[]>(); + } + } + + /// <summary> + /// Extracts an optional boolean sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readBoolSeq(int tag, out bool isset, out bool[] v) + { + if(isset = readOptional(tag, OptionalFormat.VSize)) + { + v = readBoolSeq(); + } + else + { + v = null; + } + } + + /// <summary> + /// Extracts a short value from the stream. + /// </summary> + /// <returns>The extracted short.</returns> + public short readShort() + { + try + { + return _buf.b.getShort(); + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts an optional short value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<short> readShort(int tag) + { + if(readOptional(tag, OptionalFormat.F2)) + { + return new Optional<short>(readShort()); + } + else + { + return new Optional<short>(); + } + } + + /// <summary> + /// Extracts an optional short value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readShort(int tag, out bool isset, out short v) + { + if(isset = readOptional(tag, OptionalFormat.F2)) + { + v = readShort(); + } + else + { + v = 0; + } + } + + /// <summary> + /// Extracts a sequence of short values from the stream. + /// </summary> + /// <returns>The extracted short sequence.</returns> + public short[] readShortSeq() + { + try + { + int sz = readAndCheckSeqSize(2); + short[] v = new short[sz]; + _buf.b.getShortSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of short values from the stream. + /// </summary> + /// <param name="l">The extracted short sequence as a list.</param> + public void readShortSeq(out List<short> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new List<short>(readShortSeq()); + } + + /// <summary> + /// Extracts a sequence of short values from the stream. + /// </summary> + /// <param name="l">The extracted short sequence as a linked list.</param> + public void readShortSeq(out LinkedList<short> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new LinkedList<short>(readShortSeq()); + } + + /// <summary> + /// Extracts a sequence of short values from the stream. + /// </summary> + /// <param name="l">The extracted short sequence as a queue.</param> + public void readShortSeq(out Queue<short> l) + { + // + // Reading into an array and copy-constructing the + // queue is faster than constructing the queue + // and adding to it one element at a time. + // + l = new Queue<short>(readShortSeq()); + } + + /// <summary> + /// Extracts a sequence of short values from the stream. + /// </summary> + /// <param name="l">The extracted short sequence as a stack.</param> + public void readShortSeq(out Stack<short> l) + { + // + // Reverse the contents by copying into an array first + // because the stack is marshaled in top-to-bottom order. + // + short[] array = readShortSeq(); + Array.Reverse(array); + l = new Stack<short>(array); + } + + /// <summary> + /// Extracts an optional short sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<short[]> readShortSeq(int tag) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + return new Optional<short[]>(readShortSeq()); + } + else + { + return new Optional<short[]>(); + } + } + + /// <summary> + /// Extracts an optional short sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readShortSeq(int tag, out bool isset, out short[] v) + { + if(isset = readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v = readShortSeq(); + } + else + { + v = null; + } + } + + /// <summary> + /// Extracts an int value from the stream. + /// </summary> + /// <returns>The extracted int.</returns> + public int readInt() + { + try + { + return _buf.b.getInt(); + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts an optional int value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<int> readInt(int tag) + { + if(readOptional(tag, OptionalFormat.F4)) + { + return new Optional<int>(readInt()); + } + else + { + return new Optional<int>(); + } + } + + /// <summary> + /// Extracts an optional int value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readInt(int tag, out bool isset, out int v) + { + if(isset = readOptional(tag, OptionalFormat.F4)) + { + v = readInt(); + } + else + { + v = 0; + } + } + + /// <summary> + /// Extracts a sequence of int values from the stream. + /// </summary> + /// <returns>The extracted int sequence.</returns> + public int[] readIntSeq() + { + try + { + int sz = readAndCheckSeqSize(4); + int[] v = new int[sz]; + _buf.b.getIntSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of int values from the stream. + /// </summary> + /// <param name="l">The extracted int sequence as a list.</param> + public void readIntSeq(out List<int> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new List<int>(readIntSeq()); + } + + /// <summary> + /// Extracts a sequence of int values from the stream. + /// </summary> + /// <param name="l">The extracted int sequence as a linked list.</param> + public void readIntSeq(out LinkedList<int> l) + { + try + { + int sz = readAndCheckSeqSize(4); + l = new LinkedList<int>(); + for(int i = 0; i < sz; ++i) + { + l.AddLast(_buf.b.getInt()); + } + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of int values from the stream. + /// </summary> + /// <param name="l">The extracted int sequence as a queue.</param> + public void readIntSeq(out Queue<int> l) + { + // + // Reading into an array and copy-constructing the + // queue takes the same time as constructing the queue + // and adding to it one element at a time, so + // we avoid the copy. + // + try + { + int sz = readAndCheckSeqSize(4); + l = new Queue<int>(sz); + for(int i = 0; i < sz; ++i) + { + l.Enqueue(_buf.b.getInt()); + } + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of int values from the stream. + /// </summary> + /// <param name="l">The extracted int sequence as a stack.</param> + public void readIntSeq(out Stack<int> l) + { + // + // Reverse the contents by copying into an array first + // because the stack is marshaled in top-to-bottom order. + // + int[] array = readIntSeq(); + Array.Reverse(array); + l = new Stack<int>(array); + } + + /// <summary> + /// Extracts an optional int sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<int[]> readIntSeq(int tag) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + return new Optional<int[]>(readIntSeq()); + } + else + { + return new Optional<int[]>(); + } + } + + /// <summary> + /// Extracts an optional int sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readIntSeq(int tag, out bool isset, out int[] v) + { + if(isset = readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v = readIntSeq(); + } + else + { + v = null; + } + } + + /// <summary> + /// Extracts a long value from the stream. + /// </summary> + /// <returns>The extracted long.</returns> + public long readLong() + { + try + { + return _buf.b.getLong(); + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts an optional long value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<long> readLong(int tag) + { + if(readOptional(tag, OptionalFormat.F8)) + { + return new Optional<long>(readLong()); + } + else + { + return new Optional<long>(); + } + } + + /// <summary> + /// Extracts an optional long value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readLong(int tag, out bool isset, out long v) + { + if(isset = readOptional(tag, OptionalFormat.F8)) + { + v = readLong(); + } + else + { + v = 0; + } + } + + /// <summary> + /// Extracts a sequence of long values from the stream. + /// </summary> + /// <returns>The extracted long sequence.</returns> + public long[] readLongSeq() + { + try + { + int sz = readAndCheckSeqSize(8); + long[] v = new long[sz]; + _buf.b.getLongSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of long values from the stream. + /// </summary> + /// <param name="l">The extracted long sequence as a list.</param> + public void readLongSeq(out List<long> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new List<long>(readLongSeq()); + } + + /// <summary> + /// Extracts a sequence of long values from the stream. + /// </summary> + /// <param name="l">The extracted long sequence as a linked list.</param> + public void readLongSeq(out LinkedList<long> l) + { + try + { + int sz = readAndCheckSeqSize(4); + l = new LinkedList<long>(); + for(int i = 0; i < sz; ++i) + { + l.AddLast(_buf.b.getLong()); + } + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of long values from the stream. + /// </summary> + /// <param name="l">The extracted long sequence as a queue.</param> + public void readLongSeq(out Queue<long> l) + { + // + // Reading into an array and copy-constructing the + // queue takes the same time as constructing the queue + // and adding to it one element at a time, so + // we avoid the copy. + // + try + { + int sz = readAndCheckSeqSize(4); + l = new Queue<long>(sz); + for(int i = 0; i < sz; ++i) + { + l.Enqueue(_buf.b.getLong()); + } + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of long values from the stream. + /// </summary> + /// <param name="l">The extracted long sequence as a stack.</param> + public void readLongSeq(out Stack<long> l) + { + // + // Reverse the contents by copying into an array first + // because the stack is marshaled in top-to-bottom order. + // + long[] array = readLongSeq(); + Array.Reverse(array); + l = new Stack<long>(array); + } + + /// <summary> + /// Extracts an optional long sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<long[]> readLongSeq(int tag) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + return new Optional<long[]>(readLongSeq()); + } + else + { + return new Optional<long[]>(); + } + } + + /// <summary> + /// Extracts an optional long sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readLongSeq(int tag, out bool isset, out long[] v) + { + if(isset = readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v = readLongSeq(); + } + else + { + v = null; + } + } + + /// <summary> + /// Extracts a float value from the stream. + /// </summary> + /// <returns>The extracted float.</returns> + public float readFloat() + { + try + { + return _buf.b.getFloat(); + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts an optional float value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<float> readFloat(int tag) + { + if(readOptional(tag, OptionalFormat.F4)) + { + return new Optional<float>(readFloat()); + } + else + { + return new Optional<float>(); + } + } + + /// <summary> + /// Extracts an optional float value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readFloat(int tag, out bool isset, out float v) + { + if(isset = readOptional(tag, OptionalFormat.F4)) + { + v = readFloat(); + } + else + { + v = 0; + } + } + + /// <summary> + /// Extracts a sequence of float values from the stream. + /// </summary> + /// <returns>The extracted float sequence.</returns> + public float[] readFloatSeq() + { + try + { + int sz = readAndCheckSeqSize(4); + float[] v = new float[sz]; + _buf.b.getFloatSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of float values from the stream. + /// </summary> + /// <param name="l">The extracted float sequence as a list.</param> + public void readFloatSeq(out List<float> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new List<float>(readFloatSeq()); + } + + /// <summary> + /// Extracts a sequence of float values from the stream. + /// </summary> + /// <param name="l">The extracted float sequence as a linked list.</param> + public void readFloatSeq(out LinkedList<float> l) + { + try + { + int sz = readAndCheckSeqSize(4); + l = new LinkedList<float>(); + for(int i = 0; i < sz; ++i) + { + l.AddLast(_buf.b.getFloat()); + } + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of float values from the stream. + /// </summary> + /// <param name="l">The extracted float sequence as a queue.</param> + public void readFloatSeq(out Queue<float> l) + { + // + // Reading into an array and copy-constructing the + // queue takes the same time as constructing the queue + // and adding to it one element at a time, so + // we avoid the copy. + // + try + { + int sz = readAndCheckSeqSize(4); + l = new Queue<float>(sz); + for(int i = 0; i < sz; ++i) + { + l.Enqueue(_buf.b.getFloat()); + } + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of float values from the stream. + /// </summary> + /// <param name="l">The extracted float sequence as a stack.</param> + public void readFloatSeq(out Stack<float> l) + { + // + // Reverse the contents by copying into an array first + // because the stack is marshaled in top-to-bottom order. + // + float[] array = readFloatSeq(); + Array.Reverse(array); + l = new Stack<float>(array); + } + + /// <summary> + /// Extracts an optional float sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<float[]> readFloatSeq(int tag) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + return new Optional<float[]>(readFloatSeq()); + } + else + { + return new Optional<float[]>(); + } + } + + /// <summary> + /// Extracts an optional float sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readFloatSeq(int tag, out bool isset, out float[] v) + { + if(isset = readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v = readFloatSeq(); + } + else + { + v = null; + } + } + + /// <summary> + /// Extracts a double value from the stream. + /// </summary> + /// <returns>The extracted double.</returns> + public double readDouble() + { + try + { + return _buf.b.getDouble(); + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts an optional double value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<double> readDouble(int tag) + { + if(readOptional(tag, OptionalFormat.F8)) + { + return new Optional<double>(readDouble()); + } + else + { + return new Optional<double>(); + } + } + + /// <summary> + /// Extracts an optional double value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readDouble(int tag, out bool isset, out double v) + { + if(isset = readOptional(tag, OptionalFormat.F8)) + { + v = readDouble(); + } + else + { + v = 0; + } + } + + /// <summary> + /// Extracts a sequence of double values from the stream. + /// </summary> + /// <returns>The extracted double sequence.</returns> + public double[] readDoubleSeq() + { + try + { + int sz = readAndCheckSeqSize(8); + double[] v = new double[sz]; + _buf.b.getDoubleSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of double values from the stream. + /// </summary> + /// <param name="l">The extracted double sequence as a list.</param> + public void readDoubleSeq(out List<double> l) + { + // + // Reading into an array and copy-constructing the + // list is faster than constructing the list + // and adding to it one element at a time. + // + l = new List<double>(readDoubleSeq()); + } + + /// <summary> + /// Extracts a sequence of double values from the stream. + /// </summary> + /// <param name="l">The extracted double sequence as a linked list.</param> + public void readDoubleSeq(out LinkedList<double> l) + { + try + { + int sz = readAndCheckSeqSize(4); + l = new LinkedList<double>(); + for(int i = 0; i < sz; ++i) + { + l.AddLast(_buf.b.getDouble()); + } + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of double values from the stream. + /// </summary> + /// <param name="l">The extracted double sequence as a queue.</param> + public void readDoubleSeq(out Queue<double> l) + { + // + // Reading into an array and copy-constructing the + // queue takes the same time as constructing the queue + // and adding to it one element at a time, so + // we avoid the copy. + // + try + { + int sz = readAndCheckSeqSize(4); + l = new Queue<double>(sz); + for(int i = 0; i < sz; ++i) + { + l.Enqueue(_buf.b.getDouble()); + } + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + } + + /// <summary> + /// Extracts a sequence of double values from the stream. + /// </summary> + /// <param name="l">The extracted double sequence as a stack.</param> + public void readDoubleSeq(out Stack<double> l) + { + // + // Reverse the contents by copying into an array first + // because the stack is marshaled in top-to-bottom order. + // + double[] array = readDoubleSeq(); + Array.Reverse(array); + l = new Stack<double>(array); + } + + /// <summary> + /// Extracts an optional double sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<double[]> readDoubleSeq(int tag) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + return new Optional<double[]>(readDoubleSeq()); + } + else + { + return new Optional<double[]>(); + } + } + + /// <summary> + /// Extracts an optional double sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readDoubleSeq(int tag, out bool isset, out double[] v) + { + if(isset = readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v = readDoubleSeq(); + } + else + { + v = null; + } + } + + private static System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); + + /// <summary> + /// Extracts a string from the stream. + /// </summary> + /// <returns>The extracted string.</returns> + public string readString() + { + int len = readSize(); + + if(len == 0) + { + return ""; + } + + // + // Check the buffer has enough bytes to read. + // + if(_buf.b.remaining() < len) + { + throw new UnmarshalOutOfBoundsException(); + } + + try + { + // + // We reuse the _stringBytes array to avoid creating + // excessive garbage + // + if(_stringBytes == null || len > _stringBytes.Length) + { + _stringBytes = new byte[len]; + } + _buf.b.get(_stringBytes, 0, len); + return utf8.GetString(_stringBytes, 0, len); + } + catch(InvalidOperationException ex) + { + throw new UnmarshalOutOfBoundsException(ex); + } + catch(ArgumentException ex) + { + throw new MarshalException("Invalid UTF8 string", ex); + } + } + + /// <summary> + /// Extracts an optional string from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<string> readString(int tag) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + return new Optional<string>(readString()); + } + else + { + return new Optional<string>(); + } + } + + /// <summary> + /// Extracts an optional string from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readString(int tag, out bool isset, out string v) + { + if(isset = readOptional(tag, OptionalFormat.VSize)) + { + v = readString(); + } + else + { + v = null; + } + } + + /// <summary> + /// Extracts a sequence of strings from the stream. + /// </summary> + /// <returns>The extracted string sequence.</returns> + public string[] readStringSeq() + { + int sz = readAndCheckSeqSize(1); + string[] v = new string[sz]; + for(int i = 0; i < sz; i++) + { + v[i] = readString(); + } + return v; + } + + /// <summary> + /// Extracts a sequence of strings from the stream. + /// </summary> + /// <param name="l">The extracted string sequence as a list.</param> + public void readStringSeq(out List<string> l) + { + // + // Reading into an array and copy-constructing the + // list is slower than constructing the list + // and adding to it one element at a time. + // + int sz = readAndCheckSeqSize(1); + l = new List<string>(sz); + for(int i = 0; i < sz; ++i) + { + l.Add(readString()); + } + } + + /// <summary> + /// Extracts a sequence of strings from the stream. + /// </summary> + /// <param name="l">The extracted string sequence as a linked list.</param> + public void readStringSeq(out LinkedList<string> l) + { + // + // Reading into an array and copy-constructing the + // list is slower than constructing the list + // and adding to it one element at a time. + // + int sz = readAndCheckSeqSize(1); + l = new LinkedList<string>(); + for(int i = 0; i < sz; ++i) + { + l.AddLast(readString()); + } + } + + /// <summary> + /// Extracts a sequence of strings from the stream. + /// </summary> + /// <param name="l">The extracted string sequence as a queue.</param> + public void readStringSeq(out Queue<string> l) + { + // + // Reading into an array and copy-constructing the + // queue is slower than constructing the queue + // and adding to it one element at a time. + // + int sz = readAndCheckSeqSize(1); + l = new Queue<string>(); + for(int i = 0; i < sz; ++i) + { + l.Enqueue(readString()); + } + } + + /// <summary> + /// Extracts a sequence of strings from the stream. + /// </summary> + /// <param name="l">The extracted string sequence as a stack.</param> + public void readStringSeq(out Stack<string> l) + { + // + // Reverse the contents by copying into an array first + // because the stack is marshaled in top-to-bottom order. + // + string[] array = readStringSeq(); + Array.Reverse(array); + l = new Stack<string>(array); + } + + /// <summary> + /// Extracts an optional string sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<string[]> readStringSeq(int tag) + { + if(readOptional(tag, OptionalFormat.FSize)) + { + skip(4); + return new Optional<string[]>(readStringSeq()); + } + else + { + return new Optional<string[]>(); + } + } + + /// <summary> + /// Extracts an optional string sequence from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readStringSeq(int tag, out bool isset, out string[] v) + { + if(isset = readOptional(tag, OptionalFormat.FSize)) + { + skip(4); + v = readStringSeq(); + } + else + { + v = null; + } + } + + /// <summary> + /// Extracts a proxy from the stream. The stream must have been initialized with a communicator. + /// </summary> + /// <returns>The extracted proxy.</returns> + public ObjectPrx readProxy() + { + return _instance.proxyFactory().streamToProxy(this); + } + + /// <summary> + /// Extracts an optional proxy from the stream. The stream must have been initialized with a communicator. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <returns>The optional value.</returns> + public Optional<ObjectPrx> readProxy(int tag) + { + if(readOptional(tag, OptionalFormat.FSize)) + { + skip(4); + return new Optional<ObjectPrx>(readProxy()); + } + else + { + return new Optional<ObjectPrx>(); + } + } + + /// <summary> + /// Extracts an optional proxy from the stream. The stream must have been initialized with a communicator. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="isset">True if the optional value is present, false otherwise.</param> + /// <param name="v">The optional value.</param> + public void readProxy(int tag, out bool isset, out ObjectPrx v) + { + if(isset = readOptional(tag, OptionalFormat.FSize)) + { + skip(4); + v = readProxy(); + } + else + { + v = null; + } + } + + /// <summary> + /// Read an enumerated value. + /// </summary> + /// <param name="maxValue">The maximum enumerator value in the definition.</param> + /// <returns>The enumerator.</returns> + public int readEnum(int maxValue) + { + if(getEncoding().Equals(Util.Encoding_1_0)) + { + if(maxValue < 127) + { + return readByte(); + } + else if(maxValue < 32767) + { + return readShort(); + } + else + { + return readInt(); + } + } + else + { + return readSize(); + } + } + + /// <summary> + /// Extracts the index of a Slice value from the stream. + /// </summary> + /// <param name="cb">The callback to notify the application when the extracted instance is available. + /// The stream extracts Slice values in stages. The Ice run time invokes the delegate when the + /// corresponding instance has been fully unmarshaled.</param> + public void readValue(ReadValueCallback cb) + { + initEncaps(); + _encapsStack.decoder.readValue(cb); + } + + /// <summary> + /// Extracts the index of an optional Slice value from the stream. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="cb">The callback to notify the application when the extracted instance is available (if any). + /// The stream extracts Slice values in stages. The Ice run time invokes the delegate when the + /// corresponding instance has been fully unmarshaled.</param> + public void readValue(int tag, ReadValueCallback cb) + { + if(readOptional(tag, OptionalFormat.Class)) + { + readValue(cb); + } + } + + /// <summary> + /// Extracts a user exception from the stream and throws it. + /// </summary> + public void throwException() + { + throwException(null); + } + + /// <summary> + /// Extracts a user exception from the stream and throws it. + /// </summary> + /// <param name="factory">The user exception factory, or null to use the stream's default behavior.</param> + public void throwException(UserExceptionFactory factory) + { + initEncaps(); + _encapsStack.decoder.throwException(factory); + } + + /// <summary> + /// Skip the given number of bytes. + /// </summary> + /// <param name="size">The number of bytes to skip</param> + public void skip(int size) + { + if(size < 0 || size > _buf.b.remaining()) + { + throw new UnmarshalOutOfBoundsException(); + } + _buf.b.position(_buf.b.position() + size); + } + + /// <summary> + /// Skip over a size value. + /// </summary> + public void skipSize() + { + byte b = readByte(); + if(b == 255) + { + skip(4); + } + } + + /// <summary> + /// Determines the current position in the stream. + /// </summary> + /// <returns>The current position.</returns> + public int pos() + { + return _buf.b.position(); + } + + /// <summary> + /// Sets the current position in the stream. + /// </summary> + /// <param name="n">The new position.</param> + public void pos(int n) + { + _buf.b.position(n); + } + + /// <summary> + /// Determines the current size of the stream. + /// </summary> + /// <returns>The current size.</returns> + public int size() + { + return _buf.size(); + } + + /// <summary> + /// Determines whether the stream is empty. + /// </summary> + /// <returns>True if the internal buffer has no data, false otherwise.</returns> + public bool isEmpty() + { + return _buf.empty(); + } + + private bool readOptImpl(int readTag, OptionalFormat expectedFormat) + { + if(isEncoding_1_0()) + { + return false; // Optional members aren't supported with the 1.0 encoding. + } + + while(true) + { + if(_buf.b.position() >= _encapsStack.start + _encapsStack.sz) + { + return false; // End of encapsulation also indicates end of optionals. + } + + int v = readByte(); + if(v == Protocol.OPTIONAL_END_MARKER) + { + _buf.b.position(_buf.b.position() - 1); // Rewind. + return false; + } + + OptionalFormat format = (OptionalFormat)(v & 0x07); // First 3 bits. + int tag = v >> 3; + if(tag == 30) + { + tag = readSize(); + } + + if(tag > readTag) + { + int offset = tag < 30 ? 1 : (tag < 255 ? 2 : 6); // Rewind + _buf.b.position(_buf.b.position() - offset); + return false; // No optional data members with the requested tag. + } + else if(tag < readTag) + { + skipOptional(format); // Skip optional data members + } + else + { + if(format != expectedFormat) + { + throw new MarshalException("invalid optional data member `" + tag + "': unexpected format"); + } + return true; + } + } + } + + private void skipOptional(OptionalFormat format) + { + switch(format) + { + case OptionalFormat.F1: + { + skip(1); + break; + } + case OptionalFormat.F2: + { + skip(2); + break; + } + case OptionalFormat.F4: + { + skip(4); + break; + } + case OptionalFormat.F8: + { + skip(8); + break; + } + case OptionalFormat.Size: + { + skipSize(); + break; + } + case OptionalFormat.VSize: + { + skip(readSize()); + break; + } + case OptionalFormat.FSize: + { + skip(readInt()); + break; + } + case OptionalFormat.Class: + { + readValue(null); + break; + } + } + } + + private bool skipOptionals() + { + // + // Skip remaining un-read optional members. + // + while(true) + { + if(_buf.b.position() >= _encapsStack.start + _encapsStack.sz) + { + return false; // End of encapsulation also indicates end of optionals. + } + + int v = readByte(); + if(v == Protocol.OPTIONAL_END_MARKER) + { + return true; + } + + OptionalFormat format = (OptionalFormat)(v & 0x07); // Read first 3 bits. + if((v >> 3) == 30) + { + skipSize(); + } + skipOptional(format); + } + } + + private UserException createUserException(string id) + { + UserException userEx = null; + + try + { + if(_classResolver != null) + { + Type c = _classResolver(id); + if(c != null) + { + Debug.Assert(!c.IsAbstract && !c.IsInterface); + userEx = (UserException)IceInternal.AssemblyUtil.createInstance(c); + } + } + } + catch(Exception ex) + { + throw new MarshalException(ex); + } + + return userEx; + } + + private IceInternal.Instance _instance; + private IceInternal.Buffer _buf; + private object _closure; + private byte[] _stringBytes; // Reusable array for reading strings. + + private enum SliceType { NoSlice, ValueSlice, ExceptionSlice } + + abstract private class EncapsDecoder + { + internal EncapsDecoder(InputStream stream, Encaps encaps, bool sliceValues, ValueFactoryManager f, + ClassResolver cr) + { + _stream = stream; + _encaps = encaps; + _sliceValues = sliceValues; + _valueFactoryManager = f; + _classResolver = cr; + _typeIdIndex = 0; + _unmarshaledMap = new Dictionary<int, Value>(); + } + + internal abstract void readValue(ReadValueCallback cb); + internal abstract void throwException(UserExceptionFactory factory); + + internal abstract void startInstance(SliceType type); + internal abstract SlicedData endInstance(bool preserve); + internal abstract string startSlice(); + internal abstract void endSlice(); + internal abstract void skipSlice(); + + internal virtual bool readOptional(int tag, OptionalFormat format) + { + return false; + } + + internal virtual void readPendingValues() + { + } + + protected string readTypeId(bool isIndex) + { + if(_typeIdMap == null) + { + _typeIdMap = new Dictionary<int, string>(); + } + + if(isIndex) + { + int index = _stream.readSize(); + string typeId; + if(!_typeIdMap.TryGetValue(index, out typeId)) + { + throw new UnmarshalOutOfBoundsException(); + } + return typeId; + } + else + { + string typeId = _stream.readString(); + _typeIdMap.Add(++_typeIdIndex, typeId); + return typeId; + } + } + + protected Type resolveClass(string typeId) + { + Type cls = null; + if(_typeIdCache == null) + { + _typeIdCache = new Dictionary<string, Type>(); // Lazy initialization. + } + else + { + _typeIdCache.TryGetValue(typeId, out cls); + } + + if(cls == typeof(EncapsDecoder)) // Marker for non-existent class. + { + cls = null; + } + else if(cls == null) + { + try + { + if(_classResolver != null) + { + cls = _classResolver(typeId); + _typeIdCache.Add(typeId, cls != null ? cls : typeof(EncapsDecoder)); + } + } + catch(Exception ex) + { + throw new NoValueFactoryException("no value factory", typeId, ex); + } + } + + return cls; + } + + protected Value newInstance(string typeId) + { + // + // Try to find a factory registered for the specific type. + // + var userFactory = _valueFactoryManager.find(typeId); + Value v = null; + if(userFactory != null) + { + v = userFactory(typeId); + } + + // + // If that fails, invoke the default factory if one has been + // registered. + // + if(v == null) + { + userFactory = _valueFactoryManager.find(""); + if(userFactory != null) + { + v = userFactory(typeId); + } + } + + // + // Last chance: try to instantiate the class dynamically. + // + if(v == null) + { + Type cls = resolveClass(typeId); + + if(cls != null) + { + try + { + Debug.Assert(!cls.IsAbstract && !cls.IsInterface); + v = (Value)IceInternal.AssemblyUtil.createInstance(cls); + } + catch(Exception ex) + { + throw new NoValueFactoryException("no value factory", typeId, ex); + } + } + } + + return v; + } + + protected void addPatchEntry(int index, ReadValueCallback cb) + { + Debug.Assert(index > 0); + + // + // Check if we already unmarshaled the instance. If that's the case, + // just call the callback and we're done. + // + Value obj; + if(_unmarshaledMap.TryGetValue(index, out obj)) + { + cb(obj); + return; + } + + if(_patchMap == null) + { + _patchMap = new Dictionary<int, LinkedList<ReadValueCallback>>(); + } + + // + // Add patch entry if the instance isn't unmarshaled yet, + // the callback will be called when the instance is + // unmarshaled. + // + LinkedList<ReadValueCallback> l; + if(!_patchMap.TryGetValue(index, out l)) + { + // + // We have no outstanding instances to be patched for this + // index, so make a new entry in the patch map. + // + l = new LinkedList<ReadValueCallback>(); + _patchMap.Add(index, l); + } + + // + // Append a patch entry for this instance. + // + l.AddLast(cb); + } + + protected void unmarshal(int index, Value v) + { + // + // Add the instance to the map of unmarshaled instances, this must + // be done before reading the instances (for circular references). + // + _unmarshaledMap.Add(index, v); + + // + // Read the instance. + // + v.iceRead(_stream); + + if(_patchMap != null) + { + // + // Patch all instances now that the instance is unmarshaled. + // + LinkedList<ReadValueCallback> l; + if(_patchMap.TryGetValue(index, out l)) + { + Debug.Assert(l.Count > 0); + + // + // Patch all pointers that refer to the instance. + // + foreach(ReadValueCallback cb in l) + { + cb(v); + } + + // + // Clear out the patch map for that index -- there is nothing left + // to patch for that index for the time being. + // + _patchMap.Remove(index); + } + } + + if((_patchMap == null || _patchMap.Count == 0) && _valueList == null) + { + try + { + v.ice_postUnmarshal(); + } + catch(System.Exception ex) + { + string s = "exception raised by ice_postUnmarshal:\n" + ex; + _stream.instance().initializationData().logger.warning(s); + } + } + else + { + if(_valueList == null) + { + _valueList = new List<Value>(); + } + _valueList.Add(v); + + if(_patchMap == null || _patchMap.Count == 0) + { + // + // Iterate over the instance list and invoke ice_postUnmarshal on + // each instance. We must do this after all instances have been + // unmarshaled in order to ensure that any instance data members + // have been properly patched. + // + foreach(var p in _valueList) + { + try + { + p.ice_postUnmarshal(); + } + catch(System.Exception ex) + { + string s = "exception raised by ice_postUnmarshal:\n" + ex; + _stream.instance().initializationData().logger.warning(s); + } + } + _valueList.Clear(); + } + } + } + + protected readonly InputStream _stream; + protected readonly Encaps _encaps; + protected readonly bool _sliceValues; + protected ValueFactoryManager _valueFactoryManager; + protected ClassResolver _classResolver; + + // + // Encapsulation attributes for object unmarshaling. + // + protected Dictionary<int, LinkedList<ReadValueCallback> > _patchMap; + private Dictionary<int, Value> _unmarshaledMap; + private Dictionary<int, string> _typeIdMap; + private int _typeIdIndex; + private List<Value> _valueList; + private Dictionary<string, Type> _typeIdCache; + } + + private sealed class EncapsDecoder10 : EncapsDecoder + { + internal EncapsDecoder10(InputStream stream, Encaps encaps, bool sliceValues, ValueFactoryManager f, + ClassResolver cr) + : base(stream, encaps, sliceValues, f, cr) + { + _sliceType = SliceType.NoSlice; + } + + internal override void readValue(ReadValueCallback cb) + { + Debug.Assert(cb != null); + + // + // Object references are encoded as a negative integer in 1.0. + // + int index = _stream.readInt(); + if(index > 0) + { + throw new MarshalException("invalid object id"); + } + index = -index; + + if(index == 0) + { + cb(null); + } + else + { + addPatchEntry(index, cb); + } + } + + internal override void throwException(UserExceptionFactory factory) + { + Debug.Assert(_sliceType == SliceType.NoSlice); + + // + // User exception with the 1.0 encoding start with a bool flag + // that indicates whether or not the exception has classes. + // + // This allows reading the pending instances even if some part of + // the exception was sliced. + // + bool usesClasses = _stream.readBool(); + + _sliceType = SliceType.ExceptionSlice; + _skipFirstSlice = false; + + // + // Read the first slice header. + // + startSlice(); + string mostDerivedId = _typeId; + while(true) + { + UserException userEx = null; + + // + // Use a factory if one was provided. + // + if(factory != null) + { + try + { + factory(_typeId); + } + catch(UserException ex) + { + userEx = ex; + } + } + + if(userEx == null) + { + userEx = _stream.createUserException(_typeId); + } + + // + // We found the exception. + // + if(userEx != null) + { + userEx.iceRead(_stream); + if(usesClasses) + { + readPendingValues(); + } + throw userEx; + + // Never reached. + } + + // + // Slice off what we don't understand. + // + skipSlice(); + try + { + startSlice(); + } + catch(UnmarshalOutOfBoundsException ex) + { + // + // An oversight in the 1.0 encoding means there is no marker to indicate + // the last slice of an exception. As a result, we just try to read the + // next type ID, which raises UnmarshalOutOfBoundsException when the + // input buffer underflows. + // + // Set the reason member to a more helpful message. + // + ex.reason = "unknown exception type `" + mostDerivedId + "'"; + throw; + } + } + } + + internal override void startInstance(SliceType sliceType) + { + Debug.Assert(_sliceType == sliceType); + _skipFirstSlice = true; + } + + internal override SlicedData endInstance(bool preserve) + { + // + // Read the Ice::Object slice. + // + if(_sliceType == SliceType.ValueSlice) + { + startSlice(); + int sz = _stream.readSize(); // For compatibility with the old AFM. + if(sz != 0) + { + throw new MarshalException("invalid Object slice"); + } + endSlice(); + } + + _sliceType = SliceType.NoSlice; + return null; + } + + internal override string startSlice() + { + // + // If first slice, don't read the header, it was already read in + // readInstance or throwException to find the factory. + // + if(_skipFirstSlice) + { + _skipFirstSlice = false; + return _typeId; + } + + // + // For instances, first read the type ID bool which indicates + // whether or not the type ID is encoded as a string or as an + // index. For exceptions, the type ID is always encoded as a + // string. + // + if(_sliceType == SliceType.ValueSlice) // For exceptions, the type ID is always encoded as a string + { + bool isIndex = _stream.readBool(); + _typeId = readTypeId(isIndex); + } + else + { + _typeId = _stream.readString(); + } + + _sliceSize = _stream.readInt(); + if(_sliceSize < 4) + { + throw new UnmarshalOutOfBoundsException(); + } + + return _typeId; + } + + internal override void endSlice() + { + } + + internal override void skipSlice() + { + if(_stream.instance().traceLevels().slicing > 0) + { + Logger logger = _stream.instance().initializationData().logger; + string slicingCat = _stream.instance().traceLevels().slicingCat; + if(_sliceType == SliceType.ValueSlice) + { + IceInternal.TraceUtil.traceSlicing("object", _typeId, slicingCat, logger); + } + else + { + IceInternal.TraceUtil.traceSlicing("exception", _typeId, slicingCat, logger); + } + } + + Debug.Assert(_sliceSize >= 4); + _stream.skip(_sliceSize - 4); + } + + internal override void readPendingValues() + { + int num; + do + { + num = _stream.readSize(); + for(int k = num; k > 0; --k) + { + readInstance(); + } + } + while(num > 0); + + if(_patchMap != null && _patchMap.Count > 0) + { + // + // If any entries remain in the patch map, the sender has sent an index for an instance, but failed + // to supply the instance. + // + throw new MarshalException("index for class received, but no instance"); + } + } + + private void readInstance() + { + int index = _stream.readInt(); + + if(index <= 0) + { + throw new MarshalException("invalid object id"); + } + + _sliceType = SliceType.ValueSlice; + _skipFirstSlice = false; + + // + // Read the first slice header. + // + startSlice(); + string mostDerivedId = _typeId; + Value v = null; + while(true) + { + // + // For the 1.0 encoding, the type ID for the base Object class + // marks the last slice. + // + if(_typeId.Equals(Value.ice_staticId())) + { + throw new NoValueFactoryException("", mostDerivedId); + } + + v = newInstance(_typeId); + + // + // We found a factory, we get out of this loop. + // + if(v != null) + { + break; + } + + // + // If slicing is disabled, stop unmarshaling. + // + if(!_sliceValues) + { + throw new NoValueFactoryException("no value factory found and slicing is disabled", _typeId); + } + + // + // Slice off what we don't understand. + // + skipSlice(); + startSlice(); // Read next Slice header for next iteration. + } + + // + // Unmarshal the instance and add it to the map of unmarshaled instances. + // + unmarshal(index, v); + } + + // Object/exception attributes + private SliceType _sliceType; + private bool _skipFirstSlice; + + // Slice attributes + private int _sliceSize; + private string _typeId; + } + + private sealed class EncapsDecoder11 : EncapsDecoder + { + internal EncapsDecoder11(InputStream stream, Encaps encaps, bool sliceValues, ValueFactoryManager f, + ClassResolver cr, CompactIdResolver r) + : base(stream, encaps, sliceValues, f, cr) + { + _compactIdResolver = r; + _current = null; + _valueIdIndex = 1; + } + + internal override void readValue(ReadValueCallback cb) + { + int index = _stream.readSize(); + if(index < 0) + { + throw new MarshalException("invalid object id"); + } + else if(index == 0) + { + if(cb != null) + { + cb(null); + } + } + else if(_current != null && (_current.sliceFlags & Protocol.FLAG_HAS_INDIRECTION_TABLE) != 0) + { + // + // When reading an instance within a slice and there's an + // indirect instance table, always read an indirect reference + // that points to an instance from the indirect instance table + // marshaled at the end of the Slice. + // + // Maintain a list of indirect references. Note that the + // indirect index starts at 1, so we decrement it by one to + // derive an index into the indirection table that we'll read + // at the end of the slice. + // + if(cb != null) + { + if(_current.indirectPatchList == null) + { + _current.indirectPatchList = new Stack<IndirectPatchEntry>(); + } + IndirectPatchEntry e = new IndirectPatchEntry(); + e.index = index - 1; + e.patcher = cb; + _current.indirectPatchList.Push(e); + } + } + else + { + readInstance(index, cb); + } + } + + internal override void throwException(UserExceptionFactory factory) + { + Debug.Assert(_current == null); + + push(SliceType.ExceptionSlice); + + // + // Read the first slice header. + // + startSlice(); + string mostDerivedId = _current.typeId; + while(true) + { + UserException userEx = null; + + // + // Use a factory if one was provided. + // + if(factory != null) + { + try + { + factory(_current.typeId); + } + catch(UserException ex) + { + userEx = ex; + } + } + + if(userEx == null) + { + userEx = _stream.createUserException(_current.typeId); + } + + // + // We found the exception. + // + if(userEx != null) + { + userEx.iceRead(_stream); + throw userEx; + + // Never reached. + } + + // + // Slice off what we don't understand. + // + skipSlice(); + + if((_current.sliceFlags & Protocol.FLAG_IS_LAST_SLICE) != 0) + { + if(mostDerivedId.StartsWith("::", StringComparison.Ordinal)) + { + throw new UnknownUserException(mostDerivedId.Substring(2)); + } + else + { + throw new UnknownUserException(mostDerivedId); + } + } + + startSlice(); + } + } + + internal override void startInstance(SliceType sliceType) + { + Debug.Assert(_current.sliceType == sliceType); + _current.skipFirstSlice = true; + } + + internal override SlicedData endInstance(bool preserve) + { + SlicedData slicedData = null; + if(preserve) + { + slicedData = readSlicedData(); + } + if(_current.slices != null) + { + _current.slices.Clear(); + _current.indirectionTables.Clear(); + } + _current = _current.previous; + return slicedData; + } + + internal override string startSlice() + { + // + // If first slice, don't read the header, it was already read in + // readInstance or throwException to find the factory. + // + if(_current.skipFirstSlice) + { + _current.skipFirstSlice = false; + return _current.typeId; + } + + _current.sliceFlags = _stream.readByte(); + + // + // Read the type ID, for instance slices the type ID is encoded as a + // string or as an index, for exceptions it's always encoded as a + // string. + // + if(_current.sliceType == SliceType.ValueSlice) + { + // + // Must be checked first! + // + if((_current.sliceFlags & Protocol.FLAG_HAS_TYPE_ID_COMPACT) == Protocol.FLAG_HAS_TYPE_ID_COMPACT) + { + _current.typeId = ""; + _current.compactId = _stream.readSize(); + } + else if((_current.sliceFlags & + (Protocol.FLAG_HAS_TYPE_ID_INDEX | Protocol.FLAG_HAS_TYPE_ID_STRING)) != 0) + { + _current.typeId = readTypeId((_current.sliceFlags & Protocol.FLAG_HAS_TYPE_ID_INDEX) != 0); + _current.compactId = -1; + } + else + { + // Only the most derived slice encodes the type ID for the compact format. + _current.typeId = ""; + _current.compactId = -1; + } + } + else + { + _current.typeId = _stream.readString(); + _current.compactId = -1; + } + + // + // Read the slice size if necessary. + // + if((_current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) != 0) + { + _current.sliceSize = _stream.readInt(); + if(_current.sliceSize < 4) + { + throw new UnmarshalOutOfBoundsException(); + } + } + else + { + _current.sliceSize = 0; + } + + return _current.typeId; + } + + internal override void endSlice() + { + if((_current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) != 0) + { + _stream.skipOptionals(); + } + + // + // Read the indirection table if one is present and transform the + // indirect patch list into patch entries with direct references. + // + if((_current.sliceFlags & Protocol.FLAG_HAS_INDIRECTION_TABLE) != 0) + { + // + // The table is written as a sequence<size> to conserve space. + // + int[] indirectionTable = new int[_stream.readAndCheckSeqSize(1)]; + for(int i = 0; i < indirectionTable.Length; ++i) + { + indirectionTable[i] = readInstance(_stream.readSize(), null); + } + + // + // Sanity checks. If there are optional members, it's possible + // that not all instance references were read if they are from + // unknown optional data members. + // + if(indirectionTable.Length == 0) + { + throw new MarshalException("empty indirection table"); + } + if((_current.indirectPatchList == null || _current.indirectPatchList.Count == 0) && + (_current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) == 0) + { + throw new MarshalException("no references to indirection table"); + } + + // + // Convert indirect references into direct references. + // + if(_current.indirectPatchList != null) + { + foreach(IndirectPatchEntry e in _current.indirectPatchList) + { + Debug.Assert(e.index >= 0); + if(e.index >= indirectionTable.Length) + { + throw new MarshalException("indirection out of range"); + } + addPatchEntry(indirectionTable[e.index], e.patcher); + } + _current.indirectPatchList.Clear(); + } + } + } + + internal override void skipSlice() + { + if(_stream.instance().traceLevels().slicing > 0) + { + Logger logger = _stream.instance().initializationData().logger; + string slicingCat = _stream.instance().traceLevels().slicingCat; + if(_current.sliceType == SliceType.ExceptionSlice) + { + IceInternal.TraceUtil.traceSlicing("exception", _current.typeId, slicingCat, logger); + } + else + { + IceInternal.TraceUtil.traceSlicing("object", _current.typeId, slicingCat, logger); + } + } + + int start = _stream.pos(); + + if((_current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) != 0) + { + Debug.Assert(_current.sliceSize >= 4); + _stream.skip(_current.sliceSize - 4); + } + else + { + if(_current.sliceType == SliceType.ValueSlice) + { + throw new NoValueFactoryException("no value factory found and compact format prevents " + + "slicing (the sender should use the sliced format " + + "instead)", _current.typeId); + } + else + { + if(_current.typeId.StartsWith("::", StringComparison.Ordinal)) + { + throw new UnknownUserException(_current.typeId.Substring(2)); + } + else + { + throw new UnknownUserException(_current.typeId); + } + } + } + + // + // Preserve this slice. + // + SliceInfo info = new SliceInfo(); + info.typeId = _current.typeId; + info.compactId = _current.compactId; + info.hasOptionalMembers = (_current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) != 0; + info.isLastSlice = (_current.sliceFlags & Protocol.FLAG_IS_LAST_SLICE) != 0; + IceInternal.ByteBuffer b = _stream.getBuffer().b; + int end = b.position(); + int dataEnd = end; + if(info.hasOptionalMembers) + { + // + // Don't include the optional member end marker. It will be re-written by + // endSlice when the sliced data is re-written. + // + --dataEnd; + } + info.bytes = new byte[dataEnd - start]; + b.position(start); + b.get(info.bytes); + b.position(end); + + if(_current.slices == null) + { + _current.slices = new List<SliceInfo>(); + _current.indirectionTables = new List<int[]>(); + } + + // + // Read the indirect instance table. We read the instances or their + // IDs if the instance is a reference to an already unmarshaled + // instance. + // + if((_current.sliceFlags & Protocol.FLAG_HAS_INDIRECTION_TABLE) != 0) + { + int[] indirectionTable = new int[_stream.readAndCheckSeqSize(1)]; + for(int i = 0; i < indirectionTable.Length; ++i) + { + indirectionTable[i] = readInstance(_stream.readSize(), null); + } + _current.indirectionTables.Add(indirectionTable); + } + else + { + _current.indirectionTables.Add(null); + } + + _current.slices.Add(info); + } + + internal override bool readOptional(int readTag, OptionalFormat expectedFormat) + { + if(_current == null) + { + return _stream.readOptImpl(readTag, expectedFormat); + } + else if((_current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) != 0) + { + return _stream.readOptImpl(readTag, expectedFormat); + } + return false; + } + + private int readInstance(int index, ReadValueCallback cb) + { + Debug.Assert(index > 0); + + if(index > 1) + { + if(cb != null) + { + addPatchEntry(index, cb); + } + return index; + } + + push(SliceType.ValueSlice); + + // + // Get the instance ID before we start reading slices. If some + // slices are skipped, the indirect instance table are still read and + // might read other instances. + // + index = ++_valueIdIndex; + + // + // Read the first slice header. + // + startSlice(); + string mostDerivedId = _current.typeId; + Value v = null; + while(true) + { + bool updateCache = false; + + if(_current.compactId >= 0) + { + updateCache = true; + + // + // Translate a compact (numeric) type ID into a class. + // + if(_compactIdCache == null) + { + _compactIdCache = new Dictionary<int, Type>(); // Lazy initialization. + } + else + { + // + // Check the cache to see if we've already translated the compact type ID into a class. + // + Type cls = null; + _compactIdCache.TryGetValue(_current.compactId, out cls); + if(cls != null) + { + try + { + Debug.Assert(!cls.IsAbstract && !cls.IsInterface); + v = (Value)IceInternal.AssemblyUtil.createInstance(cls); + updateCache = false; + } + catch(Exception ex) + { + throw new NoValueFactoryException("no value factory", "compact ID " + + _current.compactId, ex); + } + } + } + + // + // If we haven't already cached a class for the compact ID, then try to translate the + // compact ID into a type ID. + // + if(v == null) + { + _current.typeId = ""; + if(_compactIdResolver != null) + { + try + { + _current.typeId = _compactIdResolver(_current.compactId); + } + catch(LocalException) + { + throw; + } + catch(System.Exception ex) + { + throw new MarshalException("exception in CompactIdResolver for ID " + + _current.compactId, ex); + } + } + + if(_current.typeId.Length == 0) + { + _current.typeId = _stream.instance().resolveCompactId(_current.compactId); + } + } + } + + if(v == null && _current.typeId.Length > 0) + { + v = newInstance(_current.typeId); + } + + if(v != null) + { + if(updateCache) + { + Debug.Assert(_current.compactId >= 0); + _compactIdCache.Add(_current.compactId, v.GetType()); + } + + // + // We have an instance, get out of this loop. + // + break; + } + + // + // If slicing is disabled, stop unmarshaling. + // + if(!_sliceValues) + { + throw new NoValueFactoryException("no value factory found and slicing is disabled", + _current.typeId); + } + + // + // Slice off what we don't understand. + // + skipSlice(); + + // + // If this is the last slice, keep the instance as an opaque + // UnknownSlicedValue object. + // + if((_current.sliceFlags & Protocol.FLAG_IS_LAST_SLICE) != 0) + { + // + // Provide a factory with an opportunity to supply the instance. + // We pass the "::Ice::Object" ID to indicate that this is the + // last chance to preserve the instance. + // + v = newInstance(Value.ice_staticId()); + if(v == null) + { + v = new UnknownSlicedValue(mostDerivedId); + } + + break; + } + + startSlice(); // Read next Slice header for next iteration. + } + + // + // Unmarshal the instance. + // + unmarshal(index, v); + + if(_current == null && _patchMap != null && _patchMap.Count > 0) + { + // + // If any entries remain in the patch map, the sender has sent an index for an instance, but failed + // to supply the instance. + // + throw new MarshalException("index for class received, but no instance"); + } + + if(cb != null) + { + cb(v); + } + return index; + } + + private SlicedData readSlicedData() + { + if(_current.slices == null) // No preserved slices. + { + return null; + } + + // + // The _indirectionTables member holds the indirection table for each slice + // in _slices. + // + Debug.Assert(_current.slices.Count == _current.indirectionTables.Count); + for(int n = 0; n < _current.slices.Count; ++n) + { + // + // We use the "instances" list in SliceInfo to hold references + // to the target instances. Note that the instances might not have + // been read yet in the case of a circular reference to an + // enclosing instance. + // + int[] table = _current.indirectionTables[n]; + SliceInfo info = _current.slices[n]; + info.instances = new Value[table != null ? table.Length : 0]; + for(int j = 0; j < info.instances.Length; ++j) + { + IceInternal.ArrayPatcher<Value> patcher = + new IceInternal.ArrayPatcher<Value>(Value.ice_staticId(), info.instances, j); + addPatchEntry(table[j], patcher.patch); + } + } + + return new SlicedData(_current.slices.ToArray()); + } + + private void push(SliceType sliceType) + { + if(_current == null) + { + _current = new InstanceData(null); + } + else + { + _current = _current.next == null ? new InstanceData(_current) : _current.next; + } + _current.sliceType = sliceType; + _current.skipFirstSlice = false; + } + + private sealed class IndirectPatchEntry + { + public int index; + public ReadValueCallback patcher; + } + + private sealed class InstanceData + { + internal InstanceData(InstanceData previous) + { + if(previous != null) + { + previous.next = this; + } + this.previous = previous; + this.next = null; + } + + // Instance attributes + internal SliceType sliceType; + internal bool skipFirstSlice; + internal List<SliceInfo> slices; // Preserved slices. + internal List<int[]> indirectionTables; + + // Slice attributes + internal byte sliceFlags; + internal int sliceSize; + internal string typeId; + internal int compactId; + internal Stack<IndirectPatchEntry> indirectPatchList; + + internal InstanceData previous; + internal InstanceData next; + } + + private CompactIdResolver _compactIdResolver; + private InstanceData _current; + private int _valueIdIndex; // The ID of the next instance to unmarshal. + private Dictionary<int, Type> _compactIdCache; + } + + private sealed class Encaps + { + internal void reset() + { + decoder = null; + } + + internal void setEncoding(EncodingVersion encoding) + { + this.encoding = encoding; + encoding_1_0 = encoding.Equals(Util.Encoding_1_0); + } + + internal int start; + internal int sz; + internal EncodingVersion encoding; + internal bool encoding_1_0; + + internal EncapsDecoder decoder; + + internal Encaps next; + } + + // + // The encoding version to use when there's no encapsulation to + // read from. This is for example used to read message headers. + // + private EncodingVersion _encoding; + + private bool isEncoding_1_0() + { + return _encapsStack != null ? _encapsStack.encoding_1_0 : _encoding.Equals(Util.Encoding_1_0); + } + + private Encaps _encapsStack; + private Encaps _encapsCache; + + private void initEncaps() + { + if(_encapsStack == null) // Lazy initialization + { + _encapsStack = _encapsCache; + if(_encapsStack != null) + { + _encapsCache = _encapsCache.next; + } + else + { + _encapsStack = new Encaps(); + } + _encapsStack.setEncoding(_encoding); + _encapsStack.sz = _buf.b.limit(); + } + + if(_encapsStack.decoder == null) // Lazy initialization. + { + if(_encapsStack.encoding_1_0) + { + _encapsStack.decoder = new EncapsDecoder10(this, _encapsStack, _sliceValues, _valueFactoryManager, + _classResolver); + } + else + { + _encapsStack.decoder = new EncapsDecoder11(this, _encapsStack, _sliceValues, _valueFactoryManager, + _classResolver, _compactIdResolver); + } + } + } + + private bool _sliceValues; + private bool _traceSlicing; + + private int _startSeq; + private int _minSeqSize; + + private ValueFactoryManager _valueFactoryManager; + private Logger _logger; + private CompactIdResolver _compactIdResolver; + private ClassResolver _classResolver; + } + + /// <summary> + /// Base class for extracting class instances from an input stream. + /// </summary> + public abstract class ValueReader : Value + { + /// <summary> + /// Read the instance's data members. + /// </summary> + /// <param name="inStream">The input stream to read from.</param> + public abstract void read(InputStream inStream); + + public override void iceWrite(OutputStream os) + { + Debug.Assert(false); + } + + public override void iceRead(InputStream istr) + { + read(istr); + } + } + +} diff --git a/csharp/src/Ice/Instance.cs b/csharp/src/Ice/Instance.cs index 9998fde2a81..436e0908bc1 100644 --- a/csharp/src/Ice/Instance.cs +++ b/csharp/src/Ice/Instance.cs @@ -83,13 +83,6 @@ namespace IceInternal return _defaultsAndOverrides; } -#if COMPACT || SILVERLIGHT - public string[] factoryAssemblies() - { - return _factoryAssemblies; - } -#endif - public RouterManager routerManager() { lock(this) @@ -174,20 +167,6 @@ namespace IceInternal } } - public ObjectFactoryManager servantFactoryManager() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - Debug.Assert(_servantFactoryManager != null); - return _servantFactoryManager; - } - } - public ObjectAdapterFactory objectAdapterFactory() { lock(this) @@ -273,7 +252,6 @@ namespace IceInternal } } -#if !SILVERLIGHT public EndpointHostResolver endpointHostResolver() { lock(this) @@ -287,7 +265,7 @@ namespace IceInternal return _endpointHostResolver; } } -#endif + public RetryQueue retryQueue() { @@ -358,6 +336,13 @@ namespace IceInternal return _batchAutoFlushSize; } + public Ice.ToStringMode + toStringMode() + { + // No mutex lock, immutable + return _toStringMode; + } + public int cacheMessageBuffers() { // No mutex lock, immutable. @@ -381,17 +366,6 @@ namespace IceInternal return _implicitContext; } - public Ice.Identity stringToIdentity(string s) - { - return Ice.Util.stringToIdentity(s); - } - - public string identityToString(Ice.Identity ident) - { - return Ice.Util.identityToString(ident); - } - - public Ice.ObjectPrx createAdmin(Ice.ObjectAdapter adminAdapter, Ice.Identity adminIdentity) { @@ -689,6 +663,47 @@ namespace IceInternal _initData.threadHook = threadHook; } + public Type resolveClass(string id) + { + Type c = AssemblyUtil.findType(this, typeToClass(id)); + + // + // Ensure the class is instantiable. + // + if(c != null && !c.IsAbstract && !c.IsInterface) + { + return c; + } + + return null; + } + + public string resolveCompactId(int compactId) + { + String className = "IceCompactId.TypeId_" + compactId; + try + { + Type c = AssemblyUtil.findType(this, className); + if(c != null) + { + return (string)c.GetField("typeId").GetValue(null); + } + } + catch(Exception) + { + } + return ""; + } + + private static string typeToClass(string id) + { + if(!id.StartsWith("::", StringComparison.Ordinal)) + { + throw new Ice.MarshalException("expected type id but received `" + id + "'"); + } + return id.Substring(2).Replace("::", "."); + } + // // Only for use by Ice.CommunicatorI // @@ -703,10 +718,10 @@ namespace IceInternal { _initData.properties = Ice.Util.createProperties(); } -#if !SILVERLIGHT && !UNITY + lock(_staticLock) { - if(!_oneOfDone) + if(!_oneOffDone) { string stdOut = _initData.properties.getProperty("Ice.StdOut"); string stdErr = _initData.properties.getProperty("Ice.StdErr"); @@ -726,14 +741,14 @@ namespace IceInternal throw fe; } outStream.AutoFlush = true; - System.Console.Out.Close(); - System.Console.SetOut(outStream); + Console.Out.Close(); + Console.SetOut(outStream); } if(stdErr.Length > 0) { if(stdErr.Equals(stdOut)) { - System.Console.SetError(outStream); + Console.SetError(outStream); } else { @@ -749,33 +764,20 @@ namespace IceInternal throw fe; } errStream.AutoFlush = true; - System.Console.Error.Close(); - System.Console.SetError(errStream); + Console.Error.Close(); + Console.SetError(errStream); } } - _oneOfDone = true; + _oneOffDone = true; } } -#endif if(_initData.logger == null) { -#if !SILVERLIGHT && !UNITY string logfile = _initData.properties.getProperty("Ice.LogFile"); - if(_initData.properties.getPropertyAsInt("Ice.UseSyslog") > 0 && - AssemblyUtil.platform_ != AssemblyUtil.Platform.Windows) - { - if(logfile.Length != 0) - { - throw new Ice.InitializationException("Ice.LogFile and Ice.UseSyslog cannot both be set."); - } - _initData.logger = new Ice.SysLoggerI(_initData.properties.getProperty("Ice.ProgramName"), - _initData.properties.getPropertyWithDefault("Ice.SyslogFacility", "LOG_USER")); - } - else if(logfile.Length != 0) + if(logfile.Length != 0) { - _initData.logger = new Ice.FileLoggerI(_initData.properties.getProperty("Ice.ProgramName"), logfile); } @@ -784,23 +786,15 @@ namespace IceInternal // // Ice.ConsoleListener is enabled by default. // -# if COMPACT - _initData.logger = - new Ice.ConsoleLoggerI(_initData.properties.getProperty("Ice.ProgramName")); -# else - bool console = - _initData.properties.getPropertyAsIntWithDefault("Ice.ConsoleListener", 1) > 0; + bool console = _initData.properties.getPropertyAsIntWithDefault("Ice.ConsoleListener", 1) > 0; _initData.logger = new Ice.TraceLoggerI(_initData.properties.getProperty("Ice.ProgramName"), console); -# endif } -#else + if(Ice.Util.getProcessLogger() is Ice.LoggerI) { - _initData.logger = - new Ice.ConsoleLoggerI(_initData.properties.getProperty("Ice.ProgramName")); + _initData.logger = new Ice.ConsoleLoggerI(_initData.properties.getProperty("Ice.ProgramName")); } -#endif else { _initData.logger = Ice.Util.getProcessLogger(); @@ -823,10 +817,6 @@ namespace IceInternal new ACMConfig(_initData.properties, _initData.logger, "Ice.ACM", new ACMConfig(true))); -#if COMPACT || SILVERLIGHT - char[] separators = { ' ', '\t', '\n', '\r' }; - _factoryAssemblies = _initData.properties.getProperty("Ice.FactoryAssemblies").Split(separators); -#endif { const int defaultMessageSizeMax = 1024; int num = @@ -866,6 +856,24 @@ namespace IceInternal } } + string toStringModeStr = _initData.properties.getPropertyWithDefault("Ice.ToStringMode", "Unicode"); + if(toStringModeStr == "Unicode") + { + _toStringMode = Ice.ToStringMode.Unicode; + } + else if(toStringModeStr == "ASCII") + { + _toStringMode = Ice.ToStringMode.ASCII; + } + else if(toStringModeStr == "Compat") + { + _toStringMode = Ice.ToStringMode.Compat; + } + else + { + throw new Ice.InitializationException("The value for Ice.ToStringMode must be Unicode, ASCII or Compat"); + } + _cacheMessageBuffers = _initData.properties.getPropertyAsIntWithDefault("Ice.CacheMessageBuffers", 2); _implicitContext = Ice.ImplicitContextI.create(_initData.properties.getProperty("Ice.ImplicitContext")); @@ -909,14 +917,14 @@ namespace IceInternal ProtocolInstance udpInstance = new ProtocolInstance(this, Ice.UDPEndpointType.value, "udp", false); _endpointFactoryManager.add(new UdpEndpointFactory(udpInstance)); - -#if !SILVERLIGHT _pluginManager = new Ice.PluginManagerI(communicator); -#endif - _outgoingConnectionFactory = new OutgoingConnectionFactory(communicator, this); + if(_initData.valueFactoryManager == null) + { + _initData.valueFactoryManager = new ValueFactoryManagerI(); + } - _servantFactoryManager = new ObjectFactoryManager(); + _outgoingConnectionFactory = new OutgoingConnectionFactory(communicator, this); _objectAdapterFactory = new ObjectAdapterFactory(this, communicator); @@ -935,10 +943,8 @@ namespace IceInternal // Load plug-ins. // Debug.Assert(_serverThreadPool == null); -#if !SILVERLIGHT Ice.PluginManagerI pluginManagerImpl = (Ice.PluginManagerI)_pluginManager; pluginManagerImpl.loadPlugins(ref args); -#endif // // Add WS and WSS endpoint factories if TCP/SSL factories are installed. @@ -947,13 +953,13 @@ namespace IceInternal if(tcpFactory != null) { ProtocolInstance instance = new ProtocolInstance(this, Ice.WSEndpointType.value, "ws", false); - _endpointFactoryManager.add(new WSEndpointFactory(instance, tcpFactory.clone(instance))); + _endpointFactoryManager.add(new WSEndpointFactory(instance, tcpFactory.clone(instance, null))); } EndpointFactory sslFactory = _endpointFactoryManager.get(Ice.SSLEndpointType.value); if(sslFactory != null) { ProtocolInstance instance = new ProtocolInstance(this, Ice.WSSEndpointType.value, "wss", true); - _endpointFactoryManager.add(new WSEndpointFactory(instance, sslFactory.clone(instance))); + _endpointFactoryManager.add(new WSEndpointFactory(instance, sslFactory.clone(instance, null))); } // @@ -1010,7 +1016,7 @@ namespace IceInternal PropertiesAdminI propsAdmin = null; if(_adminFacetFilter.Count == 0 || _adminFacetFilter.Contains(propertiesFacetName)) { - propsAdmin= new PropertiesAdminI(_initData.properties, _initData.logger); + propsAdmin= new PropertiesAdminI(this); _adminFacets.Add(propertiesFacetName, propsAdmin); } @@ -1047,40 +1053,26 @@ namespace IceInternal // try { -#if !SILVERLIGHT - if(initializationData().properties.getProperty("Ice.ThreadPriority").Length > 0) - { - ThreadPriority priority = IceInternal.Util.stringToThreadPriority( - initializationData().properties.getProperty("Ice.ThreadPriority")); - _timer = new Timer(this, priority); - } - else - { - _timer = new Timer(this); - } -#else - _timer = new Timer(this); -#endif + _timer = new Timer(this, Util.stringToThreadPriority( + initializationData().properties.getProperty("Ice.ThreadPriority"))); } - catch(System.Exception ex) + catch(Exception ex) { string s = "cannot create thread for timer:\n" + ex; _initData.logger.error(s); throw; } -#if !SILVERLIGHT try { _endpointHostResolver = new EndpointHostResolver(this); } - catch(System.Exception ex) + catch(Exception ex) { string s = "cannot create thread for endpoint host resolver:\n" + ex; _initData.logger.error(s); throw; } -#endif _clientThreadPool = new ThreadPool(this, "Ice.ThreadPool.Client", 0); // @@ -1110,19 +1102,17 @@ namespace IceInternal // // Show process id if requested (but only once). // -#if !SILVERLIGHT lock(this) { if(!_printProcessIdDone && _initData.properties.getPropertyAsInt("Ice.PrintProcessId") > 0) { using(Process p = Process.GetCurrentProcess()) { - System.Console.WriteLine(p.Id); + Console.WriteLine(p.Id); } _printProcessIdDone = true; } } -#endif // // Server thread pool initialization is lazy in serverThreadPool(). @@ -1133,12 +1123,11 @@ namespace IceInternal // initialization until after it has interacted directly with the // plug-ins. // -#if !SILVERLIGHT if(_initData.properties.getPropertyAsIntWithDefault("Ice.InitPlugins", 1) > 0) { pluginManagerImpl.initializePlugins(); } -#endif + // // This must be done last as this call creates the Ice.Admin object adapter // and eventually registers a process proxy with the Ice locator (allowing @@ -1231,12 +1220,10 @@ namespace IceInternal { _asyncIOThread.destroy(); } -#if !SILVERLIGHT if(_endpointHostResolver != null) { _endpointHostResolver.destroy(); } -#endif // // Wait for all the threads to be finished. @@ -1257,17 +1244,19 @@ namespace IceInternal { _asyncIOThread.joinWithThread(); } -#if !SILVERLIGHT if(_endpointHostResolver != null) { _endpointHostResolver.joinWithThread(); } -#endif - if(_servantFactoryManager != null) + foreach(Ice.ObjectFactory factory in _objectFactoryMap.Values) { - _servantFactoryManager.destroy(); +// Disable Obsolete warning/error +#pragma warning disable 612, 618 + factory.destroy(); +#pragma warning restore 612, 618 } + _objectFactoryMap.Clear(); if(_routerManager != null) { @@ -1316,12 +1305,9 @@ namespace IceInternal _serverThreadPool = null; _clientThreadPool = null; _asyncIOThread = null; -#if !SILVERLIGHT _endpointHostResolver = null; -#endif _timer = null; - _servantFactoryManager = null; _referenceFactory = null; _requestHandlerFactory = null; _proxyFactory = null; @@ -1382,6 +1368,32 @@ namespace IceInternal } } + public void addObjectFactory(Ice.ObjectFactory factory, string id) + { + lock(this) + { + // + // Create a ValueFactory wrapper around the given ObjectFactory and register the wrapper + // with the value factory manager. This may raise AlreadyRegisteredException. + // +// Disable Obsolete warning/error +#pragma warning disable 612, 618 + _initData.valueFactoryManager.add((string type) => { return factory.create(type); }, id); +#pragma warning restore 612, 618 + _objectFactoryMap.Add(id, factory); + } + } + + public Ice.ObjectFactory findObjectFactory(string id) + { + lock(this) + { + Ice.ObjectFactory factory = null; + _objectFactoryMap.TryGetValue(id, out factory); + return factory; + } + } + internal void updateConnectionObservers() { try @@ -1410,12 +1422,10 @@ namespace IceInternal } Debug.Assert(_objectAdapterFactory != null); _objectAdapterFactory.updateThreadObservers(); -#if !SILVERLIGHT if(_endpointHostResolver != null) { _endpointHostResolver.updateObserver(); } -#endif if(_asyncIOThread != null) { _asyncIOThread.updateObserver(); @@ -1531,11 +1541,9 @@ namespace IceInternal private Ice.InitializationData _initData; // Immutable, not reset by destroy(). private TraceLevels _traceLevels; // Immutable, not reset by destroy(). private DefaultsAndOverrides _defaultsAndOverrides; // Immutable, not reset by destroy(). -#if COMPACT || SILVERLIGHT - private string[] _factoryAssemblies; // Immutable, not reset by destroy(). -#endif private int _messageSizeMax; // Immutable, not reset by destroy(). private int _batchAutoFlushSize; // Immutable, not reset by destroy(). + private Ice.ToStringMode _toStringMode; // Immutable, not reset by destroy(). private int _cacheMessageBuffers; // Immutable, not reset by destroy(). private ACMConfig _clientACM; // Immutable, not reset by destroy(). private ACMConfig _serverACM; // Immutable, not reset by destroy(). @@ -1546,7 +1554,6 @@ namespace IceInternal private RequestHandlerFactory _requestHandlerFactory; private ProxyFactory _proxyFactory; private OutgoingConnectionFactory _outgoingConnectionFactory; - private ObjectFactoryManager _servantFactoryManager; private ObjectAdapterFactory _objectAdapterFactory; private int _protocolSupport; private bool _preferIPv6; @@ -1554,9 +1561,7 @@ namespace IceInternal private ThreadPool _clientThreadPool; private ThreadPool _serverThreadPool; private AsyncIOThread _asyncIOThread; -#if !SILVERLIGHT private EndpointHostResolver _endpointHostResolver; -#endif private Timer _timer; private RetryQueue _retryQueue; private EndpointFactoryManager _endpointFactoryManager; @@ -1567,15 +1572,9 @@ namespace IceInternal private HashSet<string> _adminFacetFilter = new HashSet<string>(); private Ice.Identity _adminIdentity; private Dictionary<short, BufSizeWarnInfo> _setBufSizeWarn = new Dictionary<short, BufSizeWarnInfo>(); - -#if !SILVERLIGHT private static bool _printProcessIdDone = false; -#endif - -#if !SILVERLIGHT && !UNITY - private static bool _oneOfDone = false; -#endif - - private static System.Object _staticLock = new System.Object(); + private static bool _oneOffDone = false; + private Dictionary<string, Ice.ObjectFactory> _objectFactoryMap = new Dictionary<string, Ice.ObjectFactory>(); + private static object _staticLock = new object(); } } diff --git a/csharp/src/Ice/InstrumentationI.cs b/csharp/src/Ice/InstrumentationI.cs index 20fc6627ffc..ae00e85e10a 100644 --- a/csharp/src/Ice/InstrumentationI.cs +++ b/csharp/src/Ice/InstrumentationI.cs @@ -17,7 +17,7 @@ namespace IceInternal using IceMX; public class ObserverWithDelegate<T, O> : Observer<T> - where T : Metrics, new() + where T : Metrics, new() where O : Ice.Instrumentation.Observer { override public void @@ -40,7 +40,7 @@ namespace IceInternal } } - override public void + override public void failed(string exceptionName) { base.failed(exceptionName); @@ -67,30 +67,30 @@ namespace IceInternal where ObserverImpl : ObserverWithDelegate<S, Observer>, Observer, new() where Observer : Ice.Instrumentation.Observer { - ObserverImpl obsv = base.getObserver<S, ObserverImpl>(mapName, helper); + ObserverImpl obsv = getObserver<S, ObserverImpl>(mapName, helper); if(obsv != null) { obsv.setDelegate(del); - return (Observer)obsv; + return obsv; } return del; } protected O delegate_; - }; + } public class ObserverFactoryWithDelegate<T, OImpl, O> : ObserverFactory<T, OImpl> - where T : Metrics, new() + where T : Metrics, new() where OImpl : ObserverWithDelegate<T, O>, O, new() where O : Ice.Instrumentation.Observer { - public ObserverFactoryWithDelegate(IceInternal.MetricsAdminI metrics, string name) : base(metrics, name) + public ObserverFactoryWithDelegate(MetricsAdminI metrics, string name) : base(metrics, name) { } public O getObserver(MetricsHelper<T> helper, O del) { - OImpl o = base.getObserver(helper); + OImpl o = getObserver(helper); if(o != null) { o.setDelegate(del); @@ -101,7 +101,7 @@ namespace IceInternal public O getObserver(MetricsHelper<T> helper, object observer, O del) { - OImpl o = base.getObserver(helper, observer); + OImpl o = getObserver(helper, observer); if(o != null) { o.setDelegate(del); @@ -124,7 +124,7 @@ namespace IceInternal r.add("endpointIsSecure", cl.GetMethod("getEndpointInfo"), cli.GetMethod("secure")); r.add("endpointTimeout", cl.GetMethod("getEndpointInfo"), cli.GetField("timeout")); r.add("endpointCompress", cl.GetMethod("getEndpointInfo"), cli.GetField("compress")); - + cli = typeof(Ice.IPEndpointInfo); r.add("endpointHost", cl.GetMethod("getEndpointInfo"), cli.GetField("host")); r.add("endpointPort", cl.GetMethod("getEndpointInfo"), cli.GetField("port")); @@ -137,24 +137,24 @@ namespace IceInternal r.add("incoming", cl.GetMethod("getConnectionInfo"), cli.GetField("incoming")); r.add("adapterName", cl.GetMethod("getConnectionInfo"), cli.GetField("adapterName")); r.add("connectionId", cl.GetMethod("getConnectionInfo"), cli.GetField("connectionId")); - + cli = typeof(Ice.IPConnectionInfo); r.add("localHost", cl.GetMethod("getConnectionInfo"), cli.GetField("localAddress")); r.add("localPort", cl.GetMethod("getConnectionInfo"), cli.GetField("localPort")); r.add("remoteHost", cl.GetMethod("getConnectionInfo"), cli.GetField("remoteAddress")); r.add("remotePort", cl.GetMethod("getConnectionInfo"), cli.GetField("remotePort")); - + cli = typeof(Ice.UDPConnectionInfo); r.add("mcastHost", cl.GetMethod("getConnectionInfo"), cli.GetField("mcastAddress")); r.add("mcastPort", cl.GetMethod("getConnectionInfo"), cli.GetField("mcastPort")); - - AttrsUtil.addEndpointAttributes<T>(r, cl); + + addEndpointAttributes<T>(r, cl); } } class ConnectionHelper : MetricsHelper<ConnectionMetrics> { - class AttributeResolverI : MetricsHelper<ConnectionMetrics>.AttributeResolver + class AttributeResolverI : AttributeResolver { public AttributeResolverI() { @@ -164,17 +164,17 @@ namespace IceInternal add("parent", cl.GetMethod("getParent")); add("id", cl.GetMethod("getId")); add("state", cl.GetMethod("getState")); - AttrsUtil.addConnectionAttributes<ConnectionMetrics>(this, cl); + AttrsUtil.addConnectionAttributes(this, cl); } catch(Exception) { Debug.Assert(false); } } - }; + } static AttributeResolver _attributes = new AttributeResolverI(); - - public ConnectionHelper(Ice.ConnectionInfo con, Ice.Endpoint endpt, Ice.Instrumentation.ConnectionState state) + + public ConnectionHelper(Ice.ConnectionInfo con, Ice.Endpoint endpt, Ice.Instrumentation.ConnectionState state) : base(_attributes) { _connectionInfo = con; @@ -187,9 +187,9 @@ namespace IceInternal if(_id == null) { StringBuilder os = new StringBuilder(); - if(_connectionInfo is Ice.IPConnectionInfo) + Ice.IPConnectionInfo info = getIPConnectionInfo(); + if(info != null) { - Ice.IPConnectionInfo info = (Ice.IPConnectionInfo)_connectionInfo; os.Append(info.localAddress).Append(':').Append(info.localPort); os.Append(" -> "); os.Append(info.remoteAddress).Append(':').Append(info.remotePort); @@ -226,7 +226,7 @@ namespace IceInternal return ""; } } - + public string getParent() { if(_connectionInfo.adapterName != null && _connectionInfo.adapterName.Length > 0) @@ -238,7 +238,7 @@ namespace IceInternal return "Communicator"; } } - + public Ice.ConnectionInfo getConnectionInfo() { return _connectionInfo; @@ -258,16 +258,29 @@ namespace IceInternal return _endpointInfo; } + private Ice.IPConnectionInfo + getIPConnectionInfo() + { + for(Ice.ConnectionInfo p = _connectionInfo; p != null; p = p.underlying) + { + if(p is Ice.IPConnectionInfo) + { + return (Ice.IPConnectionInfo)p; + } + } + return null; + } + readonly private Ice.ConnectionInfo _connectionInfo; readonly private Ice.Endpoint _endpoint; readonly private Ice.Instrumentation.ConnectionState _state; private string _id; private Ice.EndpointInfo _endpointInfo; - }; + } class DispatchHelper : MetricsHelper<DispatchMetrics> { - class AttributeResolverI : MetricsHelper<DispatchMetrics>.AttributeResolver + class AttributeResolverI : AttributeResolver { public AttributeResolverI() { @@ -276,9 +289,9 @@ namespace IceInternal Type cl = typeof(DispatchHelper); add("parent", cl.GetMethod("getParent")); add("id", cl.GetMethod("getId")); - - AttrsUtil.addConnectionAttributes<DispatchMetrics>(this, cl); - + + AttrsUtil.addConnectionAttributes(this, cl); + Type clc = typeof(Ice.Current); add("operation", cl.GetMethod("getCurrent"), clc.GetField("operation")); add("identity", cl.GetMethod("getIdentity")); @@ -291,9 +304,9 @@ namespace IceInternal Debug.Assert(false); } } - }; + } static AttributeResolver _attributes = new AttributeResolverI(); - + public DispatchHelper(Ice.Current current, int size) : base(_attributes) { _current = current; @@ -317,7 +330,7 @@ namespace IceInternal { v.size += _size; } - + public string getMode() { return _current.requestId == 0 ? "oneway" : "twoway"; @@ -342,7 +355,7 @@ namespace IceInternal { return _current.adapter.getName(); } - + public Ice.ConnectionInfo getConnectionInfo() { if(_current.con != null) @@ -351,7 +364,7 @@ namespace IceInternal } return null; } - + public Ice.Endpoint getEndpoint() { if(_current.con != null) @@ -365,7 +378,7 @@ namespace IceInternal { return _current.con; } - + public Ice.EndpointInfo getEndpointInfo() { if(_current.con != null && _endpointInfo == null) @@ -379,22 +392,22 @@ namespace IceInternal { return _current; } - + public string getIdentity() { return _current.adapter.getCommunicator().identityToString(_current.id); } - + readonly private Ice.Current _current; readonly private int _size; private string _id; private Ice.EndpointInfo _endpointInfo; - }; + } class InvocationHelper : MetricsHelper<InvocationMetrics> { - class AttributeResolverI : MetricsHelper<InvocationMetrics>.AttributeResolver - { + class AttributeResolverI : AttributeResolver + { public AttributeResolverI() { try @@ -402,10 +415,10 @@ namespace IceInternal Type cl = typeof(InvocationHelper); add("parent", cl.GetMethod("getParent")); add("id", cl.GetMethod("getId")); - + add("operation", cl.GetMethod("getOperation")); add("identity", cl.GetMethod("getIdentity")); - + Type cli = typeof(Ice.ObjectPrx); add("facet", cl.GetMethod("getProxy"), cli.GetMethod("ice_getFacet")); add("encoding", cl.GetMethod("getEncodingVersion")); @@ -417,9 +430,9 @@ namespace IceInternal Debug.Assert(false); } } - }; + } static AttributeResolver _attributes = new AttributeResolverI(); - + public InvocationHelper(Ice.ObjectPrx proxy, string op, Dictionary<string, string> ctx) : base(_attributes) { _proxy = proxy; @@ -439,34 +452,34 @@ namespace IceInternal } throw new ArgumentOutOfRangeException(attribute); } - + public string getMode() { if(_proxy == null) { throw new ArgumentOutOfRangeException("mode"); } - + if(_proxy.ice_isTwoway()) { return "twoway"; - } + } else if(_proxy.ice_isOneway()) { return "oneway"; - } + } else if(_proxy.ice_isBatchOneway()) { return "batch-oneway"; - } + } else if(_proxy.ice_isDatagram()) { return "datagram"; - } + } else if(_proxy.ice_isBatchDatagram()) { return "batch-datagram"; - } + } else { throw new ArgumentOutOfRangeException("mode"); @@ -499,12 +512,12 @@ namespace IceInternal } return _id; } - + public string getParent() { return "Communicator"; } - + public Ice.ObjectPrx getProxy() { return _proxy; @@ -514,7 +527,7 @@ namespace IceInternal { return Ice.Util.encodingVersionToString(_proxy.ice_getEncodingVersion()); } - + public string getIdentity() { if(_proxy != null) @@ -526,24 +539,24 @@ namespace IceInternal return ""; } } - + public string getOperation() { return _operation; } - + readonly private Ice.ObjectPrx _proxy; readonly private string _operation; readonly private Dictionary<string, string> _context; private string _id; readonly static private Ice.Endpoint[] emptyEndpoints = new Ice.Endpoint[0]; - }; - + } + class ThreadHelper : MetricsHelper<ThreadMetrics> { - class AttributeResolverI : MetricsHelper<ThreadMetrics>.AttributeResolver - { + class AttributeResolverI : AttributeResolver + { public AttributeResolverI() { try @@ -557,7 +570,7 @@ namespace IceInternal Debug.Assert(false); } } - }; + } static AttributeResolver _attributes = new AttributeResolverI(); public ThreadHelper(string parent, string id, Ice.Instrumentation.ThreadState state) : base(_attributes) @@ -584,16 +597,16 @@ namespace IceInternal break; } } - + readonly public string _parent; readonly public string _id; readonly private Ice.Instrumentation.ThreadState _state; - }; + } class EndpointHelper : MetricsHelper<Metrics> { - class AttributeResolverI : MetricsHelper<Metrics>.AttributeResolver - { + class AttributeResolverI : AttributeResolver + { public AttributeResolverI() { try @@ -601,14 +614,14 @@ namespace IceInternal Type cl = typeof(EndpointHelper); add("parent", cl.GetMethod("getParent")); add("id", cl.GetMethod("getId")); - AttrsUtil.addEndpointAttributes<Metrics>(this, cl); + AttrsUtil.addEndpointAttributes(this, cl); } catch(Exception) { Debug.Assert(false); } } - }; + } static AttributeResolver _attributes = new AttributeResolverI(); public EndpointHelper(Ice.Endpoint endpt, string id) : base(_attributes) @@ -621,7 +634,7 @@ namespace IceInternal { _endpoint = endpt; } - + public Ice.EndpointInfo getEndpointInfo() { if(_endpointInfo == null) @@ -635,7 +648,7 @@ namespace IceInternal { return "Communicator"; } - + public string getId() { if(_id == null) @@ -644,21 +657,21 @@ namespace IceInternal } return _id; } - + public string getEndpoint() { return _endpoint.ToString(); } - + readonly private Ice.Endpoint _endpoint; private string _id; private Ice.EndpointInfo _endpointInfo; - }; - + } + public class RemoteInvocationHelper : MetricsHelper<RemoteMetrics> { - class AttributeResolverI : MetricsHelper<RemoteMetrics>.AttributeResolver - { + class AttributeResolverI : AttributeResolver + { public AttributeResolverI() { try @@ -667,14 +680,14 @@ namespace IceInternal add("parent", cl.GetMethod("getParent")); add("id", cl.GetMethod("getId")); add("requestId", cl.GetMethod("getRequestId")); - AttrsUtil.addConnectionAttributes<RemoteMetrics>(this, cl); + AttrsUtil.addConnectionAttributes(this, cl); } catch(Exception) { Debug.Assert(false); } } - }; + } static AttributeResolver _attributes = new AttributeResolverI(); public RemoteInvocationHelper(Ice.ConnectionInfo con, Ice.Endpoint endpt, int requestId, int size) : @@ -708,7 +721,7 @@ namespace IceInternal { return _requestId; } - + public string getParent() { if(_connectionInfo.adapterName != null && _connectionInfo.adapterName.Length > 0) @@ -720,12 +733,12 @@ namespace IceInternal return "Communicator"; } } - + public Ice.ConnectionInfo getConnectionInfo() { return _connectionInfo; } - + public Ice.Endpoint getEndpoint() { return _endpoint; @@ -746,12 +759,12 @@ namespace IceInternal readonly private int _requestId; private string _id; private Ice.EndpointInfo _endpointInfo; - }; + } public class CollocatedInvocationHelper : MetricsHelper<CollocatedMetrics> { - class AttributeResolverI : MetricsHelper<CollocatedMetrics>.AttributeResolver - { + class AttributeResolverI : AttributeResolver + { public AttributeResolverI() { try @@ -766,7 +779,7 @@ namespace IceInternal Debug.Assert(false); } } - }; + } static AttributeResolver _attributes = new AttributeResolverI(); public CollocatedInvocationHelper(Ice.ObjectAdapter adapter, int requestId, int size) : @@ -791,20 +804,20 @@ namespace IceInternal { return _requestId; } - + public string getParent() { return "Communicator"; } - + readonly private int _size; readonly private int _requestId; readonly private string _id; - }; + } public class ObserverWithDelegateI : ObserverWithDelegate<Metrics, Ice.Instrumentation.Observer> { - }; + } public class ConnectionObserverI : ObserverWithDelegate<ConnectionMetrics, Ice.Instrumentation.ConnectionObserver>, Ice.Instrumentation.ConnectionObserver @@ -841,7 +854,7 @@ namespace IceInternal private int _sentBytes; private int _receivedBytes; - }; + } public class DispatchObserverI : ObserverWithDelegate<DispatchMetrics, Ice.Instrumentation.DispatchObserver>, Ice.Instrumentation.DispatchObserver @@ -925,8 +938,8 @@ namespace IceInternal delegate_.retried(); } } - - public Ice.Instrumentation.RemoteObserver getRemoteObserver(Ice.ConnectionInfo con, Ice.Endpoint endpt, + + public Ice.Instrumentation.RemoteObserver getRemoteObserver(Ice.ConnectionInfo con, Ice.Endpoint endpt, int requestId, int size) { Ice.Instrumentation.RemoteObserver del = null; @@ -934,14 +947,14 @@ namespace IceInternal { del = delegate_.getRemoteObserver(con, endpt, requestId, size); } - return getObserver<RemoteMetrics, RemoteObserverI, - Ice.Instrumentation.RemoteObserver>("Remote", + return getObserver<RemoteMetrics, RemoteObserverI, + Ice.Instrumentation.RemoteObserver>("Remote", new RemoteInvocationHelper(con, endpt, requestId, size), del); } - public Ice.Instrumentation.CollocatedObserver getCollocatedObserver(Ice.ObjectAdapter adapter, - int requestId, + public Ice.Instrumentation.CollocatedObserver getCollocatedObserver(Ice.ObjectAdapter adapter, + int requestId, int size) { Ice.Instrumentation.CollocatedObserver del = null; @@ -950,7 +963,7 @@ namespace IceInternal del = delegate_.getCollocatedObserver(adapter, requestId, size); } return getObserver<CollocatedMetrics, CollocatedObserverI, - Ice.Instrumentation.CollocatedObserver>("Collocated", + Ice.Instrumentation.CollocatedObserver>("Collocated", new CollocatedInvocationHelper(adapter, requestId, size), del); } @@ -1014,7 +1027,7 @@ namespace IceInternal private Ice.Instrumentation.ThreadState _oldState; private Ice.Instrumentation.ThreadState _newState; - }; + } public class CommunicatorObserverI : Ice.Instrumentation.CommunicatorObserver { @@ -1088,8 +1101,8 @@ namespace IceInternal } return null; } - - public Ice.Instrumentation.ConnectionObserver getConnectionObserver(Ice.ConnectionInfo c, + + public Ice.Instrumentation.ConnectionObserver getConnectionObserver(Ice.ConnectionInfo c, Ice.Endpoint e, Ice.Instrumentation.ConnectionState s, Ice.Instrumentation.ConnectionObserver obsv) @@ -1113,9 +1126,9 @@ namespace IceInternal } return null; } - - public Ice.Instrumentation.ThreadObserver getThreadObserver(string parent, string id, - Ice.Instrumentation.ThreadState s, + + public Ice.Instrumentation.ThreadObserver getThreadObserver(string parent, string id, + Ice.Instrumentation.ThreadState s, Ice.Instrumentation.ThreadObserver obsv) { if(_threads.isEnabled()) @@ -1137,8 +1150,8 @@ namespace IceInternal } return null; } - - public Ice.Instrumentation.InvocationObserver getInvocationObserver(Ice.ObjectPrx prx, string operation, + + public Ice.Instrumentation.InvocationObserver getInvocationObserver(Ice.ObjectPrx prx, string operation, Dictionary<string, string> ctx) { if(_invocations.isEnabled()) @@ -1159,7 +1172,7 @@ namespace IceInternal } return null; } - + public Ice.Instrumentation.DispatchObserver getDispatchObserver(Ice.Current c, int size) { if(_dispatch.isEnabled()) @@ -1180,7 +1193,7 @@ namespace IceInternal } return null; } - + public void setObserverUpdater(Ice.Instrumentation.ObserverUpdater updater) { if(updater == null) @@ -1199,12 +1212,12 @@ namespace IceInternal } } - public IceInternal.MetricsAdminI getFacet() + public MetricsAdminI getFacet() { return _metrics; } - readonly private IceInternal.MetricsAdminI _metrics; + readonly private MetricsAdminI _metrics; readonly private Ice.Instrumentation.CommunicatorObserver _delegate; readonly private ObserverFactoryWithDelegate<ConnectionMetrics, ConnectionObserverI, Ice.Instrumentation.ConnectionObserver> _connections; diff --git a/csharp/src/Ice/LocatorInfo.cs b/csharp/src/Ice/LocatorInfo.cs index 2ab8dab5d27..fb4df8944f8 100644 --- a/csharp/src/Ice/LocatorInfo.cs +++ b/csharp/src/Ice/LocatorInfo.cs @@ -30,7 +30,7 @@ namespace IceInternal EndpointI[] endpoints = null; if(proxy != null) { - Reference r = ((Ice.ObjectPrxHelperBase)proxy).reference__(); + Reference r = ((Ice.ObjectPrxHelperBase)proxy).iceReference(); if(_ref.isWellKnown() && !Protocol.isSupported(_ref.getEncoding(), r.getEncoding())) { // @@ -130,64 +130,6 @@ namespace IceInternal } } - public EndpointI[] - getEndpoints(Reference @ref, Reference wellKnownRef, int ttl, out bool cached) - { - lock(this) - { - if(!_response || _exception == null) - { - if(wellKnownRef != null) - { - // This request is to resolve the endpoints of a cached well-known object ref - _wellKnownRefs.Add(wellKnownRef); - } - if(!_sent) - { - _sent = true; - send(); - } - - while(!_response && _exception == null) - { - System.Threading.Monitor.Wait(this); - } - } - - if(_exception != null) - { - _locatorInfo.getEndpointsException(@ref, _exception); // This throws. - } - - Debug.Assert(_response); - EndpointI[] endpoints = null; - if(_proxy != null) - { - Reference r = ((Ice.ObjectPrxHelperBase)_proxy).reference__(); - if(!r.isIndirect()) - { - endpoints = r.getEndpoints(); - } - else if(@ref.isWellKnown() && !r.isWellKnown()) - { - // - // We're resolving the endpoints of a well-known object and the proxy returned - // by the locator is an indirect proxy. We now need to resolve the endpoints - // of this indirect proxy. - // - return _locatorInfo.getEndpoints(r, @ref, ttl, out cached); - } - } - - cached = false; - if(_ref.getInstance().traceLevels().location >= 1) - { - _locatorInfo.getEndpointsTrace(@ref, endpoints, false); - } - return endpoints == null ? new EndpointI[0] : endpoints; - } - } - public Request(LocatorInfo locatorInfo, Reference @ref) { _locatorInfo = locatorInfo; @@ -204,7 +146,7 @@ namespace IceInternal _locatorInfo.finishRequest(_ref, _wellKnownRefs, proxy, false); _response = true; _proxy = proxy; - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); } foreach(RequestCallback callback in _callbacks) { @@ -219,7 +161,7 @@ namespace IceInternal { _locatorInfo.finishRequest(_ref, _wellKnownRefs, null, ex is Ice.UserException); _exception = ex; - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); } foreach(RequestCallback callback in _callbacks) { @@ -273,7 +215,7 @@ namespace IceInternal try { _locatorInfo.getLocator().begin_findAdapterById(_ref.getAdapterId()).whenCompleted( - this.response, this.exception); + response, exception); } catch(Ice.Exception ex) { @@ -300,7 +242,7 @@ namespace IceInternal public override bool Equals(object obj) { - if(object.ReferenceEquals(this, obj)) + if(ReferenceEquals(this, obj)) { return true; } @@ -354,67 +296,6 @@ namespace IceInternal } } - public EndpointI[] - getEndpoints(Reference @ref, int ttl, out bool cached) - { - return getEndpoints(@ref, null, ttl, out cached); - } - - public EndpointI[] - getEndpoints(Reference @ref, Reference wellKnownRef, int ttl, out bool cached) - { - Debug.Assert(@ref.isIndirect()); - EndpointI[] endpoints = null; - cached = false; - if(!@ref.isWellKnown()) - { - endpoints = _table.getAdapterEndpoints(@ref.getAdapterId(), ttl, out cached); - if(!cached) - { - if(_background && endpoints != null) - { - getAdapterRequest(@ref).addCallback(@ref, wellKnownRef, ttl, null); - } - else - { - return getAdapterRequest(@ref).getEndpoints(@ref, wellKnownRef, ttl, out cached); - } - } - } - else - { - Reference r = _table.getObjectReference(@ref.getIdentity(), ttl, out cached); - if(!cached) - { - if(_background && r != null) - { - getObjectRequest(@ref).addCallback(@ref, null, ttl, null); - } - else - { - return getObjectRequest(@ref).getEndpoints(@ref, null, ttl, out cached); - } - } - - if(!r.isIndirect()) - { - endpoints = r.getEndpoints(); - } - else if(!r.isWellKnown()) - { - return getEndpoints(r, @ref, ttl, out cached); - } - } - - Debug.Assert(endpoints != null); - cached = true; - if(@ref.getInstance().traceLevels().location >= 1) - { - getEndpointsTrace(@ref, endpoints, true); - } - return endpoints; - } - public void getEndpoints(Reference @ref, int ttl, GetEndpointsCallback callback) { @@ -523,7 +404,8 @@ namespace IceInternal } else { - s.Append("object = " + r.getInstance().identityToString(r.getIdentity()) + "\n"); + s.Append("object = " + Ice.Util.identityToString(r.getIdentity(), r.getInstance().toStringMode()) + + "\n"); } s.Append("endpoints = "); @@ -569,13 +451,13 @@ namespace IceInternal { System.Text.StringBuilder s = new System.Text.StringBuilder(); s.Append("object not found\n"); - s.Append("object = " + instance.identityToString(@ref.getIdentity())); + s.Append("object = " + Ice.Util.identityToString(@ref.getIdentity(), instance.toStringMode())); instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.ToString()); } Ice.NotRegisteredException e = new Ice.NotRegisteredException(ex); e.kindOfObject = "object"; - e.id = instance.identityToString(@ref.getIdentity()); + e.id = Ice.Util.identityToString(@ref.getIdentity(), instance.toStringMode()); throw e; } catch(Ice.NotRegisteredException) @@ -595,7 +477,7 @@ namespace IceInternal } else { - s.Append("object = " + instance.identityToString(@ref.getIdentity()) + "\n"); + s.Append("object = " + Ice.Util.identityToString(@ref.getIdentity(), instance.toStringMode()) + "\n"); } s.Append("reason = " + ex); instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.ToString()); @@ -634,7 +516,7 @@ namespace IceInternal else { s.Append("object\n"); - s.Append("object = " + instance.identityToString(@ref.getIdentity())); + s.Append("object = " + Ice.Util.identityToString(@ref.getIdentity(), instance.toStringMode())); } instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.ToString()); } @@ -674,7 +556,7 @@ namespace IceInternal Instance instance = @ref.getInstance(); System.Text.StringBuilder s = new System.Text.StringBuilder(); s.Append("searching for object by id\nobject = "); - s.Append(instance.identityToString(@ref.getIdentity())); + s.Append(Ice.Util.identityToString(@ref.getIdentity(), instance.toStringMode())); instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.ToString()); } @@ -696,7 +578,7 @@ namespace IceInternal finishRequest(Reference @ref, List<Reference> wellKnownRefs, Ice.ObjectPrx proxy, bool notRegistered) { Ice.ObjectPrxHelperBase @base = proxy as Ice.ObjectPrxHelperBase; - if(proxy == null || @base.reference__().isIndirect()) + if(proxy == null || @base.iceReference().isIndirect()) { // // Remove the cached references of well-known objects for which we tried @@ -710,10 +592,10 @@ namespace IceInternal if(!@ref.isWellKnown()) { - if(proxy != null && !@base.reference__().isIndirect()) + if(proxy != null && !@base.iceReference().isIndirect()) { // Cache the adapter endpoints. - _table.addAdapterEndpoints(@ref.getAdapterId(), @base.reference__().getEndpoints()); + _table.addAdapterEndpoints(@ref.getAdapterId(), @base.iceReference().getEndpoints()); } else if(notRegistered) // If the adapter isn't registered anymore, remove it from the cache. { @@ -728,10 +610,10 @@ namespace IceInternal } else { - if(proxy != null && !@base.reference__().isWellKnown()) + if(proxy != null && !@base.iceReference().isWellKnown()) { // Cache the well-known object reference. - _table.addObjectReference(@ref.getIdentity(), @base.reference__()); + _table.addObjectReference(@ref.getIdentity(), @base.iceReference()); } else if(notRegistered) // If the well-known object isn't registered anymore, remove it from the cache. { @@ -761,7 +643,7 @@ namespace IceInternal { public LocatorKey(Ice.LocatorPrx prx) { - Reference r = ((Ice.ObjectPrxHelperBase)prx).reference__(); + Reference r = ((Ice.ObjectPrxHelperBase)prx).iceReference(); _id = r.getIdentity(); _encoding = r.getEncoding(); } @@ -783,14 +665,14 @@ namespace IceInternal public override int GetHashCode() { int h = 5381; - IceInternal.HashUtil.hashAdd(ref h, _id); - IceInternal.HashUtil.hashAdd(ref h, _encoding); + HashUtil.hashAdd(ref h, _id); + HashUtil.hashAdd(ref h, _encoding); return h; } private Ice.Identity _id; private Ice.EncodingVersion _encoding; - }; + } internal LocatorManager(Ice.Properties properties) { @@ -831,7 +713,6 @@ namespace IceInternal // // TODO: reap unused locator info objects? // - lock(this) { LocatorInfo info = null; @@ -880,7 +761,7 @@ namespace IceInternal } } - internal IceInternal.EndpointI[] getAdapterEndpoints(string adapter, int ttl, out bool cached) + internal EndpointI[] getAdapterEndpoints(string adapter, int ttl, out bool cached) { if(ttl == 0) // Locator cache disabled. { @@ -902,7 +783,7 @@ namespace IceInternal } } - internal void addAdapterEndpoints(string adapter, IceInternal.EndpointI[] endpoints) + internal void addAdapterEndpoints(string adapter, EndpointI[] endpoints) { lock(this) { @@ -911,7 +792,7 @@ namespace IceInternal } } - internal IceInternal.EndpointI[] removeAdapterEndpoints(string adapter) + internal EndpointI[] removeAdapterEndpoints(string adapter) { lock(this) { @@ -983,14 +864,14 @@ namespace IceInternal sealed private class EndpointTableEntry { - public EndpointTableEntry(long time, IceInternal.EndpointI[] endpoints) + public EndpointTableEntry(long time, EndpointI[] endpoints) { this.time = time; this.endpoints = endpoints; } public long time; - public IceInternal.EndpointI[] endpoints; + public EndpointI[] endpoints; } sealed private class ReferenceTableEntry diff --git a/csharp/src/Ice/LoggerAdminI.cs b/csharp/src/Ice/LoggerAdminI.cs index a4743164647..04163f4fba8 100644 --- a/csharp/src/Ice/LoggerAdminI.cs +++ b/csharp/src/Ice/LoggerAdminI.cs @@ -10,7 +10,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Threading; namespace IceInternal { @@ -81,12 +80,29 @@ sealed class LoggerAdminI : Ice.LoggerAdminDisp_ try { - remoteLogger.begin_init(_logger.getPrefix(), initLogMessages.ToArray(), initCompleted, null); + remoteLogger.initAsync(_logger.getPrefix(), initLogMessages.ToArray()).ContinueWith( + (t) => + { + try + { + t.Wait(); + if(_traceLevel > 1) + { + _logger.trace(_traceCategory,"init on `" + remoteLogger.ToString() + + "' completed successfully"); + } + } + catch(System.AggregateException ae) + { + Debug.Assert(ae.InnerException is Ice.LocalException); + deadRemoteLogger(remoteLogger, _logger, (Ice.LocalException)ae.InnerException, "init"); + } + }); } catch(Ice.LocalException ex) { deadRemoteLogger(remoteLogger, _logger, ex, "init"); - throw ex; + throw; } } @@ -305,26 +321,6 @@ sealed class LoggerAdminI : Ice.LoggerAdminDisp_ return _remoteLoggerMap.Remove(remoteLogger.ice_getIdentity()); } } - - private void initCompleted(Ice.AsyncResult r) - { - Ice.RemoteLoggerPrx remoteLogger = Ice.RemoteLoggerPrxHelper.uncheckedCast(r.getProxy()); - - try - { - remoteLogger.end_init(r); - - if(_traceLevel > 1) - { - _logger.trace(_traceCategory, r.getOperation() + " on `" + remoteLogger.ToString() - + "' completed successfully"); - } - } - catch(Ice.LocalException ex) - { - deadRemoteLogger(remoteLogger, _logger, ex, r.getOperation()); - } - } private static void filterLogMessages(LinkedList<Ice.LogMessage> logMessages, HashSet<Ice.LogMessageType> messageTypes, diff --git a/csharp/src/Ice/LoggerAdminLoggerI.cs b/csharp/src/Ice/LoggerAdminLoggerI.cs index 6973366307b..9089ec151fb 100644 --- a/csharp/src/Ice/LoggerAdminLoggerI.cs +++ b/csharp/src/Ice/LoggerAdminLoggerI.cs @@ -60,7 +60,7 @@ sealed class LoggerAdminLoggerI : LoggerAdminLogger { return _localLogger.cloneWithPrefix(prefix); } - + public Ice.Object getFacet() { return _loggerAdmin; @@ -79,10 +79,10 @@ sealed class LoggerAdminLoggerI : LoggerAdminLogger Monitor.PulseAll(this); } } - + if(thread != null) { - thread.Join(); + thread.Join(); } _loggerAdmin.destroy(); @@ -91,7 +91,7 @@ sealed class LoggerAdminLoggerI : LoggerAdminLogger internal LoggerAdminLoggerI(Ice.Properties props, Ice.Logger localLogger) { LoggerAdminLoggerI wrapper = localLogger as LoggerAdminLoggerI; - + if(wrapper != null) { _localLogger = wrapper.getLocalLogger(); @@ -112,11 +112,11 @@ sealed class LoggerAdminLoggerI : LoggerAdminLogger internal void log(Ice.LogMessage logMessage) { List<Ice.RemoteLoggerPrx> remoteLoggers = _loggerAdmin.log(logMessage); - + if(remoteLoggers != null) { Debug.Assert(remoteLoggers.Count > 0); - + lock(this) { if(_sendLogThread == null) @@ -126,13 +126,13 @@ sealed class LoggerAdminLoggerI : LoggerAdminLogger _sendLogThread.IsBackground = true; _sendLogThread.Start(); } - + _jobQueue.Enqueue(new Job(remoteLoggers, logMessage)); Monitor.PulseAll(this); - } + } } } - + private void run() { if(_loggerAdmin.getTraceLevel() > 1) @@ -149,7 +149,7 @@ sealed class LoggerAdminLoggerI : LoggerAdminLogger { Monitor.Wait(this); } - + if(_destroyed) { break; // for(;;) @@ -158,26 +158,50 @@ sealed class LoggerAdminLoggerI : LoggerAdminLogger Debug.Assert(_jobQueue.Count > 0); job = _jobQueue.Dequeue(); } - + foreach(var p in job.remoteLoggers) { if(_loggerAdmin.getTraceLevel() > 1) { _localLogger.trace(_traceCategory, "sending log message to `" + p.ToString() + "'"); } - + try { // // p is a proxy associated with the _sendLogCommunicator // - p.begin_log(job.logMessage, logCompleted, null); + p.logAsync(job.logMessage).ContinueWith( + (t) => + { + try + { + t.Wait(); + if(_loggerAdmin.getTraceLevel() > 1) + { + _localLogger.trace(_traceCategory, "log on `" + p.ToString() + + "' completed successfully"); + } + } + catch(AggregateException ae) + { + if(ae.InnerException is Ice.CommunicatorDestroyedException) + { + // expected if there are outstanding calls during communicator destruction + } + if(ae.InnerException is Ice.LocalException) + { + _loggerAdmin.deadRemoteLogger(p, _localLogger, + (Ice.LocalException)ae.InnerException, "log"); + } + } + }); } catch(Ice.LocalException ex) { _loggerAdmin.deadRemoteLogger(p, _localLogger, ex, "log"); } - } + } } if(_loggerAdmin.getTraceLevel() > 1) @@ -186,30 +210,6 @@ sealed class LoggerAdminLoggerI : LoggerAdminLogger } } - private void logCompleted(Ice.AsyncResult r) - { - Ice.RemoteLoggerPrx remoteLogger = Ice.RemoteLoggerPrxHelper.uncheckedCast(r.getProxy()); - - try - { - remoteLogger.end_log(r); - - if(_loggerAdmin.getTraceLevel() > 1) - { - _localLogger.trace(_traceCategory, r.getOperation() + " on `" + remoteLogger.ToString() - + "' completed successfully"); - } - } - catch(Ice.CommunicatorDestroyedException) - { - // expected if there are outstanding calls during communicator destruction - } - catch(Ice.LocalException ex) - { - _loggerAdmin.deadRemoteLogger(remoteLogger, _localLogger, ex, r.getOperation()); - } - } - static private long now() { TimeSpan t = DateTime.UtcNow - _unixEpoch; @@ -223,17 +223,17 @@ sealed class LoggerAdminLoggerI : LoggerAdminLogger remoteLoggers = r; logMessage = l; } - + internal readonly List<Ice.RemoteLoggerPrx> remoteLoggers; internal readonly Ice.LogMessage logMessage; - } + } private readonly Ice.Logger _localLogger; private readonly LoggerAdminI _loggerAdmin; private bool _destroyed = false; private Thread _sendLogThread; private readonly Queue<Job> _jobQueue = new Queue<Job>(); - + static private readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); static private readonly string _traceCategory = "Admin.Logger"; } diff --git a/csharp/src/Ice/LoggerI.cs b/csharp/src/Ice/LoggerI.cs index 2f2b71862dd..2de076dff35 100644 --- a/csharp/src/Ice/LoggerI.cs +++ b/csharp/src/Ice/LoggerI.cs @@ -7,15 +7,11 @@ // // ********************************************************************** -#define TRACE - namespace Ice { using System.Diagnostics; using System.Globalization; -#if !SILVERLIGHT && !UNITY using System.IO; -#endif public abstract class LoggerI : Logger { @@ -120,7 +116,6 @@ namespace Ice } } -#if !SILVERLIGHT && !UNITY public sealed class FileLoggerI : LoggerI { public FileLoggerI(string prefix, string file) : @@ -145,8 +140,6 @@ namespace Ice private TextWriter _writer; } - -# if !COMPACT public class ConsoleListener : TraceListener { public ConsoleListener() @@ -177,7 +170,7 @@ namespace Ice s.Append(System.DateTime.Now.ToString(_time, CultureInfo.CurrentCulture)); s.Append(' '); s.Append(message); - this.WriteLine(s.ToString()); + WriteLine(s.ToString()); } public override void Write(string message) @@ -259,6 +252,4 @@ namespace Ice private bool _console; internal static ConsoleListener _consoleListener = new ConsoleListener(); } -# endif -#endif } diff --git a/csharp/src/Ice/LoggerPlugin.cs b/csharp/src/Ice/LoggerPlugin.cs index b6933ce7788..33aa8cba658 100644 --- a/csharp/src/Ice/LoggerPlugin.cs +++ b/csharp/src/Ice/LoggerPlugin.cs @@ -14,7 +14,7 @@ namespace Ice /// instantiate a LoggerPlugin with a custom logger and /// return the instance from their PluginFactory implementation. /// </summary> - public class LoggerPlugin : Ice.Plugin + public class LoggerPlugin : Plugin { /// <summary> /// Installs a custom logger for a communicator. diff --git a/csharp/src/Ice/Makefile b/csharp/src/Ice/Makefile deleted file mode 100644 index 9cbf5697d57..00000000000 --- a/csharp/src/Ice/Makefile +++ /dev/null @@ -1,201 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -PKG = Ice -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)/$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = Acceptor.cs \ - ACM.cs \ - AMDCallback.cs \ - Application.cs \ - Arrays.cs \ - AssemblyInfo.cs \ - AssemblyUtil.cs \ - AsyncIOThread.cs \ - AsyncResult.cs \ - Base64.cs \ - BasicStream.cs \ - BatchRequestInterceptor.cs \ - BatchRequestQueue.cs \ - Buffer.cs \ - ByteBuffer.cs \ - CollectionBase.cs \ - Collections.cs \ - CollocatedRequestHandler.cs \ - CommunicatorI.cs \ - Compare.cs \ - ConnectionFactory.cs \ - ConnectionI.cs \ - ConnectionRequestHandler.cs \ - Connector.cs \ - ConnectRequestHandler.cs \ - DefaultsAndOverrides.cs \ - DictionaryBase.cs \ - DispatchInterceptor.cs \ - EndpointFactory.cs \ - EndpointFactoryManager.cs \ - EndpointHostResolver.cs \ - EndpointI.cs \ - EventHandler.cs \ - Exception.cs \ - FormatType.cs \ - HttpParser.cs \ - ImplicitContextI.cs \ - Incoming.cs \ - IncomingAsync.cs \ - Instance.cs \ - InstrumentationI.cs \ - IPEndpointI.cs \ - LocatorInfo.cs \ - LoggerAdminI.cs \ - LoggerAdminLoggerI.cs \ - LoggerI.cs \ - LoggerPlugin.cs \ - MetricsAdminI.cs \ - MetricsObserverI.cs \ - Network.cs \ - NetworkProxy.cs \ - Object.cs \ - ObjectAdapterFactory.cs \ - ObjectAdapterI.cs \ - ObjectFactoryManager.cs \ - ObserverHelper.cs \ - OpaqueEndpointI.cs \ - Optional.cs \ - Options.cs \ - OutgoingAsync.cs \ - OutputBase.cs \ - Patcher.cs \ - PluginManagerI.cs \ - ProcessI.cs \ - PropertiesAdminI.cs \ - PropertiesI.cs \ - Property.cs \ - PropertyNames.cs \ - Protocol.cs \ - ProtocolInstance.cs \ - ProtocolPluginFacade.cs \ - Proxy.cs \ - ProxyFactory.cs \ - ProxyIdentityKey.cs \ - Reference.cs \ - ReferenceFactory.cs \ - ReplyStatus.cs \ - RequestHandler.cs \ - RequestHandlerFactory.cs \ - ResponseHandler.cs \ - RetryQueue.cs \ - RouterInfo.cs \ - ServantManager.cs \ - SliceChecksums.cs \ - SlicedData.cs \ - SocketOperation.cs \ - Stream.cs \ - StreamI.cs \ - StreamSocket.cs \ - StreamWrapper.cs \ - StringUtil.cs \ - SysLoggerI.cs \ - TcpAcceptor.cs \ - TcpConnector.cs \ - TcpEndpointI.cs \ - TcpTransceiver.cs \ - ThreadHookPlugin.cs \ - ThreadPool.cs \ - TieBase.cs \ - Time.cs \ - Timer.cs \ - TraceLevels.cs \ - TraceUtil.cs \ - Transceiver.cs \ - UdpConnector.cs \ - UdpEndpointI.cs \ - UdpTransceiver.cs \ - UnknownSlicedObject.cs \ - UserExceptionFactory.cs \ - Util.cs \ - ValueWriter.cs \ - WSAcceptor.cs \ - WSConnector.cs \ - WSEndpoint.cs \ - WSTransceiver.cs - -SLICE_SRCS = $(SDIR)/BuiltinSequences.ice \ - $(SDIR)/Communicator.ice \ - $(SDIR)/Connection.ice \ - $(SDIR)/Current.ice \ - $(SDIR)/Endpoint.ice \ - $(SDIR)/EndpointTypes.ice \ - $(SDIR)/FacetMap.ice \ - $(SDIR)/Identity.ice \ - $(SDIR)/ImplicitContext.ice \ - $(SDIR)/Instrumentation.ice \ - $(SDIR)/LocalException.ice \ - $(SDIR)/Locator.ice \ - $(SDIR)/Logger.ice \ - $(SDIR)/Metrics.ice \ - $(SDIR)/ObjectAdapter.ice \ - $(SDIR)/ObjectFactory.ice \ - $(SDIR)/Plugin.ice \ - $(SDIR)/Process.ice \ - $(SDIR)/Properties.ice \ - $(SDIR)/PropertiesAdmin.ice \ - $(SDIR)/RemoteLogger.ice \ - $(SDIR)/Router.ice \ - $(SDIR)/ServantLocator.ice \ - $(SDIR)/SliceChecksumDict.ice \ - $(SDIR)/Version.ice \ - -SDIR = $(slicedir)/Ice -GDIR = generated - -include $(top_srcdir)/config/Make.rules.cs - -MCSFLAGS := $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS := $(MCSFLAGS) -keyfile:$(KEYFILE) -MCSFLAGS := $(MCSFLAGS) /doc:$(assembliesdir)/$(PKG).xml /nowarn:1591 - -ifneq ($(MANAGED),yes) - MCSFLAGS := $(MCSFLAGS) -unsafe+ -endif - -SLICE2CSFLAGS := $(SLICE2CSFLAGS) --ice -I$(slicedir) - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) $(subst /,$(DSEP),$^) - $(INSTALL) $(LIBNAME).config $(assembliesdir) - -clean:: - -rm -f $(assembliesdir)/$(LIBNAME).config - -ifeq ($(GACINSTALL),yes) -install:: all - $(call installdata,../../lib/pkgconfig/$(PKG).pc,$(DESTDIR)$(install_pkgconfigdir)) -else -install:: all - $(call installdata,$(TARGETS).config,$(DESTDIR)$(install_assembliesdir)) -endif - -install:: all - (cd $(assembliesdir); $(call installassembly,$(LIBNAME),$(PKG)); $(call installpolicy,$(POLICY)); \ - $(call installmdb,$(LIBNAME).mdb); \ - $(call installdata,$(PKG).xml,$(DESTDIR)$(install_assembliesdir))) - -clean:: - echo $(GEN_SRCS) - -rm -f $(assembliesdir)/$(PKG).xml - -$(GDIR)/BuiltinSequences.cs: $(SDIR)/BuiltinSequences.ice $(SLICE2CPP) $(SLICEPARSERLIB) - rm -f $(GDIR)/BuiltinSequences.cs - $(SLICE2CS) $(SLICE2CSFLAGS) --stream $(SDIR)/BuiltinSequences.ice - mv BuiltinSequences.cs $(GDIR) diff --git a/csharp/src/Ice/Makefile.mak b/csharp/src/Ice/Makefile.mak deleted file mode 100644 index 8873b76fc78..00000000000 --- a/csharp/src/Ice/Makefile.mak +++ /dev/null @@ -1,201 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -PKG = Ice -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)\$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = Acceptor.cs \ - ACM.cs \ - AMDCallback.cs \ - Application.cs \ - Arrays.cs \ - AssemblyInfo.cs \ - AssemblyUtil.cs \ - AsyncIOThread.cs \ - AsyncResult.cs \ - Base64.cs \ - BasicStream.cs \ - BatchRequestInterceptor.cs \ - BatchRequestQueue.cs \ - Buffer.cs \ - ByteBuffer.cs \ - CollectionBase.cs \ - Collections.cs \ - CollocatedRequestHandler.cs \ - CommunicatorI.cs \ - Compare.cs \ - ConnectionFactory.cs \ - ConnectionI.cs \ - ConnectionRequestHandler.cs \ - Connector.cs \ - ConnectRequestHandler.cs \ - DefaultsAndOverrides.cs \ - DictionaryBase.cs \ - DispatchInterceptor.cs \ - EndpointFactory.cs \ - EndpointFactoryManager.cs \ - EndpointHostResolver.cs \ - EndpointI.cs \ - EventHandler.cs \ - Exception.cs \ - FormatType.cs \ - HashSet.cs \ - HttpParser.cs \ - ImplicitContextI.cs \ - Incoming.cs \ - IncomingAsync.cs \ - Instance.cs \ - InstrumentationI.cs \ - IPEndpointI.cs \ - LocatorInfo.cs \ - LoggerAdminI.cs \ - LoggerAdminLoggerI.cs \ - LoggerI.cs \ - LoggerPlugin.cs \ - MetricsAdminI.cs \ - MetricsObserverI.cs \ - Network.cs \ - NetworkProxy.cs \ - Object.cs \ - ObjectAdapterFactory.cs \ - ObjectAdapterI.cs \ - ObjectFactoryManager.cs \ - ObserverHelper.cs \ - OpaqueEndpointI.cs \ - Optional.cs \ - Options.cs \ - OutgoingAsync.cs \ - OutputBase.cs \ - Patcher.cs \ - PluginManagerI.cs \ - ProcessI.cs \ - PropertiesAdminI.cs \ - PropertiesI.cs \ - Property.cs \ - PropertyNames.cs \ - Protocol.cs \ - ProtocolInstance.cs \ - ProtocolPluginFacade.cs \ - Proxy.cs \ - ProxyFactory.cs \ - ProxyIdentityKey.cs \ - Reference.cs \ - ReferenceFactory.cs \ - ReplyStatus.cs \ - RequestHandler.cs \ - RequestHandlerFactory.cs \ - ResponseHandler.cs \ - RetryQueue.cs \ - RouterInfo.cs \ - ServantManager.cs \ - SliceChecksums.cs \ - SlicedData.cs \ - SocketOperation.cs \ - Stream.cs \ - StreamI.cs \ - StreamSocket.cs \ - StreamWrapper.cs \ - StringUtil.cs \ - SysLoggerI.cs \ - TcpAcceptor.cs \ - TcpConnector.cs \ - TcpEndpointI.cs \ - TcpTransceiver.cs \ - ThreadHookPlugin.cs \ - ThreadPool.cs \ - TieBase.cs \ - Time.cs \ - Timer.cs \ - TraceLevels.cs \ - TraceUtil.cs \ - Transceiver.cs \ - UdpConnector.cs \ - UdpEndpointI.cs \ - UdpTransceiver.cs \ - UnknownSlicedObject.cs \ - UserExceptionFactory.cs \ - Util.cs \ - ValueWriter.cs \ - WSAcceptor.cs \ - WSConnector.cs \ - WSEndpoint.cs \ - WSTransceiver.cs - -GEN_SRCS = $(GDIR)\BuiltinSequences.cs \ - $(GDIR)\Communicator.cs \ - $(GDIR)\Connection.cs \ - $(GDIR)\Current.cs \ - $(GDIR)\Endpoint.cs \ - $(GDIR)\EndpointTypes.cs \ - $(GDIR)\FacetMap.cs \ - $(GDIR)\Identity.cs \ - $(GDIR)\ImplicitContext.cs \ - $(GDIR)\Instrumentation.cs \ - $(GDIR)\LocalException.cs \ - $(GDIR)\Locator.cs \ - $(GDIR)\Logger.cs \ - $(GDIR)\Metrics.cs \ - $(GDIR)\ObjectAdapter.cs \ - $(GDIR)\ObjectFactory.cs \ - $(GDIR)\Plugin.cs \ - $(GDIR)\Process.cs \ - $(GDIR)\Properties.cs \ - $(GDIR)\PropertiesAdmin.cs \ - $(GDIR)\RemoteLogger.cs \ - $(GDIR)\Router.cs \ - $(GDIR)\ServantLocator.cs \ - $(GDIR)\SliceChecksumDict.cs \ - $(GDIR)\Version.cs - -SDIR = $(slicedir)\Ice -GDIR = generated - -!include $(top_srcdir)\config\Make.rules.mak.cs - -MCSFLAGS = $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS = $(MCSFLAGS) -keyfile:"$(KEYFILE)" -MCSFLAGS = $(MCSFLAGS) /doc:$(assembliesdir)\$(PKG).xml /nowarn:1591 - -!if "$(MANAGED)" != "yes" -MCSFLAGS = $(MCSFLAGS) /unsafe -!endif - -SLICE2CSFLAGS = $(SLICE2CSFLAGS) --ice -I"$(slicedir)" - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) /baseaddress:0x20000000 $(MCSFLAGS) $(SRCS) $(GEN_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -!if "$(DEBUG)" == "yes" -clean:: - del /q $(assembliesdir)\$(PKG).pdb -!endif - -clean:: - del /q $(assembliesdir)\$(PKG).xml - -install:: all - copy $(assembliesdir)\$(LIBNAME) "$(install_assembliesdir)" - copy $(assembliesdir)\$(PKG).xml "$(install_assembliesdir)" -!if "$(generate_policies)" == "yes" - copy $(assembliesdir)\$(POLICY_TARGET) "$(install_assembliesdir)" -!endif -!if "$(DEBUG)" == "yes" - copy $(assembliesdir)\$(PKG).pdb "$(install_assembliesdir)" -!endif - -$(GDIR)\BuiltinSequences.cs: "$(SDIR)\BuiltinSequences.ice" "$(SLICE2CS)" "$(SLICEPARSERLIB)" - del /q $(GDIR)\BuiltinSequences.cs - "$(SLICE2CS)" $(SLICE2CSFLAGS) --stream "$(SDIR)\BuiltinSequences.ice" - move BuiltinSequences.cs $(GDIR) diff --git a/csharp/src/Ice/MetricsAdminI.cs b/csharp/src/Ice/MetricsAdminI.cs index bd2639317a9..53956277145 100644 --- a/csharp/src/Ice/MetricsAdminI.cs +++ b/csharp/src/Ice/MetricsAdminI.cs @@ -21,29 +21,29 @@ namespace IceInternal IceMX.MetricsFailures[] getFailures(); IceMX.MetricsFailures getFailures(string id); Dictionary<string, string> getProperties(); - }; + } interface ISubMap { void addSubMapToMetrics(IceMX.Metrics metrics); - }; + } interface ISubMapCloneFactory { ISubMap create(); - }; + } interface ISubMapFactory { ISubMapCloneFactory createCloneFactory(string subMapPrefix, Ice.Properties properties); - }; + } internal interface IMetricsMapFactory { void registerSubMap<S>(string subMap, System.Reflection.FieldInfo field) where S : IceMX.Metrics, new(); void update(); IMetricsMap create(string mapPrefix, Ice.Properties properties); - }; + } internal class SubMap<S> : ISubMap where S : IceMX.Metrics, new() { @@ -72,7 +72,7 @@ namespace IceInternal readonly private MetricsMap<S> _map; readonly private System.Reflection.FieldInfo _field; - }; + } internal class SubMapCloneFactory<S> : ISubMapCloneFactory where S : IceMX.Metrics, new() { @@ -89,7 +89,7 @@ namespace IceInternal readonly private MetricsMap<S> _map; readonly private System.Reflection.FieldInfo _field; - }; + } class SubMapFactory<S> : ISubMapFactory where S : IceMX.Metrics, new() { @@ -104,7 +104,7 @@ namespace IceInternal } readonly private System.Reflection.FieldInfo _field; - }; + } public class MetricsMap<T> : IMetricsMap where T : IceMX.Metrics, new() { @@ -231,7 +231,7 @@ namespace IceInternal private T _object; private Dictionary<string, int> _failures; private Dictionary<string, ISubMap> _subMaps; - }; + } internal MetricsMap(string mapPrefix, Ice.Properties props, Dictionary<string, ISubMapFactory> subMaps) { @@ -248,7 +248,7 @@ namespace IceInternal if(groupBy.Length > 0) { string v = ""; - bool attribute = Char.IsLetter(groupBy[0]) || Char.IsDigit(groupBy[0]); + bool attribute = char.IsLetter(groupBy[0]) || char.IsDigit(groupBy[0]); if(!attribute) { _groupByAttributes.Add(""); @@ -256,7 +256,7 @@ namespace IceInternal foreach(char p in groupBy) { - bool isAlphaNum = Char.IsLetter(p) || Char.IsDigit(p) || p == '.'; + bool isAlphaNum = char.IsLetter(p) || char.IsDigit(p) || p == '.'; if(attribute && !isAlphaNum) { _groupByAttributes.Add(v); @@ -543,7 +543,7 @@ namespace IceInternal readonly private Dictionary<string, Entry> _objects = new Dictionary<string, Entry>(); readonly private Dictionary<string, ISubMapCloneFactory> _subMaps; private LinkedList<Entry> _detachedQueue; - }; + } internal class MetricsViewI { @@ -661,7 +661,7 @@ namespace IceInternal readonly private string _name; readonly private Dictionary<string, IMetricsMap> _maps = new Dictionary<string, IMetricsMap>(); - }; + } public class MetricsAdminI : IceMX.MetricsAdminDisp_, Ice.PropertiesAdminUpdateCallback { @@ -713,11 +713,7 @@ namespace IceInternal class MetricsMapFactory<T> : IMetricsMapFactory where T : IceMX.Metrics, new() { -#if COMPACT - public MetricsMapFactory(Ice.VoidAction updater) -#else - public MetricsMapFactory(System.Action updater) -#endif + public MetricsMapFactory(Action updater) { _updater = updater; } @@ -739,13 +735,9 @@ namespace IceInternal _subMaps.Add(subMap, new SubMapFactory<S>(field)); } -#if COMPACT - readonly private Ice.VoidAction _updater; -#else - readonly private System.Action _updater; -#endif + readonly private Action _updater; readonly private Dictionary<string, ISubMapFactory> _subMaps = new Dictionary<string, ISubMapFactory>(); - }; + } public MetricsAdminI(Ice.Properties properties, Ice.Logger logger) { @@ -867,7 +859,7 @@ namespace IceInternal lock(this) { MetricsViewI view = getMetricsView(viewName); - timestamp = IceInternal.Time.currentMonotonicTimeMillis(); + timestamp = Time.currentMonotonicTimeMillis(); if(view != null) { return view.getMetrics(); @@ -903,11 +895,7 @@ namespace IceInternal } } -#if COMPACT - public void registerMap<T>(string map, Ice.VoidAction updater) -#else - public void registerMap<T>(string map, System.Action updater) -#endif + public void registerMap<T>(string map, Action updater) where T : IceMX.Metrics, new() { bool updated; diff --git a/csharp/src/Ice/MetricsObserverI.cs b/csharp/src/Ice/MetricsObserverI.cs index 9e5de0623e3..82a600e38ef 100644 --- a/csharp/src/Ice/MetricsObserverI.cs +++ b/csharp/src/Ice/MetricsObserverI.cs @@ -24,9 +24,9 @@ namespace IceMX { _name = name; } - + protected abstract object resolve(object obj); - + public string resolveImpl(object obj) { try @@ -38,22 +38,45 @@ namespace IceMX } return ""; } - catch(ArgumentOutOfRangeException ex) + catch(ArgumentOutOfRangeException) { - throw ex; + throw; } catch(Exception ex) { -#if COMPACT - throw new ArgumentOutOfRangeException(_name, ex.ToString()); -#else throw new ArgumentOutOfRangeException(_name, ex); -#endif } } - + + protected object getField(System.Reflection.FieldInfo field, object obj) + { + while(obj != null) + { + try + { + return field.GetValue(obj); + } + catch(ArgumentException) + { + if(obj is Ice.EndpointInfo) + { + obj = ((Ice.EndpointInfo)obj).underlying; + } + else if(obj is Ice.ConnectionInfo) + { + obj = ((Ice.ConnectionInfo)obj).underlying; + } + else + { + throw; + } + } + } + return null; + } + readonly protected string _name; - }; + } class FieldResolverI : Resolver { @@ -62,15 +85,15 @@ namespace IceMX Debug.Assert(field != null); _field = field; } - + override protected object resolve(object obj) { - return _field.GetValue(obj); + return getField(_field, obj); } - + readonly private System.Reflection.FieldInfo _field; - }; - + } + class MethodResolverI : Resolver { internal MethodResolverI(string name, System.Reflection.MethodInfo method) : base(name) @@ -78,14 +101,14 @@ namespace IceMX Debug.Assert(method != null); _method = method; } - + override protected object resolve(object obj) { return _method.Invoke(obj, null); } - + readonly private System.Reflection.MethodInfo _method; - }; + } class MemberFieldResolverI : Resolver { @@ -97,24 +120,24 @@ namespace IceMX _method = method; _field = field; } - + override protected object resolve(object obj) { object o = _method.Invoke(obj, null); if(o != null) { - return _field.GetValue(o); + return getField(_field, o); } throw new ArgumentOutOfRangeException(_name); } - + readonly private System.Reflection.MethodInfo _method; readonly private System.Reflection.FieldInfo _field; - }; - + } + class MemberMethodResolverI : Resolver { - internal MemberMethodResolverI(string name, System.Reflection.MethodInfo method, + internal MemberMethodResolverI(string name, System.Reflection.MethodInfo method, System.Reflection.MethodInfo subMeth) : base(name) { @@ -122,7 +145,7 @@ namespace IceMX _method = method; _subMethod = subMeth; } - + override protected object resolve(object obj) { object o = _method.Invoke(obj, null); @@ -132,10 +155,10 @@ namespace IceMX } throw new ArgumentOutOfRangeException(_name); } - + readonly private System.Reflection.MethodInfo _method; readonly private System.Reflection.MethodInfo _subMethod; - }; + } protected AttributeResolver() { @@ -159,33 +182,33 @@ namespace IceMX } return resolver.resolveImpl(helper); } - - public void + + public void add(string name, System.Reflection.MethodInfo method) { _attributes.Add(name, new MethodResolverI(name, method)); } - - public void + + public void add(string name, System.Reflection.FieldInfo field) { _attributes.Add(name, new FieldResolverI(name, field)); } - - public void + + public void add(string name, System.Reflection.MethodInfo method, System.Reflection.FieldInfo field) { _attributes.Add(name, new MemberFieldResolverI(name, method, field)); } - - public void + + public void add(string name, System.Reflection.MethodInfo method, System.Reflection.MethodInfo subMethod) { _attributes.Add(name, new MemberMethodResolverI(name, method, subMethod)); } private Dictionary<string, Resolver> _attributes = new Dictionary<string, Resolver>(); - }; + } protected MetricsHelper(AttributeResolver attributes) { @@ -208,12 +231,12 @@ namespace IceMX } private AttributeResolver _attributes; - }; + } public class Observer<T> : Stopwatch, Ice.Instrumentation.Observer where T : Metrics, new() { public delegate void MetricsUpdate(T m); - + virtual public void attach() { Start(); @@ -236,7 +259,7 @@ namespace IceMX e.failed(exceptionName); } } - + public void forEach(MetricsUpdate u) { foreach(MetricsMap<T>.Entry e in _objects) @@ -253,7 +276,7 @@ namespace IceMX { return; } - + _previousDelay = previous._previousDelay + (long)(previous.ElapsedTicks / (Frequency / 1000000.0)); foreach(MetricsMap<T>.Entry e in previous._objects) { @@ -263,7 +286,7 @@ namespace IceMX } } } - + public ObserverImpl getObserver<S, ObserverImpl>(string mapName, MetricsHelper<S> helper) where S : Metrics, new() where ObserverImpl : Observer<S>, new() @@ -311,10 +334,10 @@ namespace IceMX } return null; } - + private List<MetricsMap<T>.Entry> _objects; private long _previousDelay = 0; - }; + } public class ObserverFactory<T, O> where T : Metrics, new() where O : Observer<T>, new() { @@ -369,7 +392,7 @@ namespace IceMX metricsObjects.Add(e); } } - + if(metricsObjects == null) { if(old != null) @@ -407,11 +430,7 @@ namespace IceMX public void update() { -#if COMPACT - Ice.VoidAction updater; -#else - System.Action updater; -#endif + Action updater; lock(this) { _maps.Clear(); @@ -429,26 +448,18 @@ namespace IceMX } } -#if COMPACT - public void setUpdater(Ice.VoidAction updater) -#else - public void setUpdater(System.Action updater) -#endif + public void setUpdater(Action updater) { lock(this) { _updater = updater; } } - - private readonly IceInternal.MetricsAdminI _metrics; + + private readonly MetricsAdminI _metrics; private readonly string _name; private List<MetricsMap<T>> _maps = new List<MetricsMap<T>>(); private volatile bool _enabled; -#if COMPACT - private Ice.VoidAction _updater; -#else - private System.Action _updater; -#endif - }; + private Action _updater; + } } diff --git a/csharp/src/Ice/Network.cs b/csharp/src/Ice/Network.cs index 1201366b648..d9172aa086c 100644 --- a/csharp/src/Ice/Network.cs +++ b/csharp/src/Ice/Network.cs @@ -10,17 +10,10 @@ namespace IceInternal { using System; - using System.Collections; using System.Collections.Generic; - using System.ComponentModel; - using System.Diagnostics; using System.Net; -#if !COMPACT && !UNITY using System.Net.NetworkInformation; -#endif using System.Net.Sockets; - using System.Runtime.InteropServices; - using System.Threading; using System.Globalization; public sealed class Network @@ -30,71 +23,10 @@ namespace IceInternal public const int EnableIPv6 = 1; public const int EnableBoth = 2; -#if COMPACT - public static SocketError socketErrorCode(SocketException ex) - { - return (SocketError)ex.ErrorCode; - } -#else public static SocketError socketErrorCode(SocketException ex) { return ex.SocketErrorCode; } -#endif - -#if COMPACT - // - // SocketError enumeration isn't available with Silverlight - // - public enum SocketError - { - Interrupted = 10004, // A blocking Socket call was canceled. - //AccessDenied =10013, // An attempt was made to access a Socket in a way that is forbidden by its access permissions. - Fault = 10014, // An invalid pointer address was detected by the underlying socket provider. - InvalidArgument = 10022, // An invalid argument was supplied to a Socket member. - TooManyOpenSockets = 10024, // There are too many open sockets in the underlying socket provider. - WouldBlock = 10035, // An operation on a nonblocking socket cannot be completed immediately. - InProgress = 10036, // A blocking operation is in progress. - //AlreadyInProgress = 10037, // The nonblocking Socket already has an operation in progress. - //NotSocket = 10038, // A Socket operation was attempted on a non-socket. - //DestinationAddressRequired = 10039, // A required address was omitted from an operation on a Socket. - MessageSize = 10040, // The datagram is too long. - //ProtocolType = 10041, // The protocol type is incorrect for this Socket. - //ProtocolOption = 10042, // An unknown, invalid, or unsupported option or level was used with a Socket. - //ProtocolNotSupported = 10043, // The protocol is not implemented or has not been configured. - //SocketNotSupported = 10044, // The support for the specified socket type does not exist in this address family. - //OperationNotSupported = 10045, // The address family is not supported by the protocol family. - //ProtocolFamilyNotSupported = 10046, // The protocol family is not implemented or has not been configured. - //AddressFamilyNotSupported = 10047, // The address family specified is not supported. - //AddressAlreadyInUse = 10048, // Only one use of an address is normally permitted. - //AddressNotAvailable = 10049, // The selected IP address is not valid in this context. - NetworkDown = 10050, // The network is not available. - NetworkUnreachable = 10051, // No route to the remote host exists. - NetworkReset = 10052, // The application tried to set KeepAlive on a connection that has already timed out. - ConnectionAborted = 10053, // The connection was aborted by the .NET Framework or the underlying socket provider. - ConnectionReset = 10054, // The connection was reset by the remote peer. - NoBufferSpaceAvailable = 10055, // No free buffer space is available for a Socket operation. - //IsConnected = 10056, // The Socket is already connected. - NotConnected = 10057, // The application tried to send or receive data, and the Socket is not connected. - Shutdown = 10058, // A request to send or receive data was disallowed because the Socket has already been closed. - TimedOut = 10060, // The connection attempt timed out, or the connected host has failed to respond. - ConnectionRefused = 10061, // The remote host is actively refusing a connection. - //HostDown = 10064, // The operation failed because the remote host is down. - HostUnreachable = 10065, // There is no network route to the specified host. - //ProcessLimit = 10067, // Too many processes are using the underlying socket provider. - //SystemNotReady = 10091, // The network subsystem is unavailable. - //VersionNotSupported = 10092, // The version of the underlying socket provider is out of range. - //NotInitialized = 10093, // The underlying socket provider has not been initialized. - //Disconnecting = 10101, // A graceful shutdown is in progress. - //TypeNotFound = 10109, // The specified class was not found. - //HostNotFound = 11001, // No such host is known. The name is not an official host name or alias. - TryAgain = 11002, // The name of the host could not be resolved. Try again later. - //NoRecovery = 11003, // The error is unrecoverable or the requested database cannot be located. - //NoData = 11004, // The requested name or IP address was not found on the name server. - //IOPending = 997, // The application has initiated an overlapped operation that cannot be completed immediately. - OperationAborted =995 // The overlapped operation was aborted due to the closure of the Socket. - } -#endif public static bool interrupted(SocketException ex) { @@ -117,7 +49,7 @@ namespace IceInternal { SocketError error = socketErrorCode(ex); return error == SocketError.NoBufferSpaceAvailable || - error == SocketError.Fault; + error == SocketError.Fault; } public static bool wouldBlock(SocketException ex) @@ -166,7 +98,6 @@ namespace IceInternal return connectionLost(ex.InnerException as SocketException); } -#if !UNITY // // In other cases the IOException has no inner exception. We could examine the // exception's message, but that is fragile due to localization issues. We @@ -186,8 +117,6 @@ namespace IceInternal { return true; } -#endif - return false; } @@ -226,7 +155,7 @@ namespace IceInternal return ex.Message.IndexOf("period of time", StringComparison.Ordinal) >= 0; } - public static bool noMoreFds(System.Exception ex) + public static bool noMoreFds(Exception ex) { try { @@ -240,24 +169,20 @@ namespace IceInternal public static bool isMulticast(IPEndPoint addr) { -#if COMPACT - string ip = addr.Address.ToString().ToUpper(); -#else string ip = addr.Address.ToString().ToUpperInvariant(); -#endif if(addr.AddressFamily == AddressFamily.InterNetwork) { char[] splitChars = { '.' }; string[] arr = ip.Split(splitChars); try { - int i = System.Int32.Parse(arr[0], CultureInfo.InvariantCulture); + int i = int.Parse(arr[0], CultureInfo.InvariantCulture); if(i >= 223 && i <= 239) { return true; } } - catch(System.FormatException) + catch(FormatException) { return false; } @@ -316,12 +241,8 @@ namespace IceInternal try { setTcpNoDelay(socket); -#if !SILVERLIGHT socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); -# if !__MonoCS__ setTcpLoopbackFastPath(socket); -# endif -#endif } catch(SocketException ex) { @@ -335,7 +256,6 @@ namespace IceInternal public static Socket createServerSocket(bool udp, AddressFamily family, int protocol) { Socket socket = createSocket(udp, family); -# if !COMPACT && !UNITY && !__MonoCS__ && !SILVERLIGHT && !DOTNET3_5 // // The IPv6Only enumerator was added in .NET 4. // @@ -352,7 +272,6 @@ namespace IceInternal throw new Ice.SocketException(ex); } } -#endif return socket; } @@ -392,30 +311,25 @@ namespace IceInternal { try { -#if SILVERLIGHT - socket.NoDelay = true; -#else socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); -#endif } - catch(System.Exception ex) + catch(Exception ex) { closeSocketNoThrow(socket); throw new Ice.SocketException(ex); } } -#if !SILVERLIGHT public static void setTcpLoopbackFastPath(Socket socket) { const int SIO_LOOPBACK_FAST_PATH = (-1744830448); - Byte[] OptionInValue = BitConverter.GetBytes(1); + byte[] OptionInValue = BitConverter.GetBytes(1); try { socket.IOControl(SIO_LOOPBACK_FAST_PATH, OptionInValue, null); } - catch(System.Exception) + catch(Exception) { // Expected on platforms that do not support TCP Loopback Fast Path } @@ -440,23 +354,18 @@ namespace IceInternal { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); } - catch(System.Exception ex) + catch(Exception ex) { closeSocketNoThrow(socket); throw new Ice.SocketException(ex); } } -#endif public static void setSendBufferSize(Socket socket, int sz) { try { -#if SILVERLIGHT - socket.SendBufferSize = sz; -#else socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, sz); -#endif } catch(SocketException ex) { @@ -470,11 +379,7 @@ namespace IceInternal int sz; try { -#if SILVERLIGHT - sz = socket.SendBufferSize; -#else sz = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); -#endif } catch(SocketException ex) { @@ -488,11 +393,7 @@ namespace IceInternal { try { -#if SILVERLIGHT - socket.ReceiveBufferSize = sz; -#else socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, sz); -#endif } catch(SocketException ex) { @@ -506,11 +407,7 @@ namespace IceInternal int sz = 0; try { -#if SILVERLIGHT - sz = socket.ReceiveBufferSize; -#else sz = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); -#endif } catch(SocketException ex) { @@ -520,7 +417,6 @@ namespace IceInternal return sz; } -#if !SILVERLIGHT public static void setReuseAddress(Socket socket, bool reuse) { try @@ -539,22 +435,9 @@ namespace IceInternal try { int ifaceIndex = getInterfaceIndex(iface, family); - if(ifaceIndex == -1) - { - try - { - ifaceIndex = System.Int32.Parse(iface, CultureInfo.InvariantCulture); - } - catch(System.FormatException ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException(ex); - } - } - if(family == AddressFamily.InterNetwork) { - ifaceIndex = (int)IPAddress.HostToNetworkOrder(ifaceIndex); + ifaceIndex = IPAddress.HostToNetworkOrder(ifaceIndex); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, ifaceIndex); } else @@ -573,37 +456,40 @@ namespace IceInternal { try { - int index = getInterfaceIndex(iface, group.AddressFamily); - if(group.AddressFamily == AddressFamily.InterNetwork) + var indexes = new HashSet<int>(); + foreach(string intf in getInterfacesForMulticast(iface, group)) { - MulticastOption option; -#if COMPACT - option = new MulticastOption(group); -#else - if(index == -1) - { - option = new MulticastOption(group); - } - - else + int index = getInterfaceIndex(intf, group.AddressFamily); + if(!indexes.Contains(index)) { - option = new MulticastOption(group, index); - } -#endif - s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, option); - } - else - { - IPv6MulticastOption option; - if(index == -1) - { - option = new IPv6MulticastOption(group); - } - else - { - option = new IPv6MulticastOption(group, index); + indexes.Add(index); + if(group.AddressFamily == AddressFamily.InterNetwork) + { + MulticastOption option; + if(index == -1) + { + option = new MulticastOption(group); + } + else + { + option = new MulticastOption(group, index); + } + s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, option); + } + else + { + IPv6MulticastOption option; + if(index == -1) + { + option = new IPv6MulticastOption(group); + } + else + { + option = new IPv6MulticastOption(group, index); + } + s.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, option); + } } - s.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, option); } } catch(Exception ex) @@ -612,15 +498,11 @@ namespace IceInternal throw new Ice.SocketException(ex); } } -#endif public static void setMcastTtl(Socket socket, int ttl, AddressFamily family) { try { -#if SILVERLIGHT - socket.Ttl = (short)ttl; -#else if(family == AddressFamily.InterNetwork) { socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, ttl); @@ -629,7 +511,6 @@ namespace IceInternal { socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, ttl); } -#endif } catch(SocketException ex) { @@ -638,7 +519,6 @@ namespace IceInternal } } -#if !SILVERLIGHT public static IPEndPoint doBind(Socket socket, EndPoint addr) { try @@ -673,9 +553,7 @@ namespace IceInternal throw new Ice.SocketException(ex); } } -#endif -#if !SILVERLIGHT public static bool doConnect(Socket fd, EndPoint addr, EndPoint sourceAddr) { EndPoint bindAddr = sourceAddr; @@ -726,19 +604,6 @@ namespace IceInternal // after the asynchronous connect. Seems like a bug in .NET. // setBlock(fd, fd.Blocking); - - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.NonWindows) - { - // - // Prevent self connect (self connect happens on Linux when a client tries to connect to - // a server which was just deactivated if the client socket re-uses the same ephemeral - // port as the server). - // - if(addr.Equals(getLocalAddress(fd))) - { - throw new Ice.ConnectionRefusedException(); - } - } return true; } @@ -820,22 +685,7 @@ namespace IceInternal // after the asynchronous connect. Seems like a bug in .NET. // setBlock(fd, fd.Blocking); - - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.NonWindows) - { - // - // Prevent self connect (self connect happens on Linux when a client tries to connect to - // a server which was just deactivated if the client socket re-uses the same ephemeral - // port as the server). - // - EndPoint remoteAddr = getRemoteAddress(fd); - if(remoteAddr != null && remoteAddr.Equals(getLocalAddress(fd))) - { - throw new Ice.ConnectionRefusedException(); - } - } } -#endif public static EndPoint getAddressForServer(string host, int port, int protocol, bool preferIPv6) { @@ -898,29 +748,13 @@ namespace IceInternal } catch(FormatException) { -#if !SILVERLIGHT if(!blocking) { return addresses; } -#endif } -#if SILVERLIGHT - if(protocol != EnableIPv6) - { - addresses.Add(new DnsEndPoint(host, port, AddressFamily.InterNetwork)); - } - if(protocol != EnableIPv4) - { - addresses.Add(new DnsEndPoint(host, port, AddressFamily.InterNetworkV6)); - } -#else -# if COMPACT - foreach(IPAddress a in Dns.GetHostEntry(host).AddressList) -# else foreach(IPAddress a in Dns.GetHostAddresses(host)) -# endif { if((a.AddressFamily == AddressFamily.InterNetwork && protocol != EnableIPv6) || (a.AddressFamily == AddressFamily.InterNetworkV6 && protocol != EnableIPv4)) @@ -928,7 +762,6 @@ namespace IceInternal addresses.Add(new IPEndPoint(a, port)); } } -#endif if(selType == Ice.EndpointSelectionType.Random) { @@ -957,7 +790,7 @@ namespace IceInternal e.host = host; throw e; } - catch(System.Exception ex) + catch(Exception ex) { Ice.DNSException e = new Ice.DNSException(ex); e.host = host; @@ -978,9 +811,6 @@ namespace IceInternal public static IPAddress[] getLocalAddresses(int protocol, bool includeLoopback) { -#if SILVERLIGHT - return new List<IPAddress>().ToArray(); -#else List<IPAddress> addresses; int retry = 5; @@ -988,7 +818,6 @@ namespace IceInternal try { addresses = new List<IPAddress>(); -# if !COMPACT && !UNITY NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach(NetworkInterface ni in nics) { @@ -1006,23 +835,6 @@ namespace IceInternal } } } -# else -# if COMPACT - foreach(IPAddress a in Dns.GetHostEntry(Dns.GetHostName()).AddressList) -# else - foreach(IPAddress a in Dns.GetHostAddresses(Dns.GetHostName())) -# endif - { - if((a.AddressFamily == AddressFamily.InterNetwork && protocol != EnableIPv6) || - (a.AddressFamily == AddressFamily.InterNetworkV6 && protocol != EnableIPv4)) - { - if(includeLoopback || !IPAddress.IsLoopback(a)) - { - addresses.Add(a); - } - } - } -# endif } catch(SocketException ex) { @@ -1034,7 +846,7 @@ namespace IceInternal e.host = "0.0.0.0"; throw e; } - catch(System.Exception ex) + catch(Exception ex) { Ice.DNSException e = new Ice.DNSException(ex); e.host = "0.0.0.0"; @@ -1042,7 +854,6 @@ namespace IceInternal } return addresses.ToArray(); -#endif } public static bool @@ -1054,7 +865,7 @@ namespace IceInternal } else if (addr.AddressFamily == AddressFamily.InterNetwork) { - Byte[] bytes = addr.GetAddressBytes(); + byte[] bytes = addr.GetAddressBytes(); return bytes[0] == 169 && bytes[1] == 254; } return false; @@ -1064,15 +875,8 @@ namespace IceInternal setTcpBufSize(Socket socket, ProtocolInstance instance) { // - // By default, on Windows we use a 128KB buffer size. On Unix - // platforms, we use the system defaults. - // - int dfltBufSize = 0; - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) - { - dfltBufSize = 128 * 1024; - } - + // By default, on Windows we use a 128KB buffer size. + int dfltBufSize = 128 * 1024; int rcvSize = instance.properties().getPropertyAsIntWithDefault("Ice.TCP.RcvSize", dfltBufSize); int sndSize = instance.properties().getPropertyAsIntWithDefault("Ice.TCP.SndSize", dfltBufSize); @@ -1131,33 +935,14 @@ namespace IceInternal public static List<string> getHostsForEndpointExpand(string host, int protocol, bool includeLoopback) { - bool wildcard = host.Length == 0; - bool ipv4Wildcard = false; - if(!wildcard) - { - try - { - IPAddress addr = IPAddress.Parse(host); - ipv4Wildcard = addr.Equals(IPAddress.Any); - wildcard = ipv4Wildcard || addr.Equals(IPAddress.IPv6Any); - } - catch(Exception) - { - } - } - List<string> hosts = new List<string>(); - if(wildcard) + bool ipv4Wildcard = false; + if(isWildcard(host, out ipv4Wildcard)) { - IPAddress[] addrs = - getLocalAddresses(ipv4Wildcard ? Network.EnableIPv4 : protocol, includeLoopback); + IPAddress[] addrs = getLocalAddresses(ipv4Wildcard ? EnableIPv4 : protocol, includeLoopback); foreach(IPAddress a in addrs) { -#if COMPACT - if(!IPAddress.IsLoopback(a)) -#else if(!isLinklocal(a)) -#endif { hosts.Add(a.ToString()); } @@ -1166,6 +951,26 @@ namespace IceInternal return hosts; } + public static List<string> getInterfacesForMulticast(string intf, IPAddress group) + { + List<string> interfaces = new List<string>(); + bool ipv4Wildcard = false; + int protocol = group.AddressFamily == AddressFamily.InterNetwork ? EnableIPv4 : EnableIPv6; + if(isWildcard(intf, out ipv4Wildcard)) + { + IPAddress[] addrs = getLocalAddresses(ipv4Wildcard ? EnableIPv4 : protocol, true); + foreach(IPAddress a in addrs) + { + interfaces.Add(a.ToString()); + } + } + if(interfaces.Count == 0) + { + interfaces.Add(intf); + } + return interfaces; + } + public static string fdToString(Socket socket, NetworkProxy proxy, EndPoint target) { try @@ -1239,11 +1044,7 @@ namespace IceInternal { if(endpoint == null) { -#if SILVERLIGHT - return "<not available>"; -#else return "<not bound>"; -#endif } return endpointAddressToString(endpoint) + ":" + endpointPort(endpoint); } @@ -1261,8 +1062,6 @@ namespace IceInternal public static EndPoint getLocalAddress(Socket socket) { - // Silverlight socket doesn't exposes a local endpoint -#if !SILVERLIGHT try { return socket.LocalEndPoint; @@ -1271,9 +1070,6 @@ namespace IceInternal { throw new Ice.SocketException(ex); } -#else - return null; -#endif } public static EndPoint @@ -1281,7 +1077,7 @@ namespace IceInternal { try { - return (EndPoint)socket.RemoteEndPoint; + return socket.RemoteEndPoint; } catch(SocketException) { @@ -1306,13 +1102,12 @@ namespace IceInternal // try { - return System.Int32.Parse(iface, CultureInfo.InvariantCulture); + return int.Parse(iface, CultureInfo.InvariantCulture); } - catch(System.FormatException) + catch(FormatException) { } -#if !COMPACT && !SILVERLIGHT && !UNITY NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); try { @@ -1371,18 +1166,18 @@ namespace IceInternal } } } -#endif - return -1; + + throw new ArgumentException("couldn't find interface `" + iface + "'"); } public static EndPoint getNumericAddress(string sourceAddress) { EndPoint addr = null; - if(!String.IsNullOrEmpty(sourceAddress)) + if(!string.IsNullOrEmpty(sourceAddress)) { - List<EndPoint> addrs = getAddresses(sourceAddress, 0, Network.EnableBoth, - Ice.EndpointSelectionType.Ordered, false, false); + List<EndPoint> addrs = getAddresses(sourceAddress, 0, EnableBoth, Ice.EndpointSelectionType.Ordered, + false, false); if(addrs.Count != 0) { return addrs[0]; @@ -1391,6 +1186,32 @@ namespace IceInternal return addr; } + private static bool + isWildcard(string address, out bool ipv4Wildcard) + { + ipv4Wildcard = false; + if(address.Length == 0) + { + return true; + } + + try + { + IPAddress addr = IPAddress.Parse(address); + if(addr.Equals(IPAddress.Any)) + { + ipv4Wildcard = true; + return true; + } + return addr.Equals(IPAddress.IPv6Any); + } + catch(Exception) + { + } + + return false; + } + public static bool addressEquals(EndPoint addr1, EndPoint addr2) { @@ -1418,13 +1239,6 @@ namespace IceInternal { if(endpoint != null) { -#if SILVERLIGHT - if(endpoint is DnsEndPoint) - { - DnsEndPoint dnsEndpoint = (DnsEndPoint)endpoint; - return dnsEndpoint.Host; - } -#endif if(endpoint is IPEndPoint) { IPEndPoint ipEndpoint = (IPEndPoint) endpoint; @@ -1439,13 +1253,6 @@ namespace IceInternal { if(endpoint != null) { -#if SILVERLIGHT - if(endpoint is DnsEndPoint) - { - DnsEndPoint dnsEndpoint = (DnsEndPoint)endpoint; - return dnsEndpoint.Port; - } -#endif if(endpoint is IPEndPoint) { IPEndPoint ipEndpoint = (IPEndPoint) endpoint; diff --git a/csharp/src/Ice/NetworkProxy.cs b/csharp/src/Ice/NetworkProxy.cs index c80557c8528..3bfe12870db 100644 --- a/csharp/src/Ice/NetworkProxy.cs +++ b/csharp/src/Ice/NetworkProxy.cs @@ -9,7 +9,6 @@ namespace IceInternal { - using System; using System.Net; using System.Net.Sockets; using System.Diagnostics; @@ -39,7 +38,6 @@ namespace IceInternal // void finish(Buffer readBuffer, Buffer writeBuffer); -#if !SILVERLIGHT // // If the proxy host needs to be resolved, this should return // a new NetworkProxy containing the IP address of the proxy. @@ -47,7 +45,7 @@ namespace IceInternal // it's safe if this this method blocks. // NetworkProxy resolveHost(int protocolSupport); -#endif + // // Returns the IP address of the network proxy. This method // must not block. It's only called on a network proxy object @@ -70,12 +68,8 @@ namespace IceInternal { public SOCKSNetworkProxy(string host, int port) { -#if SILVERLIGHT - _address = new DnsEndPoint(host, port, AddressFamily.InterNetwork); -#else _host = host; _port = port; -#endif } private SOCKSNetworkProxy(EndPoint address) @@ -144,7 +138,6 @@ namespace IceInternal } } -#if !SILVERLIGHT public NetworkProxy resolveHost(int protocolSupport) { Debug.Assert(_host != null); @@ -155,7 +148,6 @@ namespace IceInternal false, true)[0]); } -#endif public EndPoint getAddress() { @@ -173,10 +165,8 @@ namespace IceInternal return Network.EnableIPv4; } -#if !SILVERLIGHT private readonly string _host; private readonly int _port; -#endif private readonly EndPoint _address; } @@ -184,14 +174,9 @@ namespace IceInternal { public HTTPNetworkProxy(string host, int port) { -#if SILVERLIGHT - _address = new DnsEndPoint(host, port, AddressFamily.InterNetwork); - _protocolSupport = Network.EnableIPv4; -#else _host = host; _port = port; _protocolSupport = Network.EnableBoth; -#endif } private HTTPNetworkProxy(EndPoint address, int protocolSupport) @@ -209,12 +194,7 @@ namespace IceInternal str.Append(" HTTP/1.1\r\nHost: "); str.Append(addr); str.Append("\r\n\r\n"); - -#if SILVERLIGHT - byte[] b = System.Text.Encoding.UTF8.GetBytes(str.ToString()); -#else byte[] b = System.Text.Encoding.ASCII.GetBytes(str.ToString()); -#endif // // HTTP connect request @@ -271,7 +251,6 @@ namespace IceInternal } } -#if !SILVERLIGHT public NetworkProxy resolveHost(int protocolSupport) { Debug.Assert(_host != null); @@ -283,7 +262,6 @@ namespace IceInternal true)[0], protocolSupport); } -#endif public EndPoint getAddress() { @@ -301,10 +279,8 @@ namespace IceInternal return _protocolSupport; } -#if !SILVERLIGHT private readonly string _host; private readonly int _port; -#endif private readonly EndPoint _address; private readonly int _protocolSupport; } diff --git a/csharp/src/Ice/Object.cs b/csharp/src/Ice/Object.cs index be15a56a4a4..5d18fa986ba 100644 --- a/csharp/src/Ice/Object.cs +++ b/csharp/src/Ice/Object.cs @@ -8,39 +8,13 @@ // ********************************************************************** using System; -using System.Collections; +using System.Threading.Tasks; using System.Diagnostics; +using System.ComponentModel; namespace Ice { /// <summary> - /// Indicates the status of operation dispatch. - /// </summary> - public enum DispatchStatus - { - /// <summary> - /// Indicates that an operation was dispatched synchronously and successfully. - /// </summary> - DispatchOK, - - /// <summary> - /// Indicates that an operation was dispatched synchronously and raised a user exception. - /// </summary> - DispatchUserException, - - /// <summary> - /// Indicates that an operation was dispatched asynchronously. - /// </summary> - DispatchAsync - } - - public interface DispatchInterceptorAsyncCallback - { - bool response(bool ok); - bool exception(System.Exception ex); - } - - /// <summary> /// Interface for incoming requests. /// </summary> public interface Request @@ -55,44 +29,23 @@ namespace Ice /// <summary> /// the base interface for servants. /// </summary> - public interface Object : System.ICloneable + public interface Object : ICloneable { /// <summary> /// Tests whether this object supports a specific Slice interface. /// </summary> /// /// <param name="s">The type ID of the Slice interface to test against.</param> - /// <returns>True if this object has the interface - /// specified by s or derives from the interface specified by s.</returns> - bool ice_isA(string s); - - /// <summary> - /// Tests whether this object supports a specific Slice interface. - /// </summary> - /// - /// <param name="s">The type ID of the Slice interface to test against.</param> /// <param name="current">The Current object for the invocation.</param> /// <returns>True if this object has the interface /// specified by s or derives from the interface specified by s.</returns> - bool ice_isA(string s, Current current); - - /// <summary> - /// Tests whether this object can be reached. - /// </summary> - void ice_ping(); + bool ice_isA(string s, Current current = null); /// <summary> /// Tests whether this object can be reached. /// </summary> /// <param name="current">The Current object for the invocation.</param> - void ice_ping(Current current); - - /// <summary> - /// Returns the Slice type IDs of the interfaces supported by this object. - /// </summary> - /// <returns>The Slice type IDs of the interfaces supported by this object, in base-to-derived - /// order. The first element of the returned array is always ::Ice::Object.</returns> - string[] ice_ids(); + void ice_ping(Current current = null); /// <summary> /// Returns the Slice type IDs of the interfaces supported by this object. @@ -100,58 +53,24 @@ namespace Ice /// <param name="current">The Current object for the invocation.</param> /// <returns>The Slice type IDs of the interfaces supported by this object, in base-to-derived /// order. The first element of the returned array is always ::Ice::Object.</returns> - string[] ice_ids(Current current); - - /// <summary> - /// Returns the Slice type ID of the most-derived interface supported by this object. - /// </summary> - /// <returns>The Slice type ID of the most-derived interface.</returns> - string ice_id(); + string[] ice_ids(Current current = null); /// <summary> /// Returns the Slice type ID of the most-derived interface supported by this object. /// </summary> /// <param name="current">The Current object for the invocation.</param> /// <returns>The Slice type ID of the most-derived interface.</returns> - string ice_id(Current current); - - /// <summary> - /// The Ice run time invokes this method prior to marshaling an object's data members. This allows a subclass - /// to override this method in order to validate its data members. - /// </summary> - void ice_preMarshal(); - - /// <summary> - /// This Ice run time invokes this method vafter unmarshaling an object's data members. This allows a - /// subclass to override this method in order to perform additional initialization. - /// </summary> - void ice_postUnmarshal(); + string ice_id(Current current = null); /// <summary> /// Dispatches an invocation to a servant. This method is used by dispatch interceptors to forward an invocation /// to a servant (or to another interceptor). /// </summary> /// <param name="request">The details of the invocation.</param> - /// <param name="cb">The callback object for asynchchronous dispatch. For synchronous dispatch, - /// the callback object must be null.</param> - /// <returns>The dispatch status for the operation.</returns> - DispatchStatus ice_dispatch(Request request, DispatchInterceptorAsyncCallback cb); + /// <returns>The task if dispatched asynchronously, null otherwise.</returns> + Task<OutputStream> ice_dispatch(Request request); - /// <summary> - /// Dispatches an invocation to a servant. This method is used by dispatch interceptors to forward an invocation - /// to a servant (or to another interceptor). - /// </summary> - /// <param name="request">The details of the invocation.</param> - /// <returns>The dispatch status for the operation.</returns> - DispatchStatus ice_dispatch(Request request); - - DispatchStatus dispatch__(IceInternal.Incoming inc, Current current); - - void write__(IceInternal.BasicStream os__); - void read__(IceInternal.BasicStream is__); - - void write__(OutputStream outS__); - void read__(InputStream inS__); + Task<OutputStream> iceDispatch(IceInternal.Incoming inc, Current current); } /// <summary> @@ -176,7 +95,7 @@ namespace Ice return MemberwiseClone(); } - public static readonly string[] ids__ = + private static readonly string[] _ids = { "::Ice::Object" }; @@ -185,67 +104,43 @@ namespace Ice /// Tests whether this object supports a specific Slice interface. /// </summary> /// <param name="s">The type ID of the Slice interface to test against.</param> - /// <returns>The return value is true if s is ::Ice::Object.</returns> - public virtual bool ice_isA(string s) - { - return s.Equals(ids__[0]); - } - - /// <summary> - /// Tests whether this object supports a specific Slice interface. - /// </summary> - /// <param name="s">The type ID of the Slice interface to test against.</param> /// <param name="current">The Current object for the invocation.</param> /// <returns>The return value is true if s is ::Ice::Object.</returns> - public virtual bool ice_isA(string s, Current current) + public virtual bool ice_isA(string s, Current current = null) { - return s.Equals(ids__[0]); + return s.Equals(_ids[0]); } - public static DispatchStatus ice_isA___(Ice.Object __obj, IceInternal.Incoming inS__, Current __current) + [EditorBrowsable(EditorBrowsableState.Never)] + public static Task<OutputStream> iceD_ice_isA(Object obj, IceInternal.Incoming inS, Current current) { - IceInternal.BasicStream is__ = inS__.startReadParams(); - string __id = is__.readString(); - inS__.endReadParams(); - bool __ret = __obj.ice_isA(__id, __current); - IceInternal.BasicStream os__ = inS__.startWriteParams__(FormatType.DefaultFormat); - os__.writeBool(__ret); - inS__.endWriteParams__(true); - return DispatchStatus.DispatchOK; - } - - /// <summary> - /// Tests whether this object can be reached. - /// </summary> - public virtual void ice_ping() - { - // Nothing to do. + InputStream istr = inS.startReadParams(); + var id = istr.readString(); + inS.endReadParams(); + var ret = obj.ice_isA(id, current); + var ostr = inS.startWriteParams(); + ostr.writeBool(ret); + inS.endWriteParams(ostr); + inS.setResult(ostr); + return null; } /// <summary> /// Tests whether this object can be reached. /// <param name="current">The Current object for the invocation.</param> /// </summary> - public virtual void ice_ping(Current current) + public virtual void ice_ping(Current current = null) { // Nothing to do. } - public static DispatchStatus ice_ping___(Ice.Object __obj, IceInternal.Incoming inS__, Current __current) + [EditorBrowsable(EditorBrowsableState.Never)] + public static Task<OutputStream> iceD_ice_ping(Object obj, IceInternal.Incoming inS, Current current) { - inS__.readEmptyParams(); - __obj.ice_ping(__current); - inS__.writeEmptyParams__(); - return DispatchStatus.DispatchOK; - } - - /// <summary> - /// Returns the Slice type IDs of the interfaces supported by this object. - /// </summary> - /// <returns>An array whose only element is ::Ice::Object.</returns> - public virtual string[] ice_ids() - { - return ids__; + inS.readEmptyParams(); + obj.ice_ping(current); + inS.setResult(inS.writeEmptyParams()); + return null; } /// <summary> @@ -253,28 +148,21 @@ namespace Ice /// </summary> /// <param name="current">The Current object for the invocation.</param> /// <returns>An array whose only element is ::Ice::Object.</returns> - public virtual string[] ice_ids(Current current) + public virtual string[] ice_ids(Current current = null) { - return ids__; + return _ids; } - public static DispatchStatus ice_ids___(Ice.Object __obj, IceInternal.Incoming inS__, Current __current) - { - inS__.readEmptyParams(); - string[] ret__ = __obj.ice_ids(__current); - IceInternal.BasicStream os__ = inS__.startWriteParams__(FormatType.DefaultFormat); - os__.writeStringSeq(ret__); - inS__.endWriteParams__(true); - return DispatchStatus.DispatchOK; - } - - /// <summary> - /// Returns the Slice type ID of the most-derived interface supported by this object. - /// </summary> - /// <returns>The return value is always ::Ice::Object.</returns> - public virtual string ice_id() + [EditorBrowsable(EditorBrowsableState.Never)] + public static Task<OutputStream> iceD_ice_ids(Object obj, IceInternal.Incoming inS, Current current) { - return ids__[0]; + inS.readEmptyParams(); + var ret = obj.ice_ids(current); + var ostr = inS.startWriteParams(); + ostr.writeStringSeq(ret); + inS.endWriteParams(ostr); + inS.setResult(ostr); + return null; } /// <summary> @@ -282,19 +170,21 @@ namespace Ice /// </summary> /// <param name="current">The Current object for the invocation.</param> /// <returns>The return value is always ::Ice::Object.</returns> - public virtual string ice_id(Current current) + public virtual string ice_id(Current current = null) { - return ids__[0]; + return _ids[0]; } - public static DispatchStatus ice_id___(Ice.Object __obj, IceInternal.Incoming inS__, Current __current) + [EditorBrowsable(EditorBrowsableState.Never)] + public static Task<OutputStream> iceD_ice_id(Object obj, IceInternal.Incoming inS, Current current) { - inS__.readEmptyParams(); - string __ret = __obj.ice_id(__current); - IceInternal.BasicStream os__ = inS__.startWriteParams__(FormatType.DefaultFormat); - os__.writeString(__ret); - inS__.endWriteParams__(true); - return DispatchStatus.DispatchOK; + inS.readEmptyParams(); + var ret = obj.ice_id(current); + var ostr = inS.startWriteParams(); + ostr.writeString(ret); + inS.endWriteParams(ostr); + inS.setResult(ostr); + return null; } /// <summary> @@ -303,26 +193,10 @@ namespace Ice /// <returns>The return value is always ::Ice::Object.</returns> public static string ice_staticId() { - return ids__[0]; + return _ids[0]; } - /// <summary> - /// The Ice run time invokes this method prior to marshaling an object's data members. This allows a subclass - /// to override this method in order to validate its data members. - /// </summary> - public virtual void ice_preMarshal() - { - } - - /// <summary> - /// This Ice run time invokes this method vafter unmarshaling an object's data members. This allows a - /// subclass to override this method in order to perform additional initialization. - /// </summary> - public virtual void ice_postUnmarshal() - { - } - - private static readonly string[] all__ = new string[] + private static readonly string[] _all = new string[] { "ice_id", "ice_ids", "ice_isA", "ice_ping" }; @@ -332,131 +206,59 @@ namespace Ice /// to a servant (or to another interceptor). /// </summary> /// <param name="request">The details of the invocation.</param> - /// <param name="cb">The callback object for asynchchronous dispatch. For synchronous dispatch, the - /// callback object must be null.</param> - /// <returns>The dispatch status for the operation.</returns> - public virtual DispatchStatus ice_dispatch(Request request, DispatchInterceptorAsyncCallback cb) + /// <returns>The task if dispatched asynchronously, null otherwise.</returns> + public virtual Task<OutputStream> ice_dispatch(Request request) { - IceInternal.Incoming inc = (IceInternal.Incoming)request; - if(cb != null) - { - inc.push(cb); - } - try - { - inc.startOver(); // may raise ResponseSentException - return dispatch__(inc, inc.getCurrent()); - } - finally - { - if(cb != null) - { - inc.pop(); - } - } + var inc = (IceInternal.Incoming)request; + inc.startOver(); + return iceDispatch(inc, inc.getCurrent()); } - /// <summary> - /// Dispatches an invocation to a servant. This method is used by dispatch interceptors to forward an invocation - /// to a servant (or to another interceptor). - /// </summary> - /// <param name="request">The details of the invocation.</param> - /// <returns>The dispatch status for the operation.</returns> - public virtual DispatchStatus ice_dispatch(Request request) + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual Task<OutputStream> iceDispatch(IceInternal.Incoming inc, Current current) { - return ice_dispatch(request, null); - } - - public virtual DispatchStatus dispatch__(IceInternal.Incoming inc, Current current) - { - int pos = System.Array.BinarySearch(all__, current.operation); + int pos = Array.BinarySearch(_all, current.operation); if(pos < 0) { - throw new Ice.OperationNotExistException(current.id, current.facet, current.operation); + throw new OperationNotExistException(current.id, current.facet, current.operation); } switch(pos) { case 0: { - return ice_id___(this, inc, current); + return iceD_ice_id(this, inc, current); } case 1: { - return ice_ids___(this, inc, current); + return iceD_ice_ids(this, inc, current); } case 2: { - return ice_isA___(this, inc, current); + return iceD_ice_isA(this, inc, current); } case 3: { - return ice_ping___(this, inc, current); + return iceD_ice_ping(this, inc, current); } } Debug.Assert(false); - throw new Ice.OperationNotExistException(current.id, current.facet, current.operation); - } - - public virtual void write__(IceInternal.BasicStream os__) - { - os__.startWriteObject(null); - writeImpl__(os__); - os__.endWriteObject(); - } - - public virtual void read__(IceInternal.BasicStream is__) - { - is__.startReadObject(); - readImpl__(is__); - is__.endReadObject(false); - } - - public virtual void write__(OutputStream os__) - { - os__.startObject(null); - writeImpl__(os__); - os__.endObject(); - } - - public virtual void read__(InputStream is__) - { - is__.startObject(); - readImpl__(is__); - is__.endObject(false); - } - - protected virtual void writeImpl__(IceInternal.BasicStream os__) - { - } - - protected virtual void readImpl__(IceInternal.BasicStream is__) - { - } - - protected virtual void writeImpl__(OutputStream os__) - { - throw new MarshalException("class was not generated with stream support"); - } - - protected virtual void readImpl__(InputStream is__) - { - throw new MarshalException("class was not generated with stream support"); + throw new OperationNotExistException(current.id, current.facet, current.operation); } private static string operationModeToString(OperationMode mode) { - if(mode == Ice.OperationMode.Normal) + if(mode == OperationMode.Normal) { return "::Ice::Normal"; } - if(mode == Ice.OperationMode.Nonmutating) + if(mode == OperationMode.Nonmutating) { return "::Ice::Nonmutating"; } - if(mode == Ice.OperationMode.Idempotent) + if(mode == OperationMode.Idempotent) { return "::Ice::Idempotent"; } @@ -464,7 +266,7 @@ namespace Ice return "???"; } - public static void checkMode__(OperationMode expected, OperationMode received) + public static void iceCheckMode(OperationMode expected, OperationMode received) { if(expected != received) { @@ -477,15 +279,13 @@ namespace Ice } else { - Ice.MarshalException ex = new Ice.MarshalException(); + MarshalException ex = new MarshalException(); ex.reason = "unexpected operation mode. expected = " + operationModeToString(expected) + " received = " + operationModeToString(received); throw ex; } } } - - public static Ice.Current defaultCurrent = new Ice.Current(); } /// <summary> @@ -493,7 +293,7 @@ namespace Ice /// derives a concrete servant class from Blobject that /// implements the Blobject.ice_invoke method. /// </summary> - public abstract class Blobject : Ice.ObjectImpl + public abstract class Blobject : ObjectImpl { /// <summary> /// Dispatch an incoming request. @@ -509,40 +309,30 @@ namespace Ice /// Ice run-time exception, it must throw it directly.</returns> public abstract bool ice_invoke(byte[] inParams, out byte[] outParams, Current current); - public override DispatchStatus dispatch__(IceInternal.Incoming inS__, Current current) + [EditorBrowsable(EditorBrowsableState.Never)] + public override Task<OutputStream> iceDispatch(IceInternal.Incoming inS, Current current) { - byte[] inEncaps = inS__.readParamEncaps(); + byte[] inEncaps = inS.readParamEncaps(); byte[] outEncaps; bool ok = ice_invoke(inEncaps, out outEncaps, current); - inS__.writeParamEncaps__(outEncaps, ok); - if(ok) - { - return DispatchStatus.DispatchOK; - } - else - { - return DispatchStatus.DispatchUserException; - } + inS.setResult(inS.writeParamEncaps(outEncaps, ok)); + return null; } } - public abstract class BlobjectAsync : Ice.ObjectImpl + public abstract class BlobjectAsync : ObjectImpl { - public abstract void ice_invoke_async(AMD_Object_ice_invoke cb, byte[] inEncaps, Current current); + public abstract Task<Ice.Object_Ice_invokeResult> ice_invokeAsync(byte[] inEncaps, Current current); - public override DispatchStatus dispatch__(IceInternal.Incoming inS__, Current current) + [EditorBrowsable(EditorBrowsableState.Never)] + public override Task<Ice.OutputStream> iceDispatch(IceInternal.Incoming inS, Current current) { - byte[] inEncaps = inS__.readParamEncaps(); - AMD_Object_ice_invoke cb = new _AMD_Object_ice_invoke(inS__); - try - { - ice_invoke_async(cb, inEncaps, current); - } - catch(System.Exception ex) + byte[] inEncaps = inS.readParamEncaps(); + return ice_invokeAsync(inEncaps, current).ContinueWith((Task<Object_Ice_invokeResult> t) => { - cb.ice_exception(ex); - } - return DispatchStatus.DispatchAsync; + var ret = t.GetAwaiter().GetResult(); + return Task.FromResult(inS.writeParamEncaps(ret.outEncaps, ret.returnValue)); + }).Unwrap(); } } } diff --git a/csharp/src/Ice/ObjectAdapterFactory.cs b/csharp/src/Ice/ObjectAdapterFactory.cs index f1ed93c40a7..791e26f8b5d 100644 --- a/csharp/src/Ice/ObjectAdapterFactory.cs +++ b/csharp/src/Ice/ObjectAdapterFactory.cs @@ -9,10 +9,7 @@ namespace IceInternal { - - using System.Collections; using System.Collections.Generic; - using System.Diagnostics; public sealed class ObjectAdapterFactory { @@ -25,16 +22,16 @@ namespace IceInternal // Ignore shutdown requests if the object adapter factory has // already been shut down. // - if(instance_ == null) + if(_instance == null) { return; } adapters = new List<Ice.ObjectAdapterI>(_adapters); - - instance_ = null; + + _instance = null; _communicator = null; - + System.Threading.Monitor.PulseAll(this); } @@ -47,7 +44,7 @@ namespace IceInternal adapter.deactivate(); } } - + public void waitForShutdown() { List<Ice.ObjectAdapterI> adapters; @@ -56,11 +53,11 @@ namespace IceInternal // // First we wait for the shutdown of the factory itself. // - while(instance_ != null) + while(_instance != null) { System.Threading.Monitor.Wait(this); } - + adapters = new List<Ice.ObjectAdapterI>(_adapters); } @@ -77,7 +74,7 @@ namespace IceInternal { lock(this) { - return instance_ == null; + return _instance == null; } } @@ -113,13 +110,13 @@ namespace IceInternal { adapters = new List<Ice.ObjectAdapterI>(_adapters); } - + foreach(Ice.ObjectAdapterI adapter in adapters) { adapter.updateConnectionObservers(); } } - + public void updateThreadObservers() { @@ -128,27 +125,27 @@ namespace IceInternal { adapters = new List<Ice.ObjectAdapterI>(_adapters); } - + foreach(Ice.ObjectAdapterI adapter in adapters) { adapter.updateThreadObservers(); } } - + public Ice.ObjectAdapter createObjectAdapter(string name, Ice.RouterPrx router) { lock(this) { - if(instance_ == null) + if(_instance == null) { throw new Ice.CommunicatorDestroyedException(); } - + Ice.ObjectAdapterI adapter = null; if(name.Length == 0) { string uuid = System.Guid.NewGuid().ToString(); - adapter = new Ice.ObjectAdapterI(instance_, _communicator, this, uuid, null, true); + adapter = new Ice.ObjectAdapterI(_instance, _communicator, this, uuid, null, true); } else { @@ -159,27 +156,27 @@ namespace IceInternal ex.id = name; throw ex; } - adapter = new Ice.ObjectAdapterI(instance_, _communicator, this, name, router, false); + adapter = new Ice.ObjectAdapterI(_instance, _communicator, this, name, router, false); _adapterNamesInUse.Add(name); } _adapters.Add(adapter); return adapter; } } - + public Ice.ObjectAdapter findObjectAdapter(Ice.ObjectPrx proxy) { List<Ice.ObjectAdapterI> adapters; lock(this) { - if(instance_ == null) + if(_instance == null) { return null; } - + adapters = new List<Ice.ObjectAdapterI>(_adapters); } - + foreach(Ice.ObjectAdapterI adapter in adapters) { try @@ -202,7 +199,7 @@ namespace IceInternal { lock(this) { - if(instance_ == null) + if(_instance == null) { return; } @@ -212,7 +209,7 @@ namespace IceInternal } } - public void flushAsyncBatchRequests(CommunicatorFlushBatch outAsync) + public void flushAsyncBatchRequests(Ice.CompressBatch compressBatch, CommunicatorFlushBatchAsync outAsync) { List<Ice.ObjectAdapterI> adapters; lock(this) @@ -222,22 +219,22 @@ namespace IceInternal foreach(Ice.ObjectAdapterI adapter in adapters) { - adapter.flushAsyncBatchRequests(outAsync); + adapter.flushAsyncBatchRequests(compressBatch, outAsync); } } - + // // Only for use by Instance. // internal ObjectAdapterFactory(Instance instance, Ice.Communicator communicator) { - instance_ = instance; + _instance = instance; _communicator = communicator; _adapterNamesInUse = new HashSet<string>(); _adapters = new List<Ice.ObjectAdapterI>(); } - - private Instance instance_; + + private Instance _instance; private Ice.Communicator _communicator; private HashSet<string> _adapterNamesInUse; private List<Ice.ObjectAdapterI> _adapters; diff --git a/csharp/src/Ice/ObjectAdapterI.cs b/csharp/src/Ice/ObjectAdapterI.cs index 611a677adcf..a0f75b109ab 100644 --- a/csharp/src/Ice/ObjectAdapterI.cs +++ b/csharp/src/Ice/ObjectAdapterI.cs @@ -10,7 +10,6 @@ namespace Ice { using System; - using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; @@ -45,7 +44,7 @@ namespace Ice // If we've previously been initialized we just need to activate the // incoming connection factories and we're done. // - if(state_ != StateUninitialized) + if(_state != StateUninitialized) { foreach(IncomingConnectionFactory icf in _incomingConnectionFactories) { @@ -61,23 +60,23 @@ namespace Ice // deactivation from other threads while these one off // initializations are done. // - state_ = StateActivating; + _state = StateActivating; locatorInfo = _locatorInfo; if(!_noConfig) { - Properties properties = instance_.initializationData().properties; + Properties properties = _instance.initializationData().properties; printAdapterReady = properties.getPropertyAsInt("Ice.PrintAdapterReady") > 0; } } try { - Ice.Identity dummy = new Ice.Identity(); + Identity dummy = new Identity(); dummy.name = "dummy"; updateLocatorRegistry(locatorInfo, createDirectProxy(dummy)); } - catch(Ice.LocalException) + catch(LocalException) { // // If we couldn't update the locator registry, we let the @@ -87,7 +86,7 @@ namespace Ice // lock(this) { - state_ = StateUninitialized; + _state = StateUninitialized; System.Threading.Monitor.PulseAll(this); } throw; @@ -95,19 +94,19 @@ namespace Ice if(printAdapterReady) { - System.Console.Out.WriteLine(_name + " ready"); + Console.Out.WriteLine(_name + " ready"); } lock(this) { - Debug.Assert(state_ == StateActivating); + Debug.Assert(_state == StateActivating); foreach(IncomingConnectionFactory icf in _incomingConnectionFactories) { icf.activate(); } - state_ = StateActive; + _state = StateActive; System.Threading.Monitor.PulseAll(this); } } @@ -117,7 +116,7 @@ namespace Ice lock(this) { checkForDeactivation(); - state_ = StateHeld; + _state = StateHeld; foreach(IncomingConnectionFactory factory in _incomingConnectionFactories) { factory.hold(); @@ -150,15 +149,15 @@ namespace Ice // Wait for activation to complete. This is necessary to not // get out of order locator updates. // - while(state_ == StateActivating || state_ == StateDeactivating) + while(_state == StateActivating || _state == StateDeactivating) { System.Threading.Monitor.Wait(this); } - if(state_ > StateDeactivating) + if(_state > StateDeactivating) { return; } - state_ = StateDeactivating; + _state = StateDeactivating; } // @@ -171,7 +170,7 @@ namespace Ice // // Remove entry from the router manager. // - instance_.routerManager().erase(_routerInfo.getRouter()); + _instance.routerManager().erase(_routerInfo.getRouter()); // // Clear this object adapter with the router. @@ -183,7 +182,7 @@ namespace Ice { updateLocatorRegistry(_locatorInfo, null); } - catch(Ice.LocalException) + catch(LocalException) { // // We can't throw exceptions in deactivate so we ignore @@ -206,12 +205,12 @@ namespace Ice // changing the object adapter might block if there are still // requests being dispatched. // - instance_.outgoingConnectionFactory().removeAdapter(this); + _instance.outgoingConnectionFactory().removeAdapter(this); lock(this) { - Debug.Assert(state_ == StateDeactivating); - state_ = StateDeactivated; + Debug.Assert(_state == StateDeactivating); + _state = StateDeactivated; System.Threading.Monitor.PulseAll(this); } } @@ -226,11 +225,11 @@ namespace Ice // for the return of all direct method calls using this // adapter. // - while((state_ < StateDeactivated) || _directCount > 0) + while((_state < StateDeactivated) || _directCount > 0) { System.Threading.Monitor.Wait(this); } - if(state_ > StateDeactivated) + if(_state > StateDeactivated) { return; } @@ -252,7 +251,7 @@ namespace Ice { lock(this) { - return state_ >= StateDeactivated; + return _state >= StateDeactivated; } } @@ -271,15 +270,15 @@ namespace Ice // adapter. Other threads wait for the destruction to be // completed. // - while(state_ == StateDestroying) + while(_state == StateDestroying) { System.Threading.Monitor.Wait(this); } - if(state_ == StateDestroyed) + if(_state == StateDestroyed) { return; } - state_ = StateDestroying; + _state = StateDestroying; } // @@ -313,7 +312,7 @@ namespace Ice // // Remove object references (some of them cyclic). // - instance_ = null; + _instance = null; _threadPool = null; _routerEndpoints = null; _routerInfo = null; @@ -322,17 +321,17 @@ namespace Ice _reference = null; _objectAdapterFactory = null; - state_ = StateDestroyed; + _state = StateDestroyed; System.Threading.Monitor.PulseAll(this); } } - public ObjectPrx add(Ice.Object obj, Identity ident) + public ObjectPrx add(Object obj, Identity ident) { return addFacet(obj, ident, ""); } - public ObjectPrx addFacet(Ice.Object obj, Identity ident, string facet) + public ObjectPrx addFacet(Object obj, Identity ident, string facet) { lock(this) { @@ -354,12 +353,12 @@ namespace Ice } } - public ObjectPrx addWithUUID(Ice.Object obj) + public ObjectPrx addWithUUID(Object obj) { return addFacetWithUUID(obj, ""); } - public ObjectPrx addFacetWithUUID(Ice.Object obj, string facet) + public ObjectPrx addFacetWithUUID(Object obj, string facet) { Identity ident = new Identity(); ident.category = ""; @@ -380,12 +379,12 @@ namespace Ice } } - public Ice.Object remove(Identity ident) + public Object remove(Identity ident) { return removeFacet(ident, ""); } - public Ice.Object removeFacet(Identity ident, string facet) + public Object removeFacet(Identity ident, string facet) { lock(this) { @@ -396,7 +395,7 @@ namespace Ice } } - public Dictionary<string, Ice.Object> removeAllFacets(Identity ident) + public Dictionary<string, Object> removeAllFacets(Identity ident) { lock(this) { @@ -407,7 +406,7 @@ namespace Ice } } - public Ice.Object removeDefaultServant(string category) + public Object removeDefaultServant(string category) { lock(this) { @@ -417,12 +416,12 @@ namespace Ice } } - public Ice.Object find(Identity ident) + public Object find(Identity ident) { return findFacet(ident, ""); } - public Ice.Object findFacet(Identity ident, string facet) + public Object findFacet(Identity ident, string facet) { lock(this) { @@ -433,7 +432,7 @@ namespace Ice } } - public Dictionary<string, Ice.Object> findAllFacets(Identity ident) + public Dictionary<string, Object> findAllFacets(Identity ident) { lock(this) { @@ -444,18 +443,18 @@ namespace Ice } } - public Ice.Object findByProxy(ObjectPrx proxy) + public Object findByProxy(ObjectPrx proxy) { lock(this) { checkForDeactivation(); - Reference @ref = ((ObjectPrxHelperBase)proxy).reference__(); + Reference @ref = ((ObjectPrxHelperBase)proxy).iceReference(); return findFacet(@ref.getIdentity(), @ref.getFacet()); } } - public Ice.Object findDefaultServant(string category) + public Object findDefaultServant(string category) { lock(this) { @@ -534,7 +533,7 @@ namespace Ice { checkForDeactivation(); - _locatorInfo = instance_.locatorManager().get(locator); + _locatorInfo = _instance.locatorManager().get(locator); } } @@ -555,6 +554,19 @@ namespace Ice } } + public Endpoint[] getEndpoints() + { + lock(this) + { + List<Endpoint> endpoints = new List<Endpoint>(); + foreach(IncomingConnectionFactory factory in _incomingConnectionFactories) + { + endpoints.Add(factory.endpoint()); + } + return endpoints.ToArray(); + } + } + public void refreshPublishedEndpoints() { LocatorInfo locatorInfo = null; @@ -572,11 +584,11 @@ namespace Ice try { - Ice.Identity dummy = new Ice.Identity(); + Identity dummy = new Identity(); dummy.name = "dummy"; updateLocatorRegistry(locatorInfo, createDirectProxy(dummy)); } - catch(Ice.LocalException) + catch(LocalException) { lock(this) { @@ -589,24 +601,52 @@ namespace Ice } } - public Endpoint[] getEndpoints() + public Endpoint[] getPublishedEndpoints() { lock(this) { - List<Endpoint> endpoints = new List<Endpoint>(); - foreach(IncomingConnectionFactory factory in _incomingConnectionFactories) - { - endpoints.Add(factory.endpoint()); - } - return endpoints.ToArray(); + return _publishedEndpoints.ToArray(); } } - public Endpoint[] getPublishedEndpoints() + public void setPublishedEndpoints(Endpoint[] newEndpoints) { + List<EndpointI> newPublishedEndpoints = new List<EndpointI>(newEndpoints.Length); + + foreach(Endpoint e in newEndpoints) + { + newPublishedEndpoints.Add((EndpointI)e); + } + + LocatorInfo locatorInfo = null; + List<EndpointI> oldPublishedEndpoints; + lock(this) { - return _publishedEndpoints.ToArray(); + checkForDeactivation(); + + oldPublishedEndpoints = _publishedEndpoints; + _publishedEndpoints = newPublishedEndpoints; + + locatorInfo = _locatorInfo; + } + + try + { + Identity dummy = new Identity(); + dummy.name = "dummy"; + updateLocatorRegistry(locatorInfo, createDirectProxy(dummy)); + } + catch(LocalException) + { + lock(this) + { + // + // Restore the old published endpoints. + // + _publishedEndpoints = oldPublishedEndpoints; + throw; + } } } @@ -617,7 +657,7 @@ namespace Ice // it can be called for AMI invocations if the proxy has no delegate set yet. // - Reference r = ((ObjectPrxHelperBase)proxy).reference__(); + Reference r = ((ObjectPrxHelperBase)proxy).iceReference(); if(r.isWellKnown()) { // @@ -689,7 +729,7 @@ namespace Ice } } - public void flushAsyncBatchRequests(CommunicatorFlushBatch outAsync) + public void flushAsyncBatchRequests(Ice.CompressBatch compressBatch, CommunicatorFlushBatchAsync outAsync) { List<IncomingConnectionFactory> f; lock(this) @@ -699,7 +739,7 @@ namespace Ice foreach(IncomingConnectionFactory factory in f) { - factory.flushAsyncBatchRequests(outAsync); + factory.flushAsyncBatchRequests(compressBatch, outAsync); } } @@ -748,7 +788,7 @@ namespace Ice { // Not check for deactivation here! - Debug.Assert(instance_ != null); // Must not be called after destroy(). + Debug.Assert(_instance != null); // Must not be called after destroy(). Debug.Assert(_directCount > 0); if(--_directCount == 0) @@ -760,13 +800,13 @@ namespace Ice public ThreadPool getThreadPool() { - // No mutex lock necessary, _threadPool and instance_ are + // No mutex lock necessary, _threadPool and _instance are // immutable after creation until they are removed in // destroy(). // Not check for deactivation here! - Debug.Assert(instance_ != null); // Must not be called after destroy(). + Debug.Assert(_instance != null); // Must not be called after destroy(). if(_threadPool != null) { @@ -774,7 +814,7 @@ namespace Ice } else { - return instance_.serverThreadPool(); + return _instance.serverThreadPool(); } } @@ -791,7 +831,7 @@ namespace Ice { // Not check for deactivation here! - Debug.Assert(instance_ != null); // Must not be called after destroy(). + Debug.Assert(_instance != null); // Must not be called after destroy(). return _acm; } @@ -808,7 +848,7 @@ namespace Ice ObjectAdapterFactory objectAdapterFactory, string name, RouterPrx router, bool noConfig) { - instance_ = instance; + _instance = instance; _communicator = communicator; _objectAdapterFactory = objectAdapterFactory; _servantManager = new ServantManager(instance, name); @@ -824,12 +864,12 @@ namespace Ice { _id = ""; _replicaGroupId = ""; - _reference = instance_.referenceFactory().create("dummy -t", ""); - _acm = instance_.serverACM(); + _reference = _instance.referenceFactory().create("dummy -t", ""); + _acm = _instance.serverACM(); return; } - Properties properties = instance_.initializationData().properties; + Properties properties = _instance.initializationData().properties; List<string> unknownProps = new List<string>(); bool noProps = filterProperties(unknownProps); @@ -846,7 +886,7 @@ namespace Ice message.Append("\n "); message.Append(s); } - instance_.initializationData().logger.warning(message.ToString()); + _instance.initializationData().logger.warning(message.ToString()); } // @@ -857,8 +897,8 @@ namespace Ice // // These need to be set to prevent warnings/asserts in the destructor. // - state_ = StateDestroyed; - instance_ = null; + _state = StateDestroyed; + _instance = null; _incomingConnectionFactories = null; InitializationException ex = new InitializationException(); @@ -876,7 +916,7 @@ namespace Ice string proxyOptions = properties.getPropertyWithDefault(_name + ".ProxyOptions", "-t"); try { - _reference = instance_.referenceFactory().create("dummy " + proxyOptions, ""); + _reference = _instance.referenceFactory().create("dummy " + proxyOptions, ""); } catch(ProxyParseException) { @@ -885,7 +925,7 @@ namespace Ice throw ex; } - _acm = new ACMConfig(properties, communicator.getLogger(), _name + ".ACM", instance_.serverACM()); + _acm = new ACMConfig(properties, communicator.getLogger(), _name + ".ACM", _instance.serverACM()); { int defaultMessageSizeMax = instance.messageSizeMax() / 1024; @@ -906,17 +946,17 @@ namespace Ice int threadPoolSizeMax = properties.getPropertyAsInt(_name + ".ThreadPool.SizeMax"); if(threadPoolSize > 0 || threadPoolSizeMax > 0) { - _threadPool = new ThreadPool(instance_, _name + ".ThreadPool", 0); + _threadPool = new ThreadPool(_instance, _name + ".ThreadPool", 0); } if(router == null) { router = RouterPrxHelper.uncheckedCast( - instance_.proxyFactory().propertyToProxy(_name + ".Router")); + _instance.proxyFactory().propertyToProxy(_name + ".Router")); } if(router != null) { - _routerInfo = instance_.routerManager().get(router); + _routerInfo = _instance.routerManager().get(router); if(_routerInfo != null) { // @@ -924,9 +964,9 @@ namespace Ice // if(_routerInfo.getAdapter() != null) { - Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); + AlreadyRegisteredException ex = new AlreadyRegisteredException(); ex.kindOfObject = "object adapter with router"; - ex.id = instance_.identityToString(router.ice_getIdentity()); + ex.id = Util.identityToString(router.ice_getIdentity(), _instance.toStringMode()); throw ex; } @@ -970,7 +1010,7 @@ namespace Ice // router's client proxy to use this object adapter for // callbacks. // - instance_.outgoingConnectionFactory().setRouterInfo(_routerInfo); + _instance.outgoingConnectionFactory().setRouterInfo(_routerInfo); } } else @@ -987,10 +1027,10 @@ namespace Ice } if(endpoints.Count == 0) { - TraceLevels tl = instance_.traceLevels(); + TraceLevels tl = _instance.traceLevels(); if(tl.network >= 2) { - instance_.initializationData().logger.trace(tl.networkCat, "created adapter `" + _name + + _instance.initializationData().logger.trace(tl.networkCat, "created adapter `" + _name + "' without endpoints"); } } @@ -1004,11 +1044,11 @@ namespace Ice if(properties.getProperty(_name + ".Locator").Length > 0) { setLocator(LocatorPrxHelper.uncheckedCast( - instance_.proxyFactory().propertyToProxy(_name + ".Locator"))); + _instance.proxyFactory().propertyToProxy(_name + ".Locator"))); } else { - setLocator(instance_.referenceFactory().getDefaultLocator()); + setLocator(_instance.referenceFactory().getDefaultLocator()); } } catch(LocalException) @@ -1018,36 +1058,6 @@ namespace Ice } } - /* - ~ObjectAdapterI() - { - if(!_deactivated) - { - string msg = "object adapter `" + getName() + "' has not been deactivated"; - if(!Environment.HasShutdownStarted) - { - instance_.initializationData().logger.warning(msg); - } - else - { - Console.Error.WriteLine(msg); - } - } - else if(!_destroyed) - { - string msg = "object adapter `" + getName() + "' has not been destroyed"; - if(!Environment.HasShutdownStarted) - { - instance_.initializationData().logger.warning(msg); - } - else - { - Console.Error.WriteLine(msg); - } - } - } - */ - private ObjectPrx newProxy(Identity ident, string facet) { if(_id.Length == 0) @@ -1092,8 +1102,8 @@ namespace Ice // // Create a reference and return a proxy for this reference. // - Reference reference = instance_.referenceFactory().create(ident, facet, _reference, endpoints); - return instance_.proxyFactory().referenceToProxy(reference); + Reference reference = _instance.referenceFactory().create(ident, facet, _reference, endpoints); + return _instance.proxyFactory().referenceToProxy(reference); } private ObjectPrx newIndirectProxy(Identity ident, string facet, string id) @@ -1102,13 +1112,13 @@ namespace Ice // Create a reference with the adapter id and return a // proxy for the reference. // - Reference reference = instance_.referenceFactory().create(ident, facet, _reference, id); - return instance_.proxyFactory().referenceToProxy(reference); + Reference reference = _instance.referenceFactory().create(ident, facet, _reference, id); + return _instance.proxyFactory().referenceToProxy(reference); } private void checkForDeactivation() { - if(state_ >= StateDeactivating) + if(_state >= StateDeactivating) { ObjectAdapterDeactivatedException ex = new ObjectAdapterDeactivatedException(); ex.name = getName(); @@ -1128,7 +1138,7 @@ namespace Ice } } - private static void checkServant(Ice.Object servant) + private static void checkServant(Object servant) { if(servant == null) { @@ -1149,13 +1159,17 @@ namespace Ice beg = IceUtilInternal.StringUtil.findFirstNotOf(endpts, delim, end); if(beg == -1) { + if(endpoints.Count != 0) + { + throw new EndpointParseException("invalid empty object adapter endpoint"); + } break; } end = beg; while(true) { - end = endpts.IndexOf((System.Char) ':', end); + end = endpts.IndexOf(':', end); if(end == -1) { end = endpts.Length; @@ -1167,14 +1181,14 @@ namespace Ice int quote = beg; while(true) { - quote = endpts.IndexOf((System.Char) '\"', quote); + quote = endpts.IndexOf('\"', quote); if(quote == -1 || end < quote) { break; } else { - quote = endpts.IndexOf((System.Char) '\"', ++quote); + quote = endpts.IndexOf('\"', ++quote); if(quote == -1) { break; @@ -1197,36 +1211,14 @@ namespace Ice if(end == beg) { - ++end; - continue; + throw new EndpointParseException("invalid empty object adapter endpoint"); } string s = endpts.Substring(beg, (end) - (beg)); - EndpointI endp = instance_.endpointFactoryManager().create(s, oaEndpoints); + EndpointI endp = _instance.endpointFactoryManager().create(s, oaEndpoints); if(endp == null) { -#if COMPACT - if(s.StartsWith("ssl", StringComparison.Ordinal) || s.StartsWith("wss", StringComparison.Ordinal)) - { - instance_.initializationData().logger.warning( - "ignoring endpoint `" + s + - "': IceSSL is not supported with the .NET Compact Framework"); - ++end; - continue; - } -#else - if(AssemblyUtil.runtime_ == AssemblyUtil.Runtime.Mono && - (s.StartsWith("ssl", StringComparison.Ordinal) || s.StartsWith("wss", StringComparison.Ordinal))) - { - instance_.initializationData().logger.warning( - "ignoring endpoint `" + s + "': IceSSL is not supported with Mono"); - ++end; - continue; - } -#endif - Ice.EndpointParseException e2 = new Ice.EndpointParseException(); - e2.str = "invalid object adapter endpoint `" + s + "'"; - throw e2; + throw new EndpointParseException("invalid object adapter endpoint `" + s + "'"); } endpoints.Add(endp); @@ -1242,7 +1234,7 @@ namespace Ice // Parse published endpoints. If set, these are used in proxies // instead of the connection factory endpoints. // - string endpts = instance_.initializationData().properties.getProperty(_name + ".PublishedEndpoints"); + string endpts = _instance.initializationData().properties.getProperty(_name + ".PublishedEndpoints"); List<EndpointI> endpoints = parseEndpoints(endpts, false); if(endpoints.Count == 0) { @@ -1257,7 +1249,7 @@ namespace Ice } } - if(instance_.traceLevels().network >= 1 && endpoints.Count > 0) + if(_instance.traceLevels().network >= 1 && endpoints.Count > 0) { StringBuilder s = new StringBuilder("published endpoints for object adapter `"); s.Append(_name); @@ -1272,7 +1264,7 @@ namespace Ice s.Append(endpoint.ToString()); first = false; } - instance_.initializationData().logger.trace(instance_.traceLevels().networkCat, s.ToString()); + _instance.initializationData().logger.trace(_instance.traceLevels().networkCat, s.ToString()); } return endpoints; } @@ -1307,12 +1299,12 @@ namespace Ice } catch(AdapterNotFoundException) { - if(instance_.traceLevels().location >= 1) + if(_instance.traceLevels().location >= 1) { - System.Text.StringBuilder s = new System.Text.StringBuilder(); + StringBuilder s = new StringBuilder(); s.Append("couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n"); s.Append("the object adapter is not known to the locator registry"); - instance_.initializationData().logger.trace(instance_.traceLevels().locationCat, s.ToString()); + _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.ToString()); } NotRegisteredException ex1 = new NotRegisteredException(); @@ -1322,12 +1314,12 @@ namespace Ice } catch(InvalidReplicaGroupIdException) { - if(instance_.traceLevels().location >= 1) + if(_instance.traceLevels().location >= 1) { - System.Text.StringBuilder s = new System.Text.StringBuilder(); + StringBuilder s = new StringBuilder(); s.Append("couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n"); s.Append("the replica group `" + _replicaGroupId + "' is not known to the locator registry"); - instance_.initializationData().logger.trace(instance_.traceLevels().locationCat, s.ToString()); + _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.ToString()); } NotRegisteredException ex1 = new NotRegisteredException(); @@ -1337,12 +1329,12 @@ namespace Ice } catch(AdapterAlreadyActiveException) { - if(instance_.traceLevels().location >= 1) + if(_instance.traceLevels().location >= 1) { - System.Text.StringBuilder s = new System.Text.StringBuilder(); + StringBuilder s = new StringBuilder(); s.Append("couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n"); s.Append("the object adapter endpoints are already set"); - instance_.initializationData().logger.trace(instance_.traceLevels().locationCat, s.ToString()); + _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.ToString()); } ObjectAdapterIdInUseException ex1 = new ObjectAdapterIdInUseException(); @@ -1359,24 +1351,24 @@ namespace Ice } catch(LocalException e) { - if(instance_.traceLevels().location >= 1) + if(_instance.traceLevels().location >= 1) { - System.Text.StringBuilder s = new System.Text.StringBuilder(); + StringBuilder s = new StringBuilder(); s.Append("couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n"); s.Append(e.ToString()); - instance_.initializationData().logger.trace(instance_.traceLevels().locationCat, s.ToString()); + _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.ToString()); } throw; // TODO: Shall we raise a special exception instead of a non obvious local exception? } - if(instance_.traceLevels().location >= 1) + if(_instance.traceLevels().location >= 1) { - System.Text.StringBuilder s = new System.Text.StringBuilder(); + StringBuilder s = new StringBuilder(); s.Append("updated object adapter `" + _id + "' endpoints with the locator registry\n"); s.Append("endpoints = "); if(proxy != null) { - Ice.Endpoint[] endpoints = proxy.ice_getEndpoints(); + Endpoint[] endpoints = proxy.ice_getEndpoints(); for(int i = 0; i < endpoints.Length; i++) { s.Append(endpoints[i].ToString()); @@ -1386,7 +1378,7 @@ namespace Ice } } } - instance_.initializationData().logger.trace(instance_.traceLevels().locationCat, s.ToString()); + _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.ToString()); } } @@ -1437,7 +1429,7 @@ namespace Ice // Do not create unknown properties list if Ice prefix, ie Ice, Glacier2, etc // bool addUnknown = true; - String prefix = _name + "."; + string prefix = _name + "."; for(int i = 0; PropertyNames.clPropNames[i] != null; ++i) { if(prefix.StartsWith(PropertyNames.clPropNames[i] + ".", StringComparison.Ordinal)) @@ -1449,8 +1441,8 @@ namespace Ice bool noProps = true; Dictionary<string, string> props = - instance_.initializationData().properties.getPropertiesForPrefix(prefix); - foreach(String prop in props.Keys) + _instance.initializationData().properties.getPropertiesForPrefix(prefix); + foreach(string prop in props.Keys) { bool valid = false; for(int i = 0; i < _suffixes.Length; ++i) @@ -1481,8 +1473,8 @@ namespace Ice private const int StateDestroying = 6; private const int StateDestroyed = 7; - private int state_ = StateUninitialized; - private Instance instance_; + private int _state = StateUninitialized; + private Instance _instance; private Communicator _communicator; private ObjectAdapterFactory _objectAdapterFactory; private ThreadPool _threadPool; diff --git a/csharp/src/Ice/ObjectFactoryManager.cs b/csharp/src/Ice/ObjectFactoryManager.cs deleted file mode 100644 index daf55ccf113..00000000000 --- a/csharp/src/Ice/ObjectFactoryManager.cs +++ /dev/null @@ -1,86 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -namespace IceInternal -{ - - using System.Collections.Generic; - - public sealed class ObjectFactoryManager - { - public void add(Ice.ObjectFactory factory, string id) - { - lock(this) - { - if(_factoryMap.ContainsKey(id)) - { - Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); - ex.id = id; - ex.kindOfObject = "object factory"; - throw ex; - } - _factoryMap[id] = factory; - } - } - - public void remove(string id) - { - object o = null; - lock(this) - { - if(!_factoryMap.ContainsKey(id)) - { - Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); - ex.id = id; - ex.kindOfObject = "object factory"; - throw ex; - } - _factoryMap.Remove(id); - } - ((Ice.ObjectFactory)o).destroy(); - } - - public Ice.ObjectFactory find(string id) - { - lock(this) - { - Ice.ObjectFactory factory = null; - _factoryMap.TryGetValue(id, out factory); - return factory; - } - } - - // - // Only for use by Instance - // - internal ObjectFactoryManager() - { - _factoryMap = new Dictionary<string, Ice.ObjectFactory>(); - } - - internal void destroy() - { - Dictionary<string, Ice.ObjectFactory> oldMap = null; - - lock(this) - { - oldMap = _factoryMap; - _factoryMap = new Dictionary<string, Ice.ObjectFactory>(); - } - - foreach(Ice.ObjectFactory factory in oldMap.Values) - { - factory.destroy(); - } - } - - private Dictionary<string, Ice.ObjectFactory> _factoryMap; - } - -} diff --git a/csharp/src/Ice/ObserverHelper.cs b/csharp/src/Ice/ObserverHelper.cs index dc51d875c3e..5ca670606c7 100644 --- a/csharp/src/Ice/ObserverHelper.cs +++ b/csharp/src/Ice/ObserverHelper.cs @@ -37,7 +37,7 @@ namespace IceInternal static public InvocationObserver get(Ice.ObjectPrx proxy, string op, Dictionary<string, string> context) { CommunicatorObserver obsv = - ((Ice.ObjectPrxHelperBase)proxy).reference__().getInstance().initializationData().observer; + ((Ice.ObjectPrxHelperBase)proxy).iceReference().getInstance().initializationData().observer; if(obsv != null) { InvocationObserver observer; diff --git a/csharp/src/Ice/OpaqueEndpointI.cs b/csharp/src/Ice/OpaqueEndpointI.cs index 0381986f6e1..2421d75c68c 100644 --- a/csharp/src/Ice/OpaqueEndpointI.cs +++ b/csharp/src/Ice/OpaqueEndpointI.cs @@ -9,10 +9,9 @@ namespace IceInternal { - - using System.Collections; using System.Collections.Generic; using System.Globalization; + using System.Diagnostics; sealed class OpaqueEndpointI : EndpointI { @@ -36,11 +35,11 @@ namespace IceInternal calcHashValue(); } - public OpaqueEndpointI(short type, BasicStream s) + public OpaqueEndpointI(short type, Ice.InputStream s) { _type = type; - _rawEncoding = s.getReadEncoding(); - int sz = s.getReadEncapsSize(); + _rawEncoding = s.getEncoding(); + int sz = s.getEncapsulationSize(); _rawBytes = new byte[sz]; s.readBlob(_rawBytes); @@ -50,11 +49,16 @@ namespace IceInternal // // Marshal the endpoint // - public override void streamWrite(BasicStream s) + public override void streamWrite(Ice.OutputStream s) { - s.startWriteEncaps(_rawEncoding, Ice.FormatType.DefaultFormat); + s.startEncapsulation(_rawEncoding, Ice.FormatType.DefaultFormat); s.writeBlob(_rawBytes); - s.endWriteEncaps(); + s.endEncapsulation(); + } + + public override void streamWriteImpl(Ice.OutputStream s) + { + Debug.Assert(false); } // @@ -62,14 +66,14 @@ namespace IceInternal // public override string ice_toString_() { - string val = IceUtilInternal.Base64.encode(_rawBytes); + string val = System.Convert.ToBase64String(_rawBytes); return "opaque -t " + _type + " -e " + Ice.Util.encodingVersionToString(_rawEncoding) + " -v " + val; } private sealed class InfoI : Ice.OpaqueEndpointInfo { public InfoI(short type, Ice.EncodingVersion rawEncoding, byte[] rawBytes) : - base(-1, false, rawEncoding, rawBytes) + base(null, -1, false, rawEncoding, rawBytes) { _type = type; } @@ -253,7 +257,7 @@ namespace IceInternal s += " -e " + Ice.Util.encodingVersionToString(_rawEncoding); if(_rawBytes.Length > 0) { - s += " -v " + IceUtilInternal.Base64.encode(_rawBytes); + s += " -v " + System.Convert.ToBase64String(_rawBytes); } return s; } @@ -371,16 +375,16 @@ namespace IceInternal throw new Ice.EndpointParseException("no argument provided for -v option in endpoint " + endpoint); } - for(int j = 0; j < argument.Length; ++j) + + try + { + _rawBytes = System.Convert.FromBase64String(argument); + } + catch(System.FormatException ex) { - if(!IceUtilInternal.Base64.isBase64(argument[j])) - { - throw new Ice.EndpointParseException("invalid base64 character `" + argument[j] + - "' (ordinal " + ((int)argument[j]) + - ") in endpoint " + endpoint); - } + throw new Ice.EndpointParseException("Invalid Base64 input in endpoint " + endpoint, ex); } - _rawBytes = IceUtilInternal.Base64.decode(argument); + return true; } @@ -413,9 +417,9 @@ namespace IceInternal private void calcHashValue() { int h = 5381; - IceInternal.HashUtil.hashAdd(ref h, _type); - IceInternal.HashUtil.hashAdd(ref h, _rawEncoding); - IceInternal.HashUtil.hashAdd(ref h, _rawBytes); + HashUtil.hashAdd(ref h, _type); + HashUtil.hashAdd(ref h, _rawEncoding); + HashUtil.hashAdd(ref h, _rawBytes); _hashCode = h; } diff --git a/csharp/src/Ice/Optional.cs b/csharp/src/Ice/Optional.cs index 665e3fd12cb..1fbfb09ea48 100644 --- a/csharp/src/Ice/Optional.cs +++ b/csharp/src/Ice/Optional.cs @@ -20,12 +20,8 @@ namespace Ice /// <summary> /// Encapsulates an optional value. Instances of this type are immutable. /// </summary> -#if SILVERLIGHT - public struct Optional<T> -#else [Serializable] public struct Optional<T> : ISerializable -#endif { /// <summary> /// Creates an optional value whose state is unset. @@ -54,7 +50,6 @@ namespace Ice _isSet = v._isSet; } -#if !SILVERLIGHT /// <summary> /// Initializes a new instance of the exception with serialized data. /// </summary> @@ -72,7 +67,6 @@ namespace Ice _value = default(T); } } -#endif /// <summary> /// Conversion operator to the underlying type; a cast is required. An exception @@ -112,7 +106,7 @@ namespace Ice { if(!_isSet) { - throw new System.InvalidOperationException(); + throw new InvalidOperationException(); } return _value; } @@ -132,7 +126,7 @@ namespace Ice public override bool Equals(object other) { - if(object.ReferenceEquals(this, other)) + if(ReferenceEquals(this, other)) { return true; } @@ -175,7 +169,6 @@ namespace Ice } } -#if !SILVERLIGHT /// <summary> /// Serializes an optional value. /// </summary> @@ -189,7 +182,6 @@ namespace Ice info.AddValue("value", _value, typeof(T)); } } -#endif private T _value; private bool _isSet; @@ -198,23 +190,22 @@ namespace Ice /// <summary> /// Handles callbacks for an optional object parameter. /// </summary> - public class OptionalPatcher<T> : IceInternal.Patcher - where T : Ice.Object + public class OptionalPatcher<T> where T : Ice.Value { /// <summary> /// Instantiates the class with the given optional. /// </summary> /// <param name="type">The Slice type ID corresponding to the formal type.</param> - public OptionalPatcher(string type) : - base(type) + public OptionalPatcher(string type) { + _type = type; } /// <summary> /// Sets the Ice object of the optional to the passed instance. /// </summary> /// <param name="v">The new object for the optional.</param> - public override void patch(Ice.Object v) + public void patch(Ice.Value v) { if(v == null || typeof(T).IsAssignableFrom(v.GetType())) { @@ -227,11 +218,11 @@ namespace Ice // However, when v is null, the optional might be cleared, which // is not the result we want. // - this.value = new Optional<T>((T)v); + value = new Optional<T>((T)v); } else { - IceInternal.Ex.throwUOE(type(), v.ice_id()); + IceInternal.Ex.throwUOE(_type, v.ice_id()); } } @@ -239,6 +230,7 @@ namespace Ice /// The target optional. /// </summary> public Optional<T> value = new Optional<T>(); + private string _type; } /// <summary> diff --git a/csharp/src/Ice/Options.cs b/csharp/src/Ice/Options.cs index 0024027a1e5..0b4b42b18e6 100644 --- a/csharp/src/Ice/Options.cs +++ b/csharp/src/Ice/Options.cs @@ -7,6 +7,7 @@ // // ********************************************************************** +using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -15,7 +16,7 @@ namespace IceUtilInternal { public sealed class Options { - public sealed class BadQuote : System.Exception + public sealed class BadQuote : Exception { public BadQuote(string message) : base(message) { @@ -400,7 +401,7 @@ namespace IceUtilInternal } } - return (string[])vec.ToArray(); + return vec.ToArray(); } } } diff --git a/csharp/src/Ice/OutgoingAsync.cs b/csharp/src/Ice/OutgoingAsync.cs index b4f7ce683cc..45e42c02644 100644 --- a/csharp/src/Ice/OutgoingAsync.cs +++ b/csharp/src/Ice/OutgoingAsync.cs @@ -7,29 +7,180 @@ // // ********************************************************************** +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; + namespace IceInternal { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Threading; + public interface OutgoingAsyncCompletionCallback + { + void init(OutgoingAsyncBase og); + + bool handleSent(bool done, bool alreadySent); + bool handleException(Ice.Exception ex); + bool handleResponse(bool ok, OutgoingAsyncBase og); - public class OutgoingAsyncBase : AsyncResultI + void handleInvokeSent(bool sentSynchronously, OutgoingAsyncBase og); + void handleInvokeException(Ice.Exception ex, OutgoingAsyncBase og); + void handleInvokeResponse(bool ok, OutgoingAsyncBase og); + } + + public abstract class OutgoingAsyncBase { - public virtual Ice.AsyncCallback sent() + public virtual bool sent() + { + return sentImpl(true); + } + + public virtual bool exception(Ice.Exception ex) + { + return exceptionImpl(ex); + } + + public virtual bool response() { - return sent(true); + Debug.Assert(false); // Must be overriden by request that can handle responses + return false; } - public virtual Ice.AsyncCallback completed(Ice.Exception ex) + public void invokeSentAsync() { - return finished(ex); + // + // This is called when it's not safe to call the sent callback + // synchronously from this thread. Instead the exception callback + // is called asynchronously from the client thread pool. + // + try + { + instance_.clientThreadPool().dispatch(invokeSent, cachedConnection_); + } + catch(Ice.CommunicatorDestroyedException) + { + } } - public virtual Ice.AsyncCallback completed() + public void invokeExceptionAsync() { - Debug.Assert(false); // Must be implemented by classes that handle responses - return null; + // + // CommunicatorDestroyedCompleted is the only exception that can propagate directly + // from this method. + // + instance_.clientThreadPool().dispatch(invokeException, cachedConnection_); + } + + public void invokeResponseAsync() + { + // + // CommunicatorDestroyedCompleted is the only exception that can propagate directly + // from this method. + // + instance_.clientThreadPool().dispatch(invokeResponse, cachedConnection_); + } + + public void invokeSent() + { + try + { + _completionCallback.handleInvokeSent(sentSynchronously_, this); + } + catch(System.Exception ex) + { + warning(ex); + } + + if(observer_ != null && _doneInSent) + { + observer_.detach(); + observer_ = null; + } + } + public void invokeException() + { + try + { + try + { + throw _ex; + } + catch(Ice.Exception ex) + { + _completionCallback.handleInvokeException(ex, this); + } + } + catch(System.Exception ex) + { + warning(ex); + } + + if(observer_ != null) + { + observer_.detach(); + observer_ = null; + } + } + + public void invokeResponse() + { + if(_ex != null) + { + invokeException(); + return; + } + + try + { + try + { + _completionCallback.handleInvokeResponse((state_ & StateOK) != 0, this); + } + catch(Ice.Exception ex) + { + if(_completionCallback.handleException(ex)) + { + _completionCallback.handleInvokeException(ex, this); + } + } + catch(System.AggregateException ex) + { + throw ex.InnerException; + } + } + catch(System.Exception ex) + { + warning(ex); + } + + if(observer_ != null) + { + observer_.detach(); + observer_ = null; + } + } + + public virtual void cancelable(CancellationHandler handler) + { + lock(this) + { + if(_cancellationException != null) + { + try + { + throw _cancellationException; + } + catch(Ice.LocalException) + { + _cancellationException = null; + throw; + } + } + _cancellationHandler = handler; + } + } + public void cancel() + { + cancel(new Ice.InvocationCanceledException()); } public void attachRemoteObserver(Ice.ConnectionInfo info, Ice.Endpoint endpt, int requestId) @@ -58,54 +209,197 @@ namespace IceInternal } } - public IceInternal.BasicStream getOs() + public Ice.OutputStream getOs() { return os_; } - public virtual IceInternal.BasicStream getIs() + public Ice.InputStream getIs() { - return null; // Must be implemented by classes that handle responses + return is_; } - protected OutgoingAsyncBase(Ice.Communicator com, Instance instance, string op, object cookie) : - base(com, instance, op, cookie) + public virtual void cacheMessageBuffers() { - os_ = new BasicStream(instance, Ice.Util.currentProtocolEncoding); } - protected OutgoingAsyncBase(Ice.Communicator com, Instance instance, string op, object cookie, BasicStream os) : - base(com, instance, op, cookie) + public virtual void throwUserException() { - os_ = os; } - protected new Ice.AsyncCallback sent(bool done) + protected OutgoingAsyncBase(Instance instance, OutgoingAsyncCompletionCallback completionCallback, + Ice.OutputStream os = null, Ice.InputStream iss = null) { - if(done) + instance_ = instance; + sentSynchronously_ = false; + _doneInSent = false; + state_ = 0; + os_ = os ?? new Ice.OutputStream(instance, Ice.Util.currentProtocolEncoding); + is_ = iss ?? new Ice.InputStream(instance, Ice.Util.currentProtocolEncoding); + _completionCallback = completionCallback; + if(_completionCallback != null) + { + _completionCallback.init(this); + } + } + + protected virtual bool sentImpl(bool done) + { + lock(this) + { + bool alreadySent = (state_ & StateSent) > 0; + state_ |= StateSent; + if(done) + { + _doneInSent = true; + if(childObserver_ != null) + { + childObserver_.detach(); + childObserver_ = null; + } + _cancellationHandler = null; + + // + // For oneway requests after the data has been sent + // the buffers can be reused unless this is a + // collocated invocation. For collocated invocations + // the buffer won't be reused because it has already + // been marked as cached in invokeCollocated. + // + cacheMessageBuffers(); + } + + bool invoke = _completionCallback.handleSent(done, alreadySent); + if(!invoke && _doneInSent && observer_ != null) + { + observer_.detach(); + observer_ = null; + } + return invoke; + } + } + + protected virtual bool exceptionImpl(Ice.Exception ex) + { + lock(this) { + _ex = ex; if(childObserver_ != null) { + childObserver_.failed(ex.ice_id()); childObserver_.detach(); childObserver_ = null; } + _cancellationHandler = null; + + if(observer_ != null) + { + observer_.failed(ex.ice_id()); + } + bool invoke = _completionCallback.handleException(ex); + if(!invoke && observer_ != null) + { + observer_.detach(); + observer_ = null; + } + return invoke; + } + } + protected virtual bool responseImpl(bool ok) + { + lock(this) + { + if(ok) + { + state_ |= StateOK; + } + + _cancellationHandler = null; + + bool invoke; + try + { + invoke = _completionCallback.handleResponse(ok, this); + } + catch(Ice.Exception ex) + { + _ex = ex; + invoke = _completionCallback.handleException(ex); + } + if(!invoke && observer_ != null) + { + observer_.detach(); + observer_ = null; + } + return invoke; } - return base.sent(done); } - protected new Ice.AsyncCallback finished(Ice.Exception ex) + protected void cancel(Ice.LocalException ex) { - if(childObserver_ != null) + CancellationHandler handler; { - childObserver_.failed(ex.ice_name()); - childObserver_.detach(); - childObserver_ = null; + lock(this) + { + _cancellationException = ex; + if(_cancellationHandler == null) + { + return; + } + handler = _cancellationHandler; + } + } + handler.asyncRequestCanceled(this, ex); + } + + void warning(System.Exception ex) + { + if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.AMICallback", 1) > 0) + { + instance_.initializationData().logger.warning("exception raised by AMI callback:\n" + ex); } - return base.finished(ex); } - protected BasicStream os_; + // + // This virtual method is necessary for the communicator flush + // batch requests implementation. + // + virtual protected Ice.Instrumentation.InvocationObserver getObserver() + { + return observer_; + } + + public bool sentSynchronously() + { + return sentSynchronously_; + } + + protected Instance instance_; + protected Ice.Connection cachedConnection_; + protected bool sentSynchronously_; + protected int state_; + + protected Ice.Instrumentation.InvocationObserver observer_; protected Ice.Instrumentation.ChildInvocationObserver childObserver_; + + protected Ice.OutputStream os_; + protected Ice.InputStream is_; + + private bool _doneInSent; + private Ice.Exception _ex; + private Ice.LocalException _cancellationException; + private CancellationHandler _cancellationHandler; + private OutgoingAsyncCompletionCallback _completionCallback; + + protected const int StateOK = 0x1; + protected const int StateDone = 0x2; + protected const int StateSent = 0x4; + protected const int StateEndCalled = 0x8; + protected const int StateCachedBuffers = 0x10; + + public const int AsyncStatusQueued = 0; + public const int AsyncStatusSent = 1; + public const int AsyncStatusInvokeSentCallback = 2; } // @@ -116,31 +410,20 @@ namespace IceInternal // public abstract class ProxyOutgoingAsyncBase : OutgoingAsyncBase, TimerTask { - public static ProxyOutgoingAsyncBase check(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation) - { - return ProxyOutgoingAsyncBase.check<ProxyOutgoingAsyncBase>(r, prx, operation); - } + public abstract int invokeRemote(Ice.ConnectionI connection, bool compress, bool response); + public abstract int invokeCollocated(CollocatedRequestHandler handler); - public abstract bool invokeRemote(Ice.ConnectionI con, bool compress, bool resp, out Ice.AsyncCallback cb); - - public abstract bool invokeCollocated(CollocatedRequestHandler handler, out Ice.AsyncCallback cb); - - public override Ice.ObjectPrx getProxy() - { - return proxy_; - } - - public override Ice.AsyncCallback completed(Ice.Exception exc) + public override bool exception(Ice.Exception exc) { if(childObserver_ != null) { - childObserver_.failed(exc.ice_name()); + childObserver_.failed(exc.ice_id()); childObserver_.detach(); childObserver_ = null; } cachedConnection_ = null; - if(proxy_.reference__().getInvocationTimeout() == -2) + if(proxy_.iceReference().getInvocationTimeout() == -2) { instance_.timer().cancel(this); } @@ -156,15 +439,28 @@ namespace IceInternal // the retry interval is 0. This method can be called with the // connection locked so we can't just retry here. // - instance_.retryQueue().add(this, handleException(exc)); - return null; + instance_.retryQueue().add(this, proxy_.iceHandleException(exc, handler_, mode_, _sent, ref _cnt)); + return false; } catch(Ice.Exception ex) { - return finished(ex); // No retries, we're done + return exceptionImpl(ex); // No retries, we're done } } + public override void cancelable(CancellationHandler handler) + { + if(proxy_.iceReference().getInvocationTimeout() == -2 && cachedConnection_ != null) + { + int timeout = cachedConnection_.timeout(); + if(timeout > 0) + { + instance_.timer().schedule(this, timeout); + } + } + base.cancelable(handler); + } + public void retryException(Ice.Exception ex) { try @@ -175,49 +471,33 @@ namespace IceInternal // require could end up waiting for the flush of the // connection to be done. // - proxy_.updateRequestHandler__(handler_, null); // Clear request handler and always retry. + proxy_.iceUpdateRequestHandler(handler_, null); // Clear request handler and always retry. instance_.retryQueue().add(this, 0); } catch(Ice.Exception exc) { - Ice.AsyncCallback cb = completed(exc); - if(cb != null) - { - invokeCompletedAsync(cb); - } - } - } - - public override void cancelable(CancellationHandler handler) - { - if(proxy_.reference__().getInvocationTimeout() == -2 && cachedConnection_ != null) - { - int timeout = cachedConnection_.timeout(); - if(timeout > 0) + if(exception(exc)) { - instance_.timer().schedule(this, timeout); + invokeExceptionAsync(); } } - base.cancelable(handler); } public void retry() { invokeImpl(false); } - - public virtual void abort(Ice.Exception ex) + public void abort(Ice.Exception ex) { Debug.Assert(childObserver_ == null); - Ice.AsyncCallback cb = finished(ex); - if(cb != null) + if(exceptionImpl(ex)) { - invokeCompletedAsync(cb); + invokeExceptionAsync(); } else if(ex is Ice.CommunicatorDestroyedException) { // - // If it's a communicator destroyed exception, don't swallow + // If it's a communicator destroyed exception, swallow // it but instead notify the user thread. Even if no callback // was provided. // @@ -225,29 +505,11 @@ namespace IceInternal } } - public void runTimerTask() - { - if(proxy_.reference__().getInvocationTimeout() == -2) - { - cancel(new Ice.ConnectionTimeoutException()); - } - else - { - cancel(new Ice.InvocationTimeoutException()); - } - } - - protected ProxyOutgoingAsyncBase(Ice.ObjectPrxHelperBase prx, string op, object cookie) : - base(prx.ice_getCommunicator(), prx.reference__().getInstance(), op, cookie) - { - proxy_ = prx; - mode_ = Ice.OperationMode.Normal; - _cnt = 0; - _sent = false; - } - - protected ProxyOutgoingAsyncBase(Ice.ObjectPrxHelperBase prx, string op, object cookie, BasicStream os) : - base(prx.ice_getCommunicator(), prx.reference__().getInstance(), op, cookie, os) + protected ProxyOutgoingAsyncBase(Ice.ObjectPrxHelperBase prx, + OutgoingAsyncCompletionCallback completionCallback, + Ice.OutputStream os = null, + Ice.InputStream iss = null) : + base(prx.iceReference().getInstance(), completionCallback, os, iss) { proxy_ = prx; mode_ = Ice.OperationMode.Normal; @@ -255,35 +517,21 @@ namespace IceInternal _sent = false; } - protected static T check<T>(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation) - { - if(r != null && r.getProxy() != prx) - { - throw new System.ArgumentException("Proxy for call to end_" + operation + - " does not match proxy that was used to call corresponding begin_" + - operation + " method"); - } - return check<T>(r, operation); - } - protected void invokeImpl(bool userThread) { try { if(userThread) { - int invocationTimeout = proxy_.reference__().getInvocationTimeout(); + int invocationTimeout = proxy_.iceReference().getInvocationTimeout(); if(invocationTimeout > 0) { instance_.timer().schedule(this, invocationTimeout); } } - else // If not called from the user thread, it's called from the retry queue + else if(observer_ != null) { - if(observer_ != null) - { - observer_.retried(); - } + observer_.retried(); } while(true) @@ -291,23 +539,23 @@ namespace IceInternal try { _sent = false; - handler_ = proxy_.getRequestHandler__(); - Ice.AsyncCallback sentCallback; - if(handler_.sendAsyncRequest(this, out sentCallback)) + handler_ = proxy_.iceGetRequestHandler(); + int status = handler_.sendAsyncRequest(this); + if((status & AsyncStatusSent) != 0) { if(userThread) { sentSynchronously_ = true; - if(sentCallback != null) + if((status & AsyncStatusInvokeSentCallback) != 0) { - invokeSent(sentCallback); // Call from the user thread. + invokeSent(); // Call the sent callback from the user thread. } } else { - if(sentCallback != null) + if((status & AsyncStatusInvokeSentCallback) != 0) { - invokeSentAsync(sentCallback); // Call from a client thread pool thread. + invokeSentAsync(); // Call the sent callback from a client thread pool thread. } } } @@ -315,17 +563,17 @@ namespace IceInternal } catch(RetryException) { - proxy_.updateRequestHandler__(handler_, null); // Clear request handler and always retry. + proxy_.iceUpdateRequestHandler(handler_, null); // Clear request handler and always retry. } catch(Ice.Exception ex) { if(childObserver_ != null) { - childObserver_.failed(ex.ice_name()); + childObserver_.failed(ex.ice_id()); childObserver_.detach(); childObserver_ = null; } - int interval = handleException(ex); + int interval = proxy_.iceHandleException(ex, handler_, mode_, _sent, ref _cnt); if(interval > 0) { instance_.retryQueue().add(this, interval); @@ -346,53 +594,57 @@ namespace IceInternal // if(userThread) { - throw ex; + throw; } - Ice.AsyncCallback cb = finished(ex); // No retries, we're done - if(cb != null) + else if(exceptionImpl(ex)) // No retries, we're done { - invokeCompletedAsync(cb); + invokeExceptionAsync(); } } } - - protected new Ice.AsyncCallback sent(bool done) + protected override bool sentImpl(bool done) { _sent = true; if(done) { - if(proxy_.reference__().getInvocationTimeout() != -1) + if(proxy_.iceReference().getInvocationTimeout() != -1) { instance_.timer().cancel(this); } } - return base.sent(done); + return base.sentImpl(done); } - - protected new Ice.AsyncCallback finished(Ice.Exception ex) + protected override bool exceptionImpl(Ice.Exception ex) { - if(proxy_.reference__().getInvocationTimeout() != -1) + if(proxy_.iceReference().getInvocationTimeout() != -1) { instance_.timer().cancel(this); } - return base.finished(ex); + return base.exceptionImpl(ex); } - protected new Ice.AsyncCallback finished(bool ok) + protected override bool responseImpl(bool ok) { - if(proxy_.reference__().getInvocationTimeout() != -1) + if(proxy_.iceReference().getInvocationTimeout() != -1) { instance_.timer().cancel(this); } - return base.finished(ok); + return base.responseImpl(ok); } - protected virtual int handleException(Ice.Exception exc) + public void runTimerTask() { - return proxy_.handleException__(exc, handler_, mode_, _sent, ref _cnt); + if(proxy_.iceReference().getInvocationTimeout() == -2) + { + cancel(new Ice.ConnectionTimeoutException()); + } + else + { + cancel(new Ice.InvocationTimeoutException()); + } } - protected Ice.ObjectPrxHelperBase proxy_; + protected readonly Ice.ObjectPrxHelperBase proxy_; protected RequestHandler handler_; protected Ice.OperationMode mode_; @@ -400,42 +652,30 @@ namespace IceInternal private bool _sent; } + // + // Class for handling Slice operation invocations + // public class OutgoingAsync : ProxyOutgoingAsyncBase { - public new static OutgoingAsync check(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation) + public OutgoingAsync(Ice.ObjectPrxHelperBase prx, OutgoingAsyncCompletionCallback completionCallback, + Ice.OutputStream os = null, Ice.InputStream iss = null) : + base(prx, completionCallback, os, iss) { - return ProxyOutgoingAsyncBase.check<OutgoingAsync>(r, prx, operation); + encoding_ = Protocol.getCompatibleEncoding(proxy_.iceReference().getEncoding()); + synchronous_ = false; } - public OutgoingAsync(Ice.ObjectPrx prx, string operation, object cookie) : - base((Ice.ObjectPrxHelperBase)prx, operation, cookie) + public void prepare(string operation, Ice.OperationMode mode, Dictionary<string, string> context, + bool synchronous) { - _encoding = Protocol.getCompatibleEncoding(proxy_.reference__().getEncoding()); - _is = null; - } - - public OutgoingAsync(Ice.ObjectPrx prx, string operation, object cookie, BasicStream istr, BasicStream ostr) : - base((Ice.ObjectPrxHelperBase)prx, operation, cookie, ostr) - { - _encoding = Protocol.getCompatibleEncoding(proxy_.reference__().getEncoding()); - _is = istr; - } - - public void prepare(string operation, Ice.OperationMode mode, Dictionary<string, string> ctx, - bool explicitCtx, bool synchronous) - { - Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(proxy_.reference__().getProtocol())); + Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(proxy_.iceReference().getProtocol())); mode_ = mode; - _synchronous = synchronous; + synchronous_ = synchronous; - if(explicitCtx && ctx == null) - { - ctx = _emptyContext; - } - observer_ = ObserverHelper.get(proxy_, operation, ctx); + observer_ = ObserverHelper.get(proxy_, operation, context); - switch(proxy_.reference__().getMode()) + switch(proxy_.iceReference().getMode()) { case Reference.Mode.ModeTwoway: case Reference.Mode.ModeOneway: @@ -448,14 +688,14 @@ namespace IceInternal case Reference.Mode.ModeBatchOneway: case Reference.Mode.ModeBatchDatagram: { - proxy_.getBatchRequestQueue__().prepareBatchRequest(os_); + proxy_.iceGetBatchRequestQueue().prepareBatchRequest(os_); break; } } - Reference rf = proxy_.reference__(); + Reference rf = proxy_.iceReference(); - rf.getIdentity().write__(os_); + rf.getIdentity().ice_writeMembers(os_); // // For compatibility with the old FacetPath. @@ -475,12 +715,12 @@ namespace IceInternal os_.writeByte((byte)mode); - if(ctx != null) + if(context != null) { // // Explicit context // - Ice.ContextHelper.write(os_, ctx); + Ice.ContextHelper.write(os_, context); } else { @@ -500,74 +740,23 @@ namespace IceInternal } } } - - public override Ice.AsyncCallback sent() - { - return sent(!proxy_.ice_isTwoway()); // done = true if not a two-way proxy (no response expected) - } - - public override bool invokeRemote(Ice.ConnectionI con, bool compress, bool resp, out Ice.AsyncCallback sentCB) - { - cachedConnection_ = con; - return con.sendAsyncRequest(this, compress, resp, 0, out sentCB); - } - - public override bool invokeCollocated(CollocatedRequestHandler handler, out Ice.AsyncCallback sentCB) - { - // The BasicStream cannot be cached if the proxy is not a twoway or there is an invocation timeout set. - if(!proxy_.ice_isTwoway() || proxy_.reference__().getInvocationTimeout() != -1) - { - // Disable caching by marking the streams as cached! - state_ |= StateCachedBuffers; - } - return handler.invokeAsyncRequest(this, 0, _synchronous, out sentCB); - } - - public override void abort(Ice.Exception ex) + public override bool sent() { - Reference.Mode mode = proxy_.reference__().getMode(); - if(mode == Reference.Mode.ModeBatchOneway || mode == Reference.Mode.ModeBatchDatagram) - { - proxy_.getBatchRequestQueue__().abortBatchRequest(os_); - } - - base.abort(ex); - } - - public void invoke() - { - Reference.Mode mode = proxy_.reference__().getMode(); - if(mode == Reference.Mode.ModeBatchOneway || mode == Reference.Mode.ModeBatchDatagram) - { - sentSynchronously_ = true; - proxy_.getBatchRequestQueue__().finishBatchRequest(os_, proxy_, getOperation()); - finished(true); - return; // Don't call sent/completed callback for batch AMI requests - } - - // - // NOTE: invokeImpl doesn't throw so this can be called from the - // try block with the catch block calling abort() in case of an - // exception. - // - invokeImpl(true); // userThread = true + return base.sentImpl(!proxy_.ice_isTwoway()); // done = true if it's not a two-way proxy } - override public Ice.AsyncCallback completed() + public override bool response() { - Debug.Assert(_is != null); // _is has been initialized prior to this call - // // NOTE: this method is called from ConnectionI.parseMessage // with the connection locked. Therefore, it must not invoke // any user callbacks. // - Debug.Assert(proxy_.ice_isTwoway()); // Can only be called for twoways. if(childObserver_ != null) { - childObserver_.reply(_is.size() - Protocol.headerSize - 4); + childObserver_.reply(is_.size() - Protocol.headerSize - 4); childObserver_.detach(); childObserver_ = null; } @@ -575,214 +764,238 @@ namespace IceInternal byte replyStatus; try { - replyStatus = _is.readByte(); + replyStatus = is_.readByte(); switch(replyStatus) { - case ReplyStatus.replyOK: - { - break; - } - - case ReplyStatus.replyUserException: - { - if(observer_ != null) + case ReplyStatus.replyOK: { - observer_.userException(); + break; } - break; - } - - case ReplyStatus.replyObjectNotExist: - case ReplyStatus.replyFacetNotExist: - case ReplyStatus.replyOperationNotExist: - { - Ice.Identity id = new Ice.Identity(); - id.read__(_is); - - // - // For compatibility with the old FacetPath. - // - string[] facetPath = _is.readStringSeq(); - string facet; - if(facetPath.Length > 0) + case ReplyStatus.replyUserException: { - if(facetPath.Length > 1) + if(observer_ != null) { - throw new Ice.MarshalException(); + observer_.userException(); } - facet = facetPath[0]; - } - else - { - facet = ""; - } - - string operation = _is.readString(); - - Ice.RequestFailedException ex = null; - switch(replyStatus) - { - case ReplyStatus.replyObjectNotExist: - { - ex = new Ice.ObjectNotExistException(); break; } + case ReplyStatus.replyObjectNotExist: case ReplyStatus.replyFacetNotExist: - { - ex = new Ice.FacetNotExistException(); - break; - } - case ReplyStatus.replyOperationNotExist: { - ex = new Ice.OperationNotExistException(); - break; - } + Ice.Identity ident = new Ice.Identity(); + ident.ice_readMembers(is_); + + // + // For compatibility with the old FacetPath. + // + string[] facetPath = is_.readStringSeq(); + ; + string facet; + if(facetPath.Length > 0) + { + if(facetPath.Length > 1) + { + throw new Ice.MarshalException(); + } + facet = facetPath[0]; + } + else + { + facet = ""; + } - default: - { - Debug.Assert(false); - break; - } - } + string operation = is_.readString(); - ex.id = id; - ex.facet = facet; - ex.operation = operation; - throw ex; - } + Ice.RequestFailedException ex = null; + switch(replyStatus) + { + case ReplyStatus.replyObjectNotExist: + { + ex = new Ice.ObjectNotExistException(); + break; + } - case ReplyStatus.replyUnknownException: - case ReplyStatus.replyUnknownLocalException: - case ReplyStatus.replyUnknownUserException: - { - string unknown = _is.readString(); + case ReplyStatus.replyFacetNotExist: + { + ex = new Ice.FacetNotExistException(); + break; + } - Ice.UnknownException ex = null; - switch(replyStatus) - { - case ReplyStatus.replyUnknownException: - { - ex = new Ice.UnknownException(); - break; - } + case ReplyStatus.replyOperationNotExist: + { + ex = new Ice.OperationNotExistException(); + break; + } - case ReplyStatus.replyUnknownLocalException: - { - ex = new Ice.UnknownLocalException(); - break; + default: + { + Debug.Assert(false); + break; + } + } + + ex.id = ident; + ex.facet = facet; + ex.operation = operation; + throw ex; } + case ReplyStatus.replyUnknownException: + case ReplyStatus.replyUnknownLocalException: case ReplyStatus.replyUnknownUserException: { - ex = new Ice.UnknownUserException(); - break; + string unknown = is_.readString(); + + Ice.UnknownException ex = null; + switch(replyStatus) + { + case ReplyStatus.replyUnknownException: + { + ex = new Ice.UnknownException(); + break; + } + + case ReplyStatus.replyUnknownLocalException: + { + ex = new Ice.UnknownLocalException(); + break; + } + + case ReplyStatus.replyUnknownUserException: + { + ex = new Ice.UnknownUserException(); + break; + } + + default: + { + Debug.Assert(false); + break; + } + } + + ex.unknown = unknown; + throw ex; } default: { - Debug.Assert(false); - break; - } + throw new Ice.UnknownReplyStatusException(); } - - ex.unknown = unknown; - throw ex; } - default: - { - throw new Ice.UnknownReplyStatusException(); - } - } - - return finished(replyStatus == ReplyStatus.replyOK); + return responseImpl(replyStatus == ReplyStatus.replyOK); } catch(Ice.Exception ex) { - return completed(ex); + return exception(ex); } } - public BasicStream startWriteParams(Ice.FormatType format) + public override int invokeRemote(Ice.ConnectionI connection, bool compress, bool response) { - os_.startWriteEncaps(_encoding, format); - return os_; + cachedConnection_ = connection; + return connection.sendAsyncRequest(this, compress, response, 0); } - public void endWriteParams() + public override int invokeCollocated(CollocatedRequestHandler handler) { - os_.endWriteEncaps(); - } - - public void writeEmptyParams() - { - os_.writeEmptyEncaps(_encoding); - } - - public void writeParamEncaps(byte[] encaps) - { - if(encaps == null || encaps.Length == 0) + // The stream cannot be cached if the proxy is not a twoway or there is an invocation timeout set. + if(!proxy_.ice_isTwoway() || proxy_.iceReference().getInvocationTimeout() != -1) { - os_.writeEmptyEncaps(_encoding); - } - else - { - os_.writeEncaps(encaps); + // Disable caching by marking the streams as cached! + state_ |= StateCachedBuffers; } + return handler.invokeAsyncRequest(this, 0, synchronous_); } - public IceInternal.BasicStream startReadParams() + public new void abort(Ice.Exception ex) { - _is.startReadEncaps(); - return _is; - } + Reference.Mode mode = proxy_.iceReference().getMode(); + if(mode == Reference.Mode.ModeBatchOneway || mode == Reference.Mode.ModeBatchDatagram) + { + // + // If we didn't finish a batch oneway or datagram request, we + // must notify the connection about that we give up ownership + // of the batch stream. + // + proxy_.iceGetBatchRequestQueue().abortBatchRequest(os_); + } - public void endReadParams() - { - _is.endReadEncaps(); + base.abort(ex); } - public void readEmptyParams() + public void invoke(string operation) { - _is.skipEmptyEncaps(); - } + Reference.Mode mode = proxy_.iceReference().getMode(); + if(mode == Reference.Mode.ModeBatchOneway || mode == Reference.Mode.ModeBatchDatagram) + { + sentSynchronously_ = true; + proxy_.iceGetBatchRequestQueue().finishBatchRequest(os_, proxy_, operation); + responseImpl(true); + return; // Don't call sent/completed callback for batch AMI requests + } - public byte[] readParamEncaps() - { - Ice.EncodingVersion encoding; - return _is.readEncaps(out encoding); + // + // NOTE: invokeImpl doesn't throw so this can be called from the + // try block with the catch block calling abort() in case of an + // exception. + // + invokeImpl(true); // userThread = true } - override public BasicStream getIs() + public void invoke(string operation, + Ice.OperationMode mode, + Ice.FormatType format, + Dictionary<string, string> context, + bool synchronous, + System.Action<Ice.OutputStream> write) { - // _is can already be initialized if the invocation is retried - if(_is == null) + try + { + prepare(operation, mode, context, synchronous); + if(write != null) + { + os_.startEncapsulation(encoding_, format); + write(os_); + os_.endEncapsulation(); + } + else + { + os_.writeEmptyEncapsulation(encoding_); + } + invoke(operation); + } + catch(Ice.Exception ex) { - _is = new IceInternal.BasicStream(instance_, Ice.Util.currentProtocolEncoding); + abort(ex); } - return _is; } - public void throwUserException() + public override void throwUserException() { try { - _is.startReadEncaps(); - _is.throwException(null); + is_.startEncapsulation(); + is_.throwException(); } catch(Ice.UserException ex) { - _is.endReadEncaps(); - throw ex; + is_.endEncapsulation(); + if(userException_!= null) + { + userException_.Invoke(ex); + } + throw new Ice.UnknownUserException(ex.ice_id()); } } public override void cacheMessageBuffers() { - if(proxy_.reference__().getInstance().cacheMessageBuffers() > 0) + if(proxy_.iceReference().getInstance().cacheMessageBuffers() > 0) { lock(this) { @@ -793,374 +1006,598 @@ namespace IceInternal state_ |= StateCachedBuffers; } - if(_is != null) + if(is_ != null) { - _is.reset(); + is_.reset(); } os_.reset(); - proxy_.cacheMessageBuffers(_is, os_); + proxy_.cacheMessageBuffers(is_, os_); - _is = null; + is_ = null; os_ = null; } } - private Ice.EncodingVersion _encoding; - private BasicStream _is; - - // - // If true this AMI request is being used for a generated synchronous invocation. - // - private bool _synchronous; - - private static Dictionary<string, string> _emptyContext = new Dictionary<string, string>(); + protected readonly Ice.EncodingVersion encoding_; + protected System.Action<Ice.UserException> userException_; + protected bool synchronous_; } - public class CommunicatorFlushBatch : IceInternal.AsyncResultI + public class OutgoingAsyncT<T> : OutgoingAsync { - public static CommunicatorFlushBatch check(Ice.AsyncResult r, Ice.Communicator com, string operation) + public OutgoingAsyncT(Ice.ObjectPrxHelperBase prx, + OutgoingAsyncCompletionCallback completionCallback, + Ice.OutputStream os = null, + Ice.InputStream iss = null) : + base(prx, completionCallback, os, iss) { - if(r != null && r.getCommunicator() != com) - { - throw new System.ArgumentException("Communicator for call to end_" + operation + - " does not match communicator that was used to call " + - "corresponding begin_" + operation + " method"); - } - return AsyncResultI.check<CommunicatorFlushBatch>(r, operation); } - public CommunicatorFlushBatch(Ice.Communicator communicator, Instance instance, string op, object cookie) : - base(communicator, instance, op, cookie) + public void invoke(string operation, + Ice.OperationMode mode, + Ice.FormatType format, + Dictionary<string, string> context, + bool synchronous, + System.Action<Ice.OutputStream> write = null, + System.Action<Ice.UserException> userException = null, + System.Func<Ice.InputStream, T> read = null) { + read_ = read; + userException_ = userException; + base.invoke(operation, mode, format, context, synchronous, write); + } - observer_ = ObserverHelper.get(instance, op); + public T getResult(bool ok) + { + try + { + if(ok) + { + if(read_ == null) + { + if(is_ == null || is_.isEmpty()) + { + // + // If there's no response (oneway, batch-oneway proxies), we just set the result + // on completion without reading anything from the input stream. This is required for + // batch invocations. + // + } + else + { + is_.skipEmptyEncapsulation(); + } + return default(T); + } + else + { + is_.startEncapsulation(); + T r = read_(is_); + is_.endEncapsulation(); + return r; + } + } + else + { + throwUserException(); + return default(T); // make compiler happy + } + } + finally + { + cacheMessageBuffers(); + } + } - // - // _useCount is initialized to 1 to prevent premature callbacks. - // The caller must invoke ready() after all flush requests have - // been initiated. - // - _useCount = 1; + protected System.Func<Ice.InputStream, T> read_; + } + + // + // Class for handling the proxy's begin_ice_flushBatchRequest request. + // + class ProxyFlushBatchAsync : ProxyOutgoingAsyncBase + { + public ProxyFlushBatchAsync(Ice.ObjectPrxHelperBase prx, OutgoingAsyncCompletionCallback completionCallback) : + base(prx, completionCallback) + { } - public void flushConnection(Ice.ConnectionI con) + public override int invokeRemote(Ice.ConnectionI connection, bool compress, bool response) { - lock(this) + if(_batchRequestNum == 0) { - ++_useCount; + if(sent()) + { + return AsyncStatusSent | AsyncStatusInvokeSentCallback; + } + else + { + return AsyncStatusSent; + } } + cachedConnection_ = connection; + return connection.sendAsyncRequest(this, compress, false, _batchRequestNum); + } - try + public override int invokeCollocated(CollocatedRequestHandler handler) + { + if(_batchRequestNum == 0) { - Ice.AsyncCallback sentCB = null; - FlushBatch flush = new FlushBatch(this); - int batchRequestNum = con.getBatchRequestQueue().swap(flush.getOs()); - if(batchRequestNum == 0) + if(sent()) { - flush.sent(); + return AsyncStatusSent | AsyncStatusInvokeSentCallback; } else { - con.sendAsyncRequest(flush, false, false, batchRequestNum, out sentCB); + return AsyncStatusSent; } - Debug.Assert(sentCB == null); } - catch(Ice.LocalException ex) + return handler.invokeAsyncRequest(this, _batchRequestNum, false); + } + + public void invoke(string operation) + { + Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(proxy_.iceReference().getProtocol())); + observer_ = ObserverHelper.get(proxy_, operation, null); + bool compress; // Not used for proxy flush batch requests. + _batchRequestNum = proxy_.iceGetBatchRequestQueue().swap(os_, out compress); + invokeImpl(true); // userThread = true + } + + private int _batchRequestNum; + } + + // + // Class for handling the proxy's begin_ice_getConnection request. + // + class ProxyGetConnection : ProxyOutgoingAsyncBase + { + public ProxyGetConnection(Ice.ObjectPrxHelperBase prx, OutgoingAsyncCompletionCallback completionCallback) : + base(prx, completionCallback) + { + } + + public override int invokeRemote(Ice.ConnectionI connection, bool compress, bool response) + { + cachedConnection_ = connection; + if(responseImpl(true)) + { + invokeResponseAsync(); + } + return AsyncStatusSent; + } + + public override int invokeCollocated(CollocatedRequestHandler handler) + { + if(responseImpl(true)) { - doCheck(false); - throw ex; + invokeResponseAsync(); } + return AsyncStatusSent; } - public void ready() + public Ice.Connection getConnection() { - doCheck(true); + return cachedConnection_; } - private void doCheck(bool userThread) + public void invoke(string operation) { - lock(this) + observer_ = ObserverHelper.get(proxy_, operation, null); + invokeImpl(true); // userThread = true + } + } + + class ConnectionFlushBatchAsync : OutgoingAsyncBase + { + public ConnectionFlushBatchAsync(Ice.ConnectionI connection, + Instance instance, + OutgoingAsyncCompletionCallback completionCallback) : + base(instance, completionCallback) + { + _connection = connection; + } + + public void invoke(string operation, Ice.CompressBatch compressBatch) + { + observer_ = ObserverHelper.get(instance_, operation); + try { - Debug.Assert(_useCount > 0); - if(--_useCount > 0) + int status; + bool compress; + int batchRequestNum = _connection.getBatchRequestQueue().swap(os_, out compress); + if(batchRequestNum == 0) { - return; + status = AsyncStatusSent; + if(sent()) + { + status = status | AsyncStatusInvokeSentCallback; + } + } + else + { + bool comp; + if(compressBatch == Ice.CompressBatch.Yes) + { + comp = true; + } + else if(compressBatch == Ice.CompressBatch.No) + { + comp = false; + } + else + { + comp = compress; + } + status = _connection.sendAsyncRequest(this, comp, false, batchRequestNum); } - } - Ice.AsyncCallback sentCB = sent(true); - if(userThread) + if((status & AsyncStatusSent) != 0) + { + sentSynchronously_ = true; + if((status & AsyncStatusInvokeSentCallback) != 0) + { + invokeSent(); + } + } + } + catch(RetryException ex) { - sentSynchronously_ = true; - if(sentCB != null) + try { - invokeSent(sentCB); + throw ex.get(); + } + catch(Ice.LocalException ee) + { + if(exception(ee)) + { + invokeExceptionAsync(); + } } } - else + catch(Ice.Exception ex) { - if(sentCB != null) + if(exception(ex)) { - invokeSentAsync(sentCB); + invokeExceptionAsync(); } } } + private readonly Ice.ConnectionI _connection; + }; + + public class CommunicatorFlushBatchAsync : OutgoingAsyncBase + { class FlushBatch : OutgoingAsyncBase { - public FlushBatch(CommunicatorFlushBatch outAsync) : - base(outAsync.getCommunicator(), outAsync.instance_, outAsync.getOperation(), null) + public FlushBatch(CommunicatorFlushBatchAsync outAsync, + Instance instance, + Ice.Instrumentation.InvocationObserver observer) : base(instance, null) { _outAsync = outAsync; + _observer = observer; } - public override Ice.AsyncCallback sent() + public override bool + sent() { if(childObserver_ != null) { childObserver_.detach(); childObserver_ = null; } - _outAsync.doCheck(false); - return null; + _outAsync.check(false); + return false; } - public override Ice.AsyncCallback completed(Ice.Exception ex) + public override bool + exception(Ice.Exception ex) { if(childObserver_ != null) { - childObserver_.failed(ex.ice_name()); + childObserver_.failed(ex.ice_id()); childObserver_.detach(); childObserver_ = null; } - _outAsync.doCheck(false); - return null; + _outAsync.check(false); + return false; } - protected override Ice.Instrumentation.InvocationObserver getObserver() + protected override Ice.Instrumentation.InvocationObserver + getObserver() { - return _outAsync.getObserver(); + return _observer; } - private CommunicatorFlushBatch _outAsync; + private CommunicatorFlushBatchAsync _outAsync; + private Ice.Instrumentation.InvocationObserver _observer; }; - private int _useCount; - } - - public class ConnectionFlushBatch : OutgoingAsyncBase - { - public static ConnectionFlushBatch check(Ice.AsyncResult r, Ice.Connection con, string operation) + public CommunicatorFlushBatchAsync(Instance instance, OutgoingAsyncCompletionCallback callback) : + base(instance, callback) { - if(r != null && r.getConnection() != con) - { - throw new System.ArgumentException("Connection for call to end_" + operation + - " does not match connection that was used to call " + - "corresponding begin_" + operation + " method"); - } - return AsyncResultI.check<ConnectionFlushBatch>(r, operation); - } - - public ConnectionFlushBatch(Ice.ConnectionI con, Ice.Communicator communicator, Instance instance, string op, - object cookie) : - base(communicator, instance, op, cookie) - { - _connection = con; + // + // _useCount is initialized to 1 to prevent premature callbacks. + // The caller must invoke ready() after all flush requests have + // been initiated. + // + _useCount = 1; } - public override Ice.Connection getConnection() + public void flushConnection(Ice.ConnectionI con, Ice.CompressBatch compressBatch) { - return _connection; - } + lock(this) + { + ++_useCount; + } - public void invoke() - { try { - int batchRequestNum = _connection.getBatchRequestQueue().swap(os_); - - bool isSent = false; - Ice.AsyncCallback sentCB; + var flushBatch = new FlushBatch(this, instance_, _observer); + bool compress; + int batchRequestNum = con.getBatchRequestQueue().swap(flushBatch.getOs(), out compress); if(batchRequestNum == 0) { - isSent = true; - sentCB = sent(); + flushBatch.sent(); } else { - isSent = _connection.sendAsyncRequest(this, false, false, batchRequestNum, out sentCB); - } - - if(isSent) - { - sentSynchronously_ = true; - if(sentCB != null) + bool comp; + if(compressBatch == Ice.CompressBatch.Yes) { - invokeSent(sentCB); + comp = true; } + else if(compressBatch == Ice.CompressBatch.No) + { + comp = false; + } + else + { + comp = compress; + } + con.sendAsyncRequest(flushBatch, comp, false, batchRequestNum); } } - catch(RetryException ex) + catch(Ice.LocalException) + { + check(false); + throw; + } + } + + public void invoke(string operation, Ice.CompressBatch compressBatch) + { + _observer = ObserverHelper.get(instance_, operation); + if(_observer != null) + { + _observer.attach(); + } + instance_.outgoingConnectionFactory().flushAsyncBatchRequests(compressBatch, this); + instance_.objectAdapterFactory().flushAsyncBatchRequests(compressBatch, this); + check(true); + } + + public void check(bool userThread) + { + lock(this) { - Ice.AsyncCallback cb = completed(ex.get()); - if(cb != null) + Debug.Assert(_useCount > 0); + if(--_useCount > 0) { - invokeCompletedAsync(cb); + return; } } - catch(Ice.Exception ex) + + if(sentImpl(true)) { - Ice.AsyncCallback cb = completed(ex); - if(cb != null) + if(userThread) + { + sentSynchronously_ = true; + invokeSent(); + } + else { - invokeCompletedAsync(cb); + invokeSentAsync(); } } } - private Ice.ConnectionI _connection; - } + private int _useCount; + private Ice.Instrumentation.InvocationObserver _observer; + }; - public class ProxyFlushBatch : ProxyOutgoingAsyncBase + public abstract class TaskCompletionCallback<T> : TaskCompletionSource<T>, OutgoingAsyncCompletionCallback { - public new static ProxyFlushBatch check(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation) + public TaskCompletionCallback(System.IProgress<bool> progress, CancellationToken cancellationToken) { - return ProxyOutgoingAsyncBase.check<ProxyFlushBatch>(r, prx, operation); + _progress = progress; + _cancellationToken = cancellationToken; } - public ProxyFlushBatch(Ice.ObjectPrxHelperBase prx, string operation, object cookie) : - base(prx, operation, cookie) + public void init(OutgoingAsyncBase outgoing) { - observer_ = ObserverHelper.get(prx, operation); - _batchRequestNum = prx.getBatchRequestQueue__().swap(os_); + if(_cancellationToken.CanBeCanceled) + { + _cancellationToken.Register(outgoing.cancel); + } } - public override bool invokeRemote(Ice.ConnectionI con, bool compress, bool resp, out Ice.AsyncCallback sentCB) + public virtual bool handleSent(bool done, bool alreadySent) { - if(_batchRequestNum == 0) + if(done) { - sentCB = sent(); - return true; + SetResult(default(T)); } - cachedConnection_ = con; - return con.sendAsyncRequest(this, compress, false, _batchRequestNum, out sentCB); + return _progress != null && !alreadySent; // Invoke the sent callback only if not already invoked. } - public override bool invokeCollocated(CollocatedRequestHandler handler, out Ice.AsyncCallback sentCB) + public bool handleException(Ice.Exception ex) { - if(_batchRequestNum == 0) - { - sentCB = sent(); - return true; - } - return handler.invokeAsyncRequest(this, _batchRequestNum, false, out sentCB); + SetException(ex); + return false; + } + + public abstract bool handleResponse(bool ok, OutgoingAsyncBase og); + + public void handleInvokeSent(bool sentSynchronously, OutgoingAsyncBase og) + { + _progress.Report(sentSynchronously); } - public void invoke() + public void handleInvokeException(Ice.Exception ex, OutgoingAsyncBase og) { - Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(proxy_.reference__().getProtocol())); - invokeImpl(true); // userThread = true + Debug.Assert(false); } - private int _batchRequestNum; + public void handleInvokeResponse(bool ok, OutgoingAsyncBase og) + { + Debug.Assert(false); + } + + private readonly CancellationToken _cancellationToken; + private readonly System.IProgress<bool> _progress; } - public class ProxyGetConnection : ProxyOutgoingAsyncBase, Ice.AsyncResult<Ice.Callback_Object_ice_getConnection> + public class OperationTaskCompletionCallback<T> : TaskCompletionCallback<T> { - public new static ProxyGetConnection check(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation) + public OperationTaskCompletionCallback(System.IProgress<bool> progress, CancellationToken cancellationToken) : + base(progress, cancellationToken) { - return ProxyOutgoingAsyncBase.check<ProxyGetConnection>(r, prx, operation); } - public ProxyGetConnection(Ice.ObjectPrxHelperBase prx, string operation, - ProxyTwowayCallback<Ice.Callback_Object_ice_getConnection> cb, object cookie) : - base(prx, operation, cookie) + public override bool handleResponse(bool ok, OutgoingAsyncBase og) { - observer_ = ObserverHelper.get(prx, operation); - _completed = cb; + SetResult(((OutgoingAsyncT<T>)og).getResult(ok)); + return false; } + } - public override bool invokeRemote(Ice.ConnectionI con, bool compress, bool resp, out Ice.AsyncCallback sentCB) + public class FlushBatchTaskCompletionCallback : TaskCompletionCallback<object> + { + public FlushBatchTaskCompletionCallback(System.IProgress<bool> progress, CancellationToken cancellationToken) : + base(progress, cancellationToken) { - sentCB = null; - cachedConnection_ = con; - Ice.AsyncCallback cb = finished(true); - if(cb != null) - { - invokeCompletedAsync(cb); - } - return true; } - public override bool invokeCollocated(CollocatedRequestHandler handler, out Ice.AsyncCallback sentCB) + public override bool handleResponse(bool ok, OutgoingAsyncBase og) { - sentCB = null; - Ice.AsyncCallback cb = finished(true); - if(cb != null) - { - invokeCompletedAsync(cb); - } - return true; + SetResult(null); + return false; } + } - public void invoke() + abstract public class AsyncResultCompletionCallback : AsyncResultI, OutgoingAsyncCompletionCallback + { + public AsyncResultCompletionCallback(Ice.Communicator com, Instance instance, string op, object cookie, + Ice.AsyncCallback cb) : + base(com, instance, op, cookie, cb) { - invokeImpl(true); // userThread = true } - new public Ice.AsyncResult<Ice.Callback_Object_ice_getConnection> whenCompleted(Ice.ExceptionCallback excb) + public void init(OutgoingAsyncBase outgoing) { - base.whenCompleted(excb); - return this; + outgoing_ = outgoing; } - virtual public Ice.AsyncResult<Ice.Callback_Object_ice_getConnection> - whenCompleted(Ice.Callback_Object_ice_getConnection cb, Ice.ExceptionCallback excb) + public bool handleSent(bool done, bool alreadySent) { - if(cb == null && excb == null) + lock(this) { - throw new System.ArgumentException("callback is null"); + state_ |= StateSent; + if(done) + { + state_ |= StateDone | StateOK; + } + if(waitHandle_ != null) + { + waitHandle_.Set(); + } + Monitor.PulseAll(this); + + // + // Invoke the sent callback only if not already invoked. + // + return !alreadySent && sentCallback_ != null; } + } + + public bool handleException(Ice.Exception ex) + { lock(this) { - if(_responseCallback != null || exceptionCallback_ != null) + state_ |= StateDone; + exception_ = ex; + if(waitHandle_ != null) { - throw new System.ArgumentException("callback already set"); + waitHandle_.Set(); } - _responseCallback = cb; - exceptionCallback_ = excb; + Monitor.PulseAll(this); + return completedCallback_ != null; } - setCompletedCallback(getCompletedCallback()); - return this; } - new public Ice.AsyncResult<Ice.Callback_Object_ice_getConnection> whenSent(Ice.SentCallback cb) + public bool handleResponse(bool ok, OutgoingAsyncBase og) { - base.whenSent(cb); - return this; + lock(this) + { + state_ |= StateDone; + if(ok) + { + state_ |= StateOK; + } + if(waitHandle_ != null) + { + waitHandle_.Set(); + } + Monitor.PulseAll(this); + return completedCallback_ != null; + } + } + + public void handleInvokeSent(bool sentSynchronously, OutgoingAsyncBase og) + { + sentCallback_(this); } - protected override Ice.AsyncCallback getCompletedCallback() + public void handleInvokeException(Ice.Exception ex, OutgoingAsyncBase og) { - return (Ice.AsyncResult result) => { _completed(this, _responseCallback, exceptionCallback_); }; + try + { + completedCallback_(this); + } + catch(Ice.Exception e) + { + throw new System.AggregateException(e); + } } - private ProxyTwowayCallback<Ice.Callback_Object_ice_getConnection> _completed; - private Ice.Callback_Object_ice_getConnection _responseCallback = null; + public void handleInvokeResponse(bool ok, OutgoingAsyncBase og) + { + try + { + completedCallback_(this); + } + catch(Ice.Exception e) + { + throw new System.AggregateException(e); + } + } } - public abstract class OutgoingAsync<T> : OutgoingAsync, Ice.AsyncResult<T> + abstract public class ProxyAsyncResultCompletionCallback<T> : AsyncResultCompletionCallback, Ice.AsyncResult<T> { - public OutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, object cookie) : - base(prx, operation, cookie) + public ProxyAsyncResultCompletionCallback(Ice.ObjectPrxHelperBase proxy, string operation, object cookie, + Ice.AsyncCallback cb) : + base(proxy.ice_getCommunicator(), proxy.iceReference().getInstance(), operation, cookie, cb) { + _proxy = proxy; } - public OutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, object cookie, BasicStream iss, - BasicStream os) : - base(prx, operation, cookie, iss, os) + public override Ice.ObjectPrx getProxy() { + return _proxy; } new public Ice.AsyncResult<T> whenCompleted(Ice.ExceptionCallback excb) @@ -1195,73 +1632,48 @@ namespace IceInternal } protected T responseCallback_; + private Ice.ObjectPrx _proxy; } - public class TwowayOutgoingAsync<T> : OutgoingAsync<T> - { - public TwowayOutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, ProxyTwowayCallback<T> cb, - object cookie) : - base(prx, operation, cookie) - { - Debug.Assert(cb != null); - _completed = cb; - } - - public TwowayOutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, ProxyTwowayCallback<T> cb, - object cookie, BasicStream iss, BasicStream os) : - base(prx, operation, cookie, iss, os) - { - Debug.Assert(cb != null); - _completed = cb; - } - - override protected Ice.AsyncCallback getCompletedCallback() - { - return (Ice.AsyncResult result) => { _completed(this, responseCallback_, exceptionCallback_); }; - } - - private ProxyTwowayCallback<T> _completed; - } - - public class OnewayOutgoingAsync<T> : OutgoingAsync<T> + public class OperationAsyncResultCompletionCallback<T, R> : ProxyAsyncResultCompletionCallback<T> { - public OnewayOutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, ProxyOnewayCallback<T> cb, - object cookie) : - base(prx, operation, cookie) + public OperationAsyncResultCompletionCallback(System.Action<T, R> completed, + Ice.ObjectPrxHelperBase proxy, + string operation, + object cookie, + Ice.AsyncCallback callback) : + base(proxy, operation, cookie, callback) { - Debug.Assert(cb != null); - _completed = cb; - } - - public OnewayOutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, ProxyOnewayCallback<T> cb, - object cookie, BasicStream iss, BasicStream os) : - base(prx, operation, cookie, iss, os) - { - Debug.Assert(cb != null); - _completed = cb; + _completed = completed; } override protected Ice.AsyncCallback getCompletedCallback() { - return (Ice.AsyncResult result) => + return (Ice.AsyncResult r) => { + Debug.Assert(r == this); try { - IceInternal.OutgoingAsync outAsync__ = (IceInternal.OutgoingAsync)result; - ((Ice.ObjectPrxHelperBase)(outAsync__.getProxy())).end__(outAsync__, outAsync__.getOperation()); + R result = ((OutgoingAsyncT<R>)outgoing_).getResult(wait()); + try + { + _completed(responseCallback_, result); + } + catch(Ice.Exception ex) + { + throw new System.AggregateException(ex); + } } - catch(Ice.Exception ex__) + catch(Ice.Exception ex) { if(exceptionCallback_ != null) { - exceptionCallback_(ex__); + exceptionCallback_.Invoke(ex); } - return; } - _completed(responseCallback_); }; } - private ProxyOnewayCallback<T> _completed; + private System.Action<T, R> _completed; } } diff --git a/csharp/src/Ice/OutputStream.cs b/csharp/src/Ice/OutputStream.cs new file mode 100644 index 00000000000..9b4130fe52a --- /dev/null +++ b/csharp/src/Ice/OutputStream.cs @@ -0,0 +1,2834 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +namespace Ice +{ + + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Runtime.Serialization; + using System.Runtime.Serialization.Formatters.Binary; + using Protocol = IceInternal.Protocol; + + /// <summary> + /// Interface for output streams used to write Slice types to a sequence + /// of bytes. + /// </summary> + public class OutputStream + { + + /// <summary> + /// Constructing an OutputStream without providing a communicator means the stream will + /// use the default encoding version and the default format for class encoding. + /// You can supply a communicator later by calling initialize(). + /// </summary> + public OutputStream() + { + _buf = new IceInternal.Buffer(); + _instance = null; + _closure = null; + _encoding = Util.currentEncoding; + _format = FormatType.CompactFormat; + } + + /// <summary> + /// This constructor uses the communicator's default encoding version. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + public OutputStream(Communicator communicator) + { + Debug.Assert(communicator != null); + IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, instance.defaultsAndOverrides().defaultEncoding); + } + + /// <summary> + /// This constructor uses the given communicator and encoding version. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + /// <param name="encoding">The desired encoding version.</param> + public OutputStream(Communicator communicator, EncodingVersion encoding) + { + Debug.Assert(communicator != null); + IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, encoding); + } + + public OutputStream(IceInternal.Instance instance, EncodingVersion encoding) + { + initialize(instance, encoding); + } + + public OutputStream(IceInternal.Instance instance, EncodingVersion encoding, IceInternal.Buffer buf, bool adopt) + { + initialize(instance, encoding, new IceInternal.Buffer(buf, adopt)); + } + + public OutputStream(IceInternal.Instance instance, EncodingVersion encoding, byte[] data) + { + initialize(instance, encoding); + _buf = new IceInternal.Buffer(data); + } + + /// <summary> + /// Initializes the stream to use the communicator's default encoding version and class + /// encoding format. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + public void initialize(Communicator communicator) + { + Debug.Assert(communicator != null); + IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, instance.defaultsAndOverrides().defaultEncoding); + } + + /// <summary> + /// Initializes the stream to use the given encoding version and the communicator's + /// default class encoding format. + /// </summary> + /// <param name="communicator">The communicator to use when initializing the stream.</param> + /// <param name="encoding">The desired encoding version.</param> + public void initialize(Communicator communicator, EncodingVersion encoding) + { + Debug.Assert(communicator != null); + IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, encoding); + } + + private void initialize(IceInternal.Instance instance, EncodingVersion encoding) + { + initialize(instance, encoding, new IceInternal.Buffer()); + } + + private void initialize(IceInternal.Instance instance, EncodingVersion encoding, IceInternal.Buffer buf) + { + Debug.Assert(instance != null); + + _instance = instance; + _buf = buf; + _closure = null; + _encoding = encoding; + + _format = _instance.defaultsAndOverrides().defaultFormat; + + _encapsStack = null; + _encapsCache = null; + } + + /// <summary> + /// Resets this output stream. This method allows the stream to be reused, to avoid creating + /// unnecessary garbage. + /// </summary> + public void reset() + { + _buf.reset(); + clear(); + } + + /// <summary> + /// Releases any data retained by encapsulations. The reset() method internally calls clear(). + /// </summary> + public void clear() + { + if(_encapsStack != null) + { + Debug.Assert(_encapsStack.next == null); + _encapsStack.next = _encapsCache; + _encapsCache = _encapsStack; + _encapsStack = null; + _encapsCache.reset(); + } + } + + public IceInternal.Instance instance() + { + return _instance; + } + + /// <summary> + /// Sets the encoding format for class and exception instances. + /// </summary> + /// <param name="fmt">The encoding format.</param> + public void setFormat(FormatType fmt) + { + _format = fmt; + } + + /// <summary> + /// Retrieves the closure object associated with this stream. + /// </summary> + /// <returns>The closure object.</returns> + public object getClosure() + { + return _closure; + } + + /// <summary> + /// Associates a closure object with this stream. + /// </summary> + /// <param name="p">The new closure object.</param> + /// <returns>The previous closure object, or null.</returns> + public object setClosure(object p) + { + object prev = _closure; + _closure = p; + return prev; + } + + /// <summary> + /// Indicates that the marshaling of a request or reply is finished. + /// </summary> + /// <returns>The byte sequence containing the encoded request or reply.</returns> + public byte[] finished() + { + IceInternal.Buffer buf = prepareWrite(); + byte[] result = new byte[buf.b.limit()]; + buf.b.get(result); + return result; + } + + /// <summary> + /// Swaps the contents of one stream with another. + /// </summary> + /// <param name="other">The other stream.</param> + public void swap(OutputStream other) + { + Debug.Assert(_instance == other._instance); + + IceInternal.Buffer tmpBuf = other._buf; + other._buf = _buf; + _buf = tmpBuf; + + EncodingVersion tmpEncoding = other._encoding; + other._encoding = _encoding; + _encoding = tmpEncoding; + + object tmpClosure = other._closure; + other._closure = _closure; + _closure = tmpClosure; + + // + // Swap is never called for streams that have encapsulations being written. However, + // encapsulations might still be set in case marshalling failed. We just + // reset the encapsulations if there are still some set. + // + resetEncapsulation(); + other.resetEncapsulation(); + } + + private void resetEncapsulation() + { + _encapsStack = null; + } + + /// <summary> + /// Resizes the stream to a new size. + /// </summary> + /// <param name="sz">The new size.</param> + public void resize(int sz) + { + _buf.resize(sz, false); + _buf.b.position(sz); + } + + /// <summary> + /// Prepares the internal data buffer to be written to a socket. + /// </summary> + public IceInternal.Buffer prepareWrite() + { + _buf.b.limit(_buf.size()); + _buf.b.position(0); + return _buf; + } + + /// <summary> + /// Retrieves the internal data buffer. + /// </summary> + /// <returns>The buffer.</returns> + public IceInternal.Buffer getBuffer() + { + return _buf; + } + + /// <summary> + /// Marks the start of a class instance. + /// </summary> + /// <param name="data">Preserved slices for this instance, or null.</param> + public void startValue(SlicedData data) + { + Debug.Assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.startInstance(SliceType.ValueSlice, data); + } + + /// <summary> + /// Marks the end of a class instance. + /// </summary> + public void endValue() + { + Debug.Assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.endInstance(); + } + + /// <summary> + /// Marks the start of a user exception. + /// </summary> + /// <param name="data">Preserved slices for this exception, or null.</param> + public void startException(SlicedData data) + { + Debug.Assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.startInstance(SliceType.ExceptionSlice, data); + } + + /// <summary> + /// Marks the end of a user exception. + /// </summary> + public void endException() + { + Debug.Assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.endInstance(); + } + + /// <summary> + /// Writes the start of an encapsulation to the stream. + /// </summary> + public void startEncapsulation() + { + // + // If no encoding version is specified, use the current write + // encapsulation encoding version if there's a current write + // encapsulation, otherwise, use the stream encoding version. + // + + if(_encapsStack != null) + { + startEncapsulation(_encapsStack.encoding, _encapsStack.format); + } + else + { + startEncapsulation(_encoding, FormatType.DefaultFormat); + } + } + + /// <summary> + /// Writes the start of an encapsulation to the stream. + /// </summary> + /// <param name="encoding">The encoding version of the encapsulation.</param> + /// <param name="format">Specify the compact or sliced format.</param> + public void startEncapsulation(EncodingVersion encoding, FormatType format) + { + Protocol.checkSupportedEncoding(encoding); + + Encaps curr = _encapsCache; + if(curr != null) + { + curr.reset(); + _encapsCache = _encapsCache.next; + } + else + { + curr = new Encaps(); + } + curr.next = _encapsStack; + _encapsStack = curr; + + _encapsStack.format = format; + _encapsStack.setEncoding(encoding); + _encapsStack.start = _buf.b.position(); + + writeInt(0); // Placeholder for the encapsulation length. + _encapsStack.encoding.ice_writeMembers(this); + } + + /// <summary> + /// Ends the previous encapsulation. + /// </summary> + public void endEncapsulation() + { + Debug.Assert(_encapsStack != null); + + // Size includes size and version. + int start = _encapsStack.start; + int sz = _buf.size() - start; + _buf.b.putInt(start, sz); + + Encaps curr = _encapsStack; + _encapsStack = curr.next; + curr.next = _encapsCache; + _encapsCache = curr; + _encapsCache.reset(); + } + + /// <summary> + /// Writes an empty encapsulation using the given encoding version. + /// </summary> + /// <param name="encoding">The encoding version of the encapsulation.</param> + public void writeEmptyEncapsulation(EncodingVersion encoding) + { + Protocol.checkSupportedEncoding(encoding); + writeInt(6); // Size + encoding.ice_writeMembers(this); + } + + /// <summary> + /// Writes a pre-encoded encapsulation. + /// </summary> + /// <param name="v">The encapsulation data.</param> + public void writeEncapsulation(byte[] v) + { + if(v.Length < 6) + { + throw new EncapsulationException(); + } + expand(v.Length); + _buf.b.put(v); + } + + /// <summary> + /// Determines the current encoding version. + /// </summary> + /// <returns>The encoding version.</returns> + public EncodingVersion getEncoding() + { + return _encapsStack != null ? _encapsStack.encoding : _encoding; + } + + /// <summary> + /// Marks the start of a new slice for a class instance or user exception. + /// </summary> + /// <param name="typeId">The Slice type ID corresponding to this slice.</param> + /// <param name="compactId">The Slice compact type ID corresponding to this slice or -1 if no compact ID + /// is defined for the type ID.</param> + /// <param name="last">True if this is the last slice, false otherwise.</param> + public void startSlice(string typeId, int compactId, bool last) + { + Debug.Assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.startSlice(typeId, compactId, last); + } + + /// <summary> + /// Marks the end of a slice for a class instance or user exception. + /// </summary> + public void endSlice() + { + Debug.Assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.endSlice(); + } + + /// <summary> + /// Writes the state of Slice classes whose index was previously written with writeValue() to the stream. + /// </summary> + public void writePendingValues() + { + if(_encapsStack != null && _encapsStack.encoder != null) + { + _encapsStack.encoder.writePendingValues(); + } + else if(_encapsStack != null ? + _encapsStack.encoding_1_0 : _encoding.Equals(Util.Encoding_1_0)) + { + // + // If using the 1.0 encoding and no instances were written, we + // still write an empty sequence for pending instances if + // requested (i.e.: if this is called). + // + // This is required by the 1.0 encoding, even if no instances + // are written we do marshal an empty sequence if marshaled + // data types use classes. + // + writeSize(0); + } + } + + /// <summary> + /// Writes a size to the stream. + /// </summary> + /// <param name="v">The size to write.</param> + public void writeSize(int v) + { + if(v > 254) + { + expand(5); + _buf.b.put(255); + _buf.b.putInt(v); + } + else + { + expand(1); + _buf.b.put((byte)v); + } + } + + /// <summary> + /// Returns the current position and allocates four bytes for a fixed-length (32-bit) size value. + /// </summary> + public int startSize() + { + int pos = _buf.b.position(); + writeInt(0); // Placeholder for 32-bit size + return pos; + } + + /// <summary> + /// Computes the amount of data written since the previous call to startSize and writes that value + /// at the saved position. + /// </summary> + /// <param name="pos">The saved position.</param> + public void endSize(int pos) + { + Debug.Assert(pos >= 0); + rewriteInt(_buf.b.position() - pos - 4, pos); + } + + /// <summary> + /// Writes a blob of bytes to the stream. + /// </summary> + /// <param name="v">The byte array to be written. All of the bytes in the array are written.</param> + public void writeBlob(byte[] v) + { + if(v == null) + { + return; + } + expand(v.Length); + _buf.b.put(v); + } + + /// <summary> + /// Writes a blob of bytes to the stream. + /// </summary> + /// <param name="v">The byte array to be written. All of the bytes in the array are written.</param> + /// <param name="off">The offset into the byte array from which to copy.</param> + /// <param name="len">The number of bytes from the byte array to copy.</param> + public void writeBlob(byte[] v, int off, int len) + { + if(v == null) + { + return; + } + expand(len); + _buf.b.put(v, off, len); + } + + /// <summary> + /// Write the header information for an optional value. + /// </summary> + /// <param name="tag">The numeric tag associated with the value.</param> + /// <param name="format">The optional format of the value.</param> + public bool writeOptional(int tag, OptionalFormat format) + { + Debug.Assert(_encapsStack != null); + if(_encapsStack.encoder != null) + { + return _encapsStack.encoder.writeOptional(tag, format); + } + else + { + return writeOptionalImpl(tag, format); + } + } + + /// <summary> + /// Writes a byte to the stream. + /// </summary> + /// <param name="v">The byte to write to the stream.</param> + public void writeByte(byte v) + { + expand(1); + _buf.b.put(v); + } + + /// <summary> + /// Writes an optional byte to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional byte to write to the stream.</param> + public void writeByte(int tag, Optional<byte> v) + { + if(v.HasValue) + { + writeByte(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional byte to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The byte to write to the stream.</param> + public void writeByte(int tag, byte v) + { + if(writeOptional(tag, OptionalFormat.F1)) + { + writeByte(v); + } + } + + /// <summary> + /// Writes a byte to the stream at the given position. The current position of the stream is not modified. + /// </summary> + /// <param name="v">The byte to write to the stream.</param> + /// <param name="dest">The position at which to store the byte in the buffer.</param> + public void rewriteByte(byte v, int dest) + { + _buf.b.put(dest, v); + } + + /// <summary> + /// Writes a byte sequence to the stream. + /// </summary> + /// <param name="v">The byte sequence to write to the stream. + /// Passing null causes an empty sequence to be written to the stream.</param> + public void writeByteSeq(byte[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length); + _buf.b.put(v); + } + } + + /// <summary> + /// Writes a byte sequence to the stream. + /// </summary> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the container holding the sequence.</param> + public void writeByteSeq(int count, IEnumerable<byte> v) + { + if(count == 0) + { + writeSize(0); + return; + } + + { + List<byte> value = v as List<byte>; + if(value != null) + { + writeByteSeq(value.ToArray()); + return; + } + } + + { + LinkedList<byte> value = v as LinkedList<byte>; + if(value != null) + { + writeSize(count); + expand(count); + IEnumerator<byte> i = v.GetEnumerator(); + while(i.MoveNext()) + { + _buf.b.put(i.Current); + } + return; + } + } + + { + Queue<byte> value = v as Queue<byte>; + if(value != null) + { + writeByteSeq(value.ToArray()); + return; + } + } + + { + Stack<byte> value = v as Stack<byte>; + if(value != null) + { + writeByteSeq(value.ToArray()); + return; + } + } + + writeSize(count); + expand(count); + foreach(byte b in v) + { + _buf.b.put(b); + } + } + + /// <summary> + /// Writes an optional byte sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional byte sequence to write to the stream.</param> + public void writeByteSeq(int tag, Optional<byte[]> v) + { + if(v.HasValue) + { + writeByteSeq(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional byte sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the optional byte sequence.</param> + public void writeByteSeq<T>(int tag, int count, Optional<T> v) + where T : IEnumerable<byte> + { + if(v.HasValue && writeOptional(tag, OptionalFormat.VSize)) + { + writeByteSeq(count, v.Value); + } + } + + /// <summary> + /// Writes an optional byte sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The byte sequence to write to the stream.</param> + public void writeByteSeq(int tag, byte[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeByteSeq(v); + } + } + + /// <summary> + /// Writes an optional byte sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the byte sequence.</param> + public void writeByteSeq(int tag, int count, IEnumerable<byte> v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeByteSeq(count, v); + } + } + + /// <summary> + /// Writes a serializable object to the stream. + /// </summary> + /// <param name="o">The serializable object to write.</param> + public void writeSerializable(object o) + { + if(o == null) + { + writeSize(0); + return; + } + try + { + IceInternal.OutputStreamWrapper w = new IceInternal.OutputStreamWrapper(this); + IFormatter f = new BinaryFormatter(); + f.Serialize(w, o); + w.Close(); + } + catch(System.Exception ex) + { + throw new MarshalException("cannot serialize object:", ex); + } + } + + /// <summary> + /// Writes a boolean to the stream. + /// </summary> + /// <param name="v">The boolean to write to the stream.</param> + public void writeBool(bool v) + { + expand(1); + _buf.b.put(v ? (byte)1 : (byte)0); + } + + /// <summary> + /// Writes an optional boolean to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional boolean to write to the stream.</param> + public void writeBool(int tag, Optional<bool> v) + { + if(v.HasValue) + { + writeBool(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional boolean to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The boolean to write to the stream.</param> + public void writeBool(int tag, bool v) + { + if(writeOptional(tag, OptionalFormat.F1)) + { + writeBool(v); + } + } + + /// <summary> + /// Writes a boolean to the stream at the given position. The current position of the stream is not modified. + /// </summary> + /// <param name="v">The boolean to write to the stream.</param> + /// <param name="dest">The position at which to store the boolean in the buffer.</param> + public void rewriteBool(bool v, int dest) + { + _buf.b.put(dest, v ? (byte)1 : (byte)0); + } + + /// <summary> + /// Writes a boolean sequence to the stream. + /// </summary> + /// <param name="v">The boolean sequence to write to the stream. + /// Passing null causes an empty sequence to be written to the stream.</param> + public void writeBoolSeq(bool[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length); + _buf.b.putBoolSeq(v); + } + } + + /// <summary> + /// Writes a boolean sequence to the stream. + /// </summary> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the container holding the sequence.</param> + public void writeBoolSeq(int count, IEnumerable<bool> v) + { + if(count == 0) + { + writeSize(0); + return; + } + + { + List<bool> value = v as List<bool>; + if(value != null) + { + writeBoolSeq(value.ToArray()); + return; + } + } + + { + LinkedList<bool> value = v as LinkedList<bool>; + if(value != null) + { + writeSize(count); + expand(count); + IEnumerator<bool> i = v.GetEnumerator(); + while(i.MoveNext()) + { + _buf.b.putBool(i.Current); + } + return; + } + } + + { + Queue<bool> value = v as Queue<bool>; + if(value != null) + { + writeBoolSeq(value.ToArray()); + return; + } + } + + { + Stack<bool> value = v as Stack<bool>; + if(value != null) + { + writeBoolSeq(value.ToArray()); + return; + } + } + + writeSize(count); + expand(count); + foreach(bool b in v) + { + _buf.b.putBool(b); + } + } + + /// <summary> + /// Writes an optional boolean sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional boolean sequence to write to the stream.</param> + public void writeBoolSeq(int tag, Optional<bool[]> v) + { + if(v.HasValue) + { + writeBoolSeq(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional boolean sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the optional boolean sequence.</param> + public void writeBoolSeq<T>(int tag, int count, Optional<T> v) + where T : IEnumerable<bool> + { + if(v.HasValue && writeOptional(tag, OptionalFormat.VSize)) + { + writeBoolSeq(count, v.Value); + } + } + + /// <summary> + /// Writes an optional boolean sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The boolean sequence to write to the stream.</param> + public void writeBoolSeq(int tag, bool[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeBoolSeq(v); + } + } + + /// <summary> + /// Writes an optional boolean sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the boolean sequence.</param> + public void writeBoolSeq(int tag, int count, IEnumerable<bool> v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeBoolSeq(count, v); + } + } + + /// <summary> + /// Writes a short to the stream. + /// </summary> + /// <param name="v">The short to write to the stream.</param> + public void writeShort(short v) + { + expand(2); + _buf.b.putShort(v); + } + + /// <summary> + /// Writes an optional short to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional short to write to the stream.</param> + public void writeShort(int tag, Optional<short> v) + { + if(v.HasValue) + { + writeShort(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional short to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The short to write to the stream.</param> + public void writeShort(int tag, short v) + { + if(writeOptional(tag, OptionalFormat.F2)) + { + writeShort(v); + } + } + + /// <summary> + /// Writes a short sequence to the stream. + /// </summary> + /// <param name="v">The short sequence to write to the stream. + /// Passing null causes an empty sequence to be written to the stream.</param> + public void writeShortSeq(short[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 2); + _buf.b.putShortSeq(v); + } + } + + /// <summary> + /// Writes a short sequence to the stream. + /// </summary> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the container holding the sequence.</param> + public void writeShortSeq(int count, IEnumerable<short> v) + { + if(count == 0) + { + writeSize(0); + return; + } + + { + List<short> value = v as List<short>; + if(value != null) + { + writeShortSeq(value.ToArray()); + return; + } + } + + { + LinkedList<short> value = v as LinkedList<short>; + if(value != null) + { + writeSize(count); + expand(count * 2); + IEnumerator<short> i = v.GetEnumerator(); + while(i.MoveNext()) + { + _buf.b.putShort(i.Current); + } + return; + } + } + + { + Queue<short> value = v as Queue<short>; + if(value != null) + { + writeShortSeq(value.ToArray()); + return; + } + } + + { + Stack<short> value = v as Stack<short>; + if(value != null) + { + writeShortSeq(value.ToArray()); + return; + } + } + + writeSize(count); + expand(count * 2); + foreach(short s in v) + { + _buf.b.putShort(s); + } + } + + /// <summary> + /// Writes an optional short sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional short sequence to write to the stream.</param> + public void writeShortSeq(int tag, Optional<short[]> v) + { + if(v.HasValue) + { + writeShortSeq(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional short sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the optional short sequence.</param> + public void writeShortSeq<T>(int tag, int count, Optional<T> v) + where T : IEnumerable<short> + { + if(v.HasValue && writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(count == 0 ? 1 : count * 2 + (count > 254 ? 5 : 1)); + writeShortSeq(count, v.Value); + } + } + + /// <summary> + /// Writes an optional short sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The short sequence to write to the stream.</param> + public void writeShortSeq(int tag, short[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.Length == 0 ? 1 : v.Length * 2 + (v.Length > 254 ? 5 : 1)); + writeShortSeq(v); + } + } + + /// <summary> + /// Writes an optional short sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the short sequence.</param> + public void writeShortSeq(int tag, int count, IEnumerable<short> v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || count == 0 ? 1 : count * 2 + (count > 254 ? 5 : 1)); + writeShortSeq(count, v); + } + } + + /// <summary> + /// Writes an int to the stream. + /// </summary> + /// <param name="v">The int to write to the stream.</param> + public void writeInt(int v) + { + expand(4); + _buf.b.putInt(v); + } + + /// <summary> + /// Writes an optional int to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional int to write to the stream.</param> + public void writeInt(int tag, Optional<int> v) + { + if(v.HasValue) + { + writeInt(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional int to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The int to write to the stream.</param> + public void writeInt(int tag, int v) + { + if(writeOptional(tag, OptionalFormat.F4)) + { + writeInt(v); + } + } + + /// <summary> + /// Writes an int to the stream at the given position. The current position of the stream is not modified. + /// </summary> + /// <param name="v">The int to write to the stream.</param> + /// <param name="dest">The position at which to store the int in the buffer.</param> + public void rewriteInt(int v, int dest) + { + _buf.b.putInt(dest, v); + } + + /// <summary> + /// Writes an int sequence to the stream. + /// </summary> + /// <param name="v">The int sequence to write to the stream. + /// Passing null causes an empty sequence to be written to the stream.</param> + public void writeIntSeq(int[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 4); + _buf.b.putIntSeq(v); + } + } + + /// <summary> + /// Writes an int sequence to the stream. + /// </summary> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the container holding the sequence.</param> + public void writeIntSeq(int count, IEnumerable<int> v) + { + if(count == 0) + { + writeSize(0); + return; + } + + { + List<int> value = v as List<int>; + if(value != null) + { + writeIntSeq(value.ToArray()); + return; + } + } + + { + LinkedList<int> value = v as LinkedList<int>; + if(value != null) + { + writeSize(count); + expand(count * 4); + IEnumerator<int> i = v.GetEnumerator(); + while(i.MoveNext()) + { + _buf.b.putInt(i.Current); + } + return; + } + } + + { + Queue<int> value = v as Queue<int>; + if(value != null) + { + writeIntSeq(value.ToArray()); + return; + } + } + + { + Stack<int> value = v as Stack<int>; + if(value != null) + { + writeIntSeq(value.ToArray()); + return; + } + } + + writeSize(count); + expand(count * 4); + foreach(int i in v) + { + _buf.b.putInt(i); + } + } + + /// <summary> + /// Writes an optional int sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional int sequence to write to the stream.</param> + public void writeIntSeq(int tag, Optional<int[]> v) + { + if(v.HasValue) + { + writeIntSeq(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional int sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the optional byte sequence.</param> + public void writeIntSeq<T>(int tag, int count, Optional<T> v) + where T : IEnumerable<int> + { + if(v.HasValue && writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(count == 0 ? 1 : count * 4 + (count > 254 ? 5 : 1)); + writeIntSeq(count, v.Value); + } + } + + /// <summary> + /// Writes an optional int sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The int sequence to write to the stream.</param> + public void writeIntSeq(int tag, int[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.Length == 0 ? 1 : v.Length * 4 + (v.Length > 254 ? 5 : 1)); + writeIntSeq(v); + } + } + + /// <summary> + /// Writes an optional int sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the int sequence.</param> + public void writeIntSeq(int tag, int count, IEnumerable<int> v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || count == 0 ? 1 : count * 4 + (count > 254 ? 5 : 1)); + writeIntSeq(count, v); + } + } + + /// <summary> + /// Writes a long to the stream. + /// </summary> + /// <param name="v">The long to write to the stream.</param> + public void writeLong(long v) + { + expand(8); + _buf.b.putLong(v); + } + + /// <summary> + /// Writes an optional long to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional long to write to the stream.</param> + public void writeLong(int tag, Optional<long> v) + { + if(v.HasValue) + { + writeLong(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional long to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The long to write to the stream.</param> + public void writeLong(int tag, long v) + { + if(writeOptional(tag, OptionalFormat.F8)) + { + writeLong(v); + } + } + + /// <summary> + /// Writes a long sequence to the stream. + /// </summary> + /// <param name="v">The long sequence to write to the stream. + /// Passing null causes an empty sequence to be written to the stream.</param> + public void writeLongSeq(long[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 8); + _buf.b.putLongSeq(v); + } + } + + /// <summary> + /// Writes a long sequence to the stream. + /// </summary> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the container holding the sequence.</param> + public void writeLongSeq(int count, IEnumerable<long> v) + { + if(count == 0) + { + writeSize(0); + return; + } + + { + List<long> value = v as List<long>; + if(value != null) + { + writeLongSeq(value.ToArray()); + return; + } + } + + { + LinkedList<long> value = v as LinkedList<long>; + if(value != null) + { + writeSize(count); + expand(count * 8); + IEnumerator<long> i = v.GetEnumerator(); + while(i.MoveNext()) + { + _buf.b.putLong(i.Current); + } + return; + } + } + + { + Queue<long> value = v as Queue<long>; + if(value != null) + { + writeLongSeq(value.ToArray()); + return; + } + } + + { + Stack<long> value = v as Stack<long>; + if(value != null) + { + writeLongSeq(value.ToArray()); + return; + } + } + + writeSize(count); + expand(count * 8); + foreach(long l in v) + { + _buf.b.putLong(l); + } + } + + /// <summary> + /// Writes an optional long sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional long sequence to write to the stream.</param> + public void writeLongSeq(int tag, Optional<long[]> v) + { + if(v.HasValue) + { + writeLongSeq(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional long sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the optional long sequence.</param> + public void writeLongSeq<T>(int tag, int count, Optional<T> v) + where T : IEnumerable<long> + { + if(v.HasValue && writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(count == 0 ? 1 : count * 8 + (count > 254 ? 5 : 1)); + writeLongSeq(count, v.Value); + } + } + + /// <summary> + /// Writes an optional long sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The long sequence to write to the stream.</param> + public void writeLongSeq(int tag, long[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.Length == 0 ? 1 : v.Length * 8 + (v.Length > 254 ? 5 : 1)); + writeLongSeq(v); + } + } + + /// <summary> + /// Writes an optional long sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the long sequence.</param> + public void writeLongSeq(int tag, int count, IEnumerable<long> v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || count == 0 ? 1 : count * 8 + (count > 254 ? 5 : 1)); + writeLongSeq(count, v); + } + } + + /// <summary> + /// Writes a float to the stream. + /// </summary> + /// <param name="v">The float to write to the stream.</param> + public void writeFloat(float v) + { + expand(4); + _buf.b.putFloat(v); + } + + /// <summary> + /// Writes an optional float to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional float to write to the stream.</param> + public void writeFloat(int tag, Optional<float> v) + { + if(v.HasValue) + { + writeFloat(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional float to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The float to write to the stream.</param> + public void writeFloat(int tag, float v) + { + if(writeOptional(tag, OptionalFormat.F4)) + { + writeFloat(v); + } + } + + /// <summary> + /// Writes a float sequence to the stream. + /// </summary> + /// <param name="v">The float sequence to write to the stream. + /// Passing null causes an empty sequence to be written to the stream.</param> + public void writeFloatSeq(float[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 4); + _buf.b.putFloatSeq(v); + } + } + + /// <summary> + /// Writes a float sequence to the stream. + /// </summary> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the container holding the sequence.</param> + public void writeFloatSeq(int count, IEnumerable<float> v) + { + if(count == 0) + { + writeSize(0); + return; + } + + { + List<float> value = v as List<float>; + if(value != null) + { + writeFloatSeq(value.ToArray()); + return; + } + } + + { + LinkedList<float> value = v as LinkedList<float>; + if(value != null) + { + writeSize(count); + expand(count * 4); + IEnumerator<float> i = v.GetEnumerator(); + while(i.MoveNext()) + { + _buf.b.putFloat(i.Current); + } + return; + } + } + + { + Queue<float> value = v as Queue<float>; + if(value != null) + { + writeFloatSeq(value.ToArray()); + return; + } + } + + { + Stack<float> value = v as Stack<float>; + if(value != null) + { + writeFloatSeq(value.ToArray()); + return; + } + } + + writeSize(count); + expand(count * 4); + foreach(float f in v) + { + _buf.b.putFloat(f); + } + } + + /// <summary> + /// Writes an optional float sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional float sequence to write to the stream.</param> + public void writeFloatSeq(int tag, Optional<float[]> v) + { + if(v.HasValue) + { + writeFloatSeq(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional float sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the optional float sequence.</param> + public void writeFloatSeq<T>(int tag, int count, Optional<T> v) + where T : IEnumerable<float> + { + if(v.HasValue && writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(count == 0 ? 1 : count * 4 + (count > 254 ? 5 : 1)); + writeFloatSeq(count, v.Value); + } + } + + /// <summary> + /// Writes an optional float sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The float sequence to write to the stream.</param> + public void writeFloatSeq(int tag, float[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.Length == 0 ? 1 : v.Length * 4 + (v.Length > 254 ? 5 : 1)); + writeFloatSeq(v); + } + } + + /// <summary> + /// Writes an optional float sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the float sequence.</param> + public void writeFloatSeq(int tag, int count, IEnumerable<float> v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || count == 0 ? 1 : count * 4 + (count > 254 ? 5 : 1)); + writeFloatSeq(count, v); + } + } + + /// <summary> + /// Writes a double to the stream. + /// </summary> + /// <param name="v">The double to write to the stream.</param> + public void writeDouble(double v) + { + expand(8); + _buf.b.putDouble(v); + } + + /// <summary> + /// Writes an optional double to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional double to write to the stream.</param> + public void writeDouble(int tag, Optional<double> v) + { + if(v.HasValue) + { + writeDouble(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional double to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The double to write to the stream.</param> + public void writeDouble(int tag, double v) + { + if(writeOptional(tag, OptionalFormat.F8)) + { + writeDouble(v); + } + } + + /// <summary> + /// Writes a double sequence to the stream. + /// </summary> + /// <param name="v">The double sequence to write to the stream. + /// Passing null causes an empty sequence to be written to the stream.</param> + public void writeDoubleSeq(double[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 8); + _buf.b.putDoubleSeq(v); + } + } + + /// <summary> + /// Writes a double sequence to the stream. + /// </summary> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the container holding the sequence.</param> + public void writeDoubleSeq(int count, IEnumerable<double> v) + { + if(count == 0) + { + writeSize(0); + return; + } + + { + List<double> value = v as List<double>; + if(value != null) + { + writeDoubleSeq(value.ToArray()); + return; + } + } + + { + LinkedList<double> value = v as LinkedList<double>; + if(value != null) + { + writeSize(count); + expand(count * 8); + IEnumerator<double> i = v.GetEnumerator(); + while(i.MoveNext()) + { + _buf.b.putDouble(i.Current); + } + return; + } + } + + { + Queue<double> value = v as Queue<double>; + if(value != null) + { + writeDoubleSeq(value.ToArray()); + return; + } + } + + { + Stack<double> value = v as Stack<double>; + if (value != null) + { + writeDoubleSeq(value.ToArray()); + return; + } + } + + writeSize(count); + expand(count * 8); + foreach(double d in v) + { + _buf.b.putDouble(d); + } + } + + /// <summary> + /// Writes an optional double sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional double sequence to write to the stream.</param> + public void writeDoubleSeq(int tag, Optional<double[]> v) + { + if(v.HasValue) + { + writeDoubleSeq(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional double sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the optional double sequence.</param> + public void writeDoubleSeq<T>(int tag, int count, Optional<T> v) + where T : IEnumerable<double> + { + if(v.HasValue && writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(count == 0 ? 1 : count * 8 + (count > 254 ? 5 : 1)); + writeDoubleSeq(count, v.Value); + } + } + + /// <summary> + /// Writes an optional double sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The double sequence to write to the stream.</param> + public void writeDoubleSeq(int tag, double[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.Length == 0 ? 1 : v.Length * 8 + (v.Length > 254 ? 5 : 1)); + writeDoubleSeq(v); + } + } + + /// <summary> + /// Writes an optional double sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the double sequence.</param> + public void writeDoubleSeq(int tag, int count, IEnumerable<double> v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || count == 0 ? 1 : count * 8 + (count > 254 ? 5 : 1)); + writeDoubleSeq(count, v); + } + } + + private static System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); + + /// <summary> + /// Writes a string to the stream. + /// </summary> + /// <param name="v">The string to write to the stream. Passing null causes + /// an empty string to be written to the stream.</param> + public void writeString(string v) + { + if(v == null || v.Length == 0) + { + writeSize(0); + return; + } + byte[] arr = utf8.GetBytes(v); + writeSize(arr.Length); + expand(arr.Length); + _buf.b.put(arr); + } + + /// <summary> + /// Writes an optional string to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional string to write to the stream.</param> + public void writeString(int tag, Optional<string> v) + { + if(v.HasValue) + { + writeString(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional string to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The string to write to the stream.</param> + public void writeString(int tag, string v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeString(v); + } + } + + /// <summary> + /// Writes a string sequence to the stream. + /// </summary> + /// <param name="v">The string sequence to write to the stream. + /// Passing null causes an empty sequence to be written to the stream.</param> + public void writeStringSeq(string[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + for(int i = 0; i < v.Length; i++) + { + writeString(v[i]); + } + } + } + + /// <summary> + /// Writes a string sequence to the stream. + /// </summary> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the container holding the sequence.</param> + public void writeStringSeq(int count, IEnumerable<string> v) + { + writeSize(count); + if(count != 0) + { + foreach(string s in v) + { + writeString(s); + } + } + } + + /// <summary> + /// Writes an optional string sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional string sequence to write to the stream.</param> + public void writeStringSeq(int tag, Optional<string[]> v) + { + if(v.HasValue) + { + writeStringSeq(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional string sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the optional string sequence.</param> + public void writeStringSeq<T>(int tag, int count, Optional<T> v) + where T : IEnumerable<string> + { + if(v.HasValue && writeOptional(tag, OptionalFormat.FSize)) + { + int pos = startSize(); + writeStringSeq(count, v.Value); + endSize(pos); + } + } + + /// <summary> + /// Writes an optional string sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The string sequence to write to the stream.</param> + public void writeStringSeq(int tag, string[] v) + { + if(writeOptional(tag, OptionalFormat.FSize)) + { + int pos = startSize(); + writeStringSeq(v); + endSize(pos); + } + } + + /// <summary> + /// Writes an optional string sequence to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="count">The number of elements in the sequence.</param> + /// <param name="v">An enumerator for the string sequence.</param> + public void writeStringSeq(int tag, int count, IEnumerable<string> v) + { + if(writeOptional(tag, OptionalFormat.FSize)) + { + int pos = startSize(); + writeStringSeq(count, v); + endSize(pos); + } + } + + /// <summary> + /// Writes a proxy to the stream. + /// </summary> + /// <param name="v">The proxy to write.</param> + public void writeProxy(ObjectPrx v) + { + if(v != null) + { + v.iceWrite(this); + } + else + { + Identity ident = new Identity(); + ident.ice_writeMembers(this); + } + } + + /// <summary> + /// Writes an optional proxy to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional proxy to write.</param> + public void writeProxy(int tag, Optional<ObjectPrx> v) + { + if(v.HasValue) + { + writeProxy(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional proxy to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The proxy to write.</param> + public void writeProxy(int tag, ObjectPrx v) + { + if(writeOptional(tag, OptionalFormat.FSize)) + { + int pos = startSize(); + writeProxy(v); + endSize(pos); + } + } + + /// <summary> + /// Writes an enumerated value. + /// </summary> + /// <param name="v">The enumerator.</param> + /// <param name="maxValue">The maximum enumerator value in the definition.</param> + public void writeEnum(int v, int maxValue) + { + if(isEncoding_1_0()) + { + if(maxValue < 127) + { + writeByte((byte)v); + } + else if(maxValue < 32767) + { + writeShort((short)v); + } + else + { + writeInt(v); + } + } + else + { + writeSize(v); + } + } + + /// <summary> + /// Writes an optional enumerator to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The enumerator.</param> + /// <param name="maxValue">The maximum enumerator value in the definition.</param> + public void writeEnum(int tag, int v, int maxValue) + { + if(writeOptional(tag, OptionalFormat.Size)) + { + writeEnum(v, maxValue); + } + } + + /// <summary> + /// Writes a class instance to the stream. + /// </summary> + /// <param name="v">The value to write. This method writes the index of an instance; the state of the value is + /// written once writePendingValues() is called.</param> + public void writeValue(Value v) + { + initEncaps(); + _encapsStack.encoder.writeValue(v); + } + + /// <summary> + /// Writes an optional class instance to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The optional value to write.</param> + public void writeValue<T>(int tag, Optional<T> v) where T : Value + { + if(v.HasValue) + { + writeValue(tag, v.Value); + } + } + + /// <summary> + /// Writes an optional class instance to the stream. + /// </summary> + /// <param name="tag">The optional tag.</param> + /// <param name="v">The value to write.</param> + public void writeValue(int tag, Value v) + { + if(writeOptional(tag, OptionalFormat.Class)) + { + writeValue(v); + } + } + + /// <summary> + /// Writes a user exception to the stream. + /// </summary> + /// <param name="v">The user exception to write.</param> + public void writeException(UserException v) + { + initEncaps(); + _encapsStack.encoder.writeException(v); + } + + private bool writeOptionalImpl(int tag, OptionalFormat format) + { + if(isEncoding_1_0()) + { + return false; // Optional members aren't supported with the 1.0 encoding. + } + + int v = (int)format; + if(tag < 30) + { + v |= tag << 3; + writeByte((byte)v); + } + else + { + v |= 0x0F0; // tag = 30 + writeByte((byte)v); + writeSize(tag); + } + return true; + } + + /// <summary> + /// Determines the current position in the stream. + /// </summary> + /// <returns>The current position.</returns> + public int pos() + { + return _buf.b.position(); + } + + /// <summary> + /// Sets the current position in the stream. + /// </summary> + /// <param name="n">The new position.</param> + public void pos(int n) + { + _buf.b.position(n); + } + + /// <summary> + /// Determines the current size of the stream. + /// </summary> + /// <returns>The current size.</returns> + public int size() + { + return _buf.size(); + } + + /// <summary> + /// Determines whether the stream is empty. + /// </summary> + /// <returns>True if no data has been written yet, false otherwise.</returns> + public bool isEmpty() + { + return _buf.empty(); + } + + /// <summary> + /// Expand the stream to accept more data. + /// </summary> + /// <param name="n">The number of bytes to accommodate in the stream.</param> + public void expand(int n) + { + _buf.expand(n); + } + + private IceInternal.Instance _instance; + private IceInternal.Buffer _buf; + private object _closure; + private FormatType _format; + + private enum SliceType { NoSlice, ValueSlice, ExceptionSlice } + + abstract private class EncapsEncoder + { + protected EncapsEncoder(OutputStream stream, Encaps encaps) + { + _stream = stream; + _encaps = encaps; + _typeIdIndex = 0; + _marshaledMap = new Dictionary<Value, int>(); + } + + internal abstract void writeValue(Value v); + internal abstract void writeException(UserException v); + + internal abstract void startInstance(SliceType type, SlicedData data); + internal abstract void endInstance(); + internal abstract void startSlice(string typeId, int compactId, bool last); + internal abstract void endSlice(); + + internal virtual bool writeOptional(int tag, OptionalFormat format) + { + return false; + } + + internal virtual void writePendingValues() + { + } + + protected int registerTypeId(string typeId) + { + if(_typeIdMap == null) + { + _typeIdMap = new Dictionary<string, int>(); + } + + int p; + if(_typeIdMap.TryGetValue(typeId, out p)) + { + return p; + } + else + { + _typeIdMap.Add(typeId, ++_typeIdIndex); + return -1; + } + } + + protected readonly OutputStream _stream; + protected readonly Encaps _encaps; + + // Encapsulation attributes for instance marshaling. + protected readonly Dictionary<Value, int> _marshaledMap; + + // Encapsulation attributes for instance marshaling. + private Dictionary<string, int> _typeIdMap; + private int _typeIdIndex; + } + + private sealed class EncapsEncoder10 : EncapsEncoder + { + internal EncapsEncoder10(OutputStream stream, Encaps encaps) : base(stream, encaps) + { + _sliceType = SliceType.NoSlice; + _valueIdIndex = 0; + _toBeMarshaledMap = new Dictionary<Value, int>(); + } + + internal override void writeValue(Value v) + { + // + // Object references are encoded as a negative integer in 1.0. + // + if(v != null) + { + _stream.writeInt(-registerValue(v)); + } + else + { + _stream.writeInt(0); + } + } + + internal override void writeException(UserException v) + { + // + // User exception with the 1.0 encoding start with a bool + // flag that indicates whether or not the exception uses + // classes. + // + // This allows reading the pending instances even if some part of + // the exception was sliced. + // + bool usesClasses = v.iceUsesClasses(); + _stream.writeBool(usesClasses); + v.iceWrite(_stream); + if(usesClasses) + { + writePendingValues(); + } + } + + internal override void startInstance(SliceType sliceType, SlicedData sliceData) + { + _sliceType = sliceType; + } + + internal override void endInstance() + { + if(_sliceType == SliceType.ValueSlice) + { + // + // Write the Object slice. + // + startSlice(Value.ice_staticId(), -1, true); + _stream.writeSize(0); // For compatibility with the old AFM. + endSlice(); + } + _sliceType = SliceType.NoSlice; + } + + internal override void startSlice(string typeId, int compactId, bool last) + { + // + // For instance slices, encode a bool to indicate how the type ID + // is encoded and the type ID either as a string or index. For + // exception slices, always encode the type ID as a string. + // + if(_sliceType == SliceType.ValueSlice) + { + int index = registerTypeId(typeId); + if(index < 0) + { + _stream.writeBool(false); + _stream.writeString(typeId); + } + else + { + _stream.writeBool(true); + _stream.writeSize(index); + } + } + else + { + _stream.writeString(typeId); + } + + _stream.writeInt(0); // Placeholder for the slice length. + + _writeSlice = _stream.pos(); + } + + internal override void endSlice() + { + // + // Write the slice length. + // + int sz = _stream.pos() - _writeSlice + 4; + _stream.rewriteInt(sz, _writeSlice - 4); + } + + internal override void writePendingValues() + { + while(_toBeMarshaledMap.Count > 0) + { + // + // Consider the to be marshalled instances as marshalled now, + // this is necessary to avoid adding again the "to be + // marshalled instances" into _toBeMarshaledMap while writing + // instances. + // + foreach(var e in _toBeMarshaledMap) + { + _marshaledMap.Add(e.Key, e.Value); + } + + var savedMap = _toBeMarshaledMap; + _toBeMarshaledMap = new Dictionary<Value, int>(); + _stream.writeSize(savedMap.Count); + foreach(var p in savedMap) + { + // + // Ask the instance to marshal itself. Any new class + // instances that are triggered by the classes marshaled + // are added to toBeMarshaledMap. + // + _stream.writeInt(p.Value); + + try + { + p.Key.ice_preMarshal(); + } + catch(System.Exception ex) + { + string s = "exception raised by ice_preMarshal:\n" + ex; + _stream.instance().initializationData().logger.warning(s); + } + + p.Key.iceWrite(_stream); + } + } + _stream.writeSize(0); // Zero marker indicates end of sequence of sequences of instances. + } + + private int registerValue(Value v) + { + Debug.Assert(v != null); + + // + // Look for this instance in the to-be-marshaled map. + // + int p; + if(_toBeMarshaledMap.TryGetValue(v, out p)) + { + return p; + } + + // + // Didn't find it, try the marshaled map next. + // + if(_marshaledMap.TryGetValue(v, out p)) + { + return p; + } + + // + // We haven't seen this instance previously, create a new + // index, and insert it into the to-be-marshaled map. + // + _toBeMarshaledMap.Add(v, ++_valueIdIndex); + return _valueIdIndex; + } + + // Instance attributes + private SliceType _sliceType; + + // Slice attributes + private int _writeSlice; // Position of the slice data members + + // Encapsulation attributes for instance marshaling. + private int _valueIdIndex; + private Dictionary<Value, int> _toBeMarshaledMap; + } + + private sealed class EncapsEncoder11 : EncapsEncoder + { + internal EncapsEncoder11(OutputStream stream, Encaps encaps) : base(stream, encaps) + { + _current = null; + _valueIdIndex = 1; + } + + internal override void writeValue(Value v) + { + if(v == null) + { + _stream.writeSize(0); + } + else if(_current != null && _encaps.format == FormatType.SlicedFormat) + { + if(_current.indirectionTable == null) + { + _current.indirectionTable = new List<Value>(); + _current.indirectionMap = new Dictionary<Value, int>(); + } + + // + // If writing an instance within a slice and using the sliced + // format, write an index from the instance indirection table. + // + int index; + if(!_current.indirectionMap.TryGetValue(v, out index)) + { + _current.indirectionTable.Add(v); + int idx = _current.indirectionTable.Count; // Position + 1 (0 is reserved for nil) + _current.indirectionMap.Add(v, idx); + _stream.writeSize(idx); + } + else + { + _stream.writeSize(index); + } + } + else + { + writeInstance(v); // Write the instance or a reference if already marshaled. + } + } + + internal override void writeException(UserException v) + { + v.iceWrite(_stream); + } + + internal override void startInstance(SliceType sliceType, SlicedData data) + { + if(_current == null) + { + _current = new InstanceData(null); + } + else + { + _current = _current.next == null ? new InstanceData(_current) : _current.next; + } + _current.sliceType = sliceType; + _current.firstSlice = true; + + if(data != null) + { + writeSlicedData(data); + } + } + + internal override void endInstance() + { + _current = _current.previous; + } + + internal override void startSlice(string typeId, int compactId, bool last) + { + Debug.Assert((_current.indirectionTable == null || _current.indirectionTable.Count == 0) && + (_current.indirectionMap == null || _current.indirectionMap.Count == 0)); + + _current.sliceFlagsPos = _stream.pos(); + + _current.sliceFlags = 0; + if(_encaps.format == FormatType.SlicedFormat) + { + // + // Encode the slice size if using the sliced format. + // + _current.sliceFlags |= Protocol.FLAG_HAS_SLICE_SIZE; + } + if(last) + { + _current.sliceFlags |= Protocol.FLAG_IS_LAST_SLICE; // This is the last slice. + } + + _stream.writeByte(0); // Placeholder for the slice flags + + // + // For instance slices, encode the flag and the type ID either as a + // string or index. For exception slices, always encode the type + // ID a string. + // + if(_current.sliceType == SliceType.ValueSlice) + { + // + // Encode the type ID (only in the first slice for the compact + // encoding). + // + if(_encaps.format == FormatType.SlicedFormat || _current.firstSlice) + { + if(compactId >= 0) + { + _current.sliceFlags |= Protocol.FLAG_HAS_TYPE_ID_COMPACT; + _stream.writeSize(compactId); + } + else + { + int index = registerTypeId(typeId); + if(index < 0) + { + _current.sliceFlags |= Protocol.FLAG_HAS_TYPE_ID_STRING; + _stream.writeString(typeId); + } + else + { + _current.sliceFlags |= Protocol.FLAG_HAS_TYPE_ID_INDEX; + _stream.writeSize(index); + } + } + } + } + else + { + _stream.writeString(typeId); + } + + if((_current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) != 0) + { + _stream.writeInt(0); // Placeholder for the slice length. + } + + _current.writeSlice = _stream.pos(); + _current.firstSlice = false; + } + + internal override void endSlice() + { + // + // Write the optional member end marker if some optional members + // were encoded. Note that the optional members are encoded before + // the indirection table and are included in the slice size. + // + if((_current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) != 0) + { + _stream.writeByte(Protocol.OPTIONAL_END_MARKER); + } + + // + // Write the slice length if necessary. + // + if((_current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) != 0) + { + int sz = _stream.pos() - _current.writeSlice + 4; + _stream.rewriteInt(sz, _current.writeSlice - 4); + } + + // + // Only write the indirection table if it contains entries. + // + if(_current.indirectionTable != null && _current.indirectionTable.Count > 0) + { + Debug.Assert(_encaps.format == FormatType.SlicedFormat); + _current.sliceFlags |= Protocol.FLAG_HAS_INDIRECTION_TABLE; + + // + // Write the indirect instance table. + // + _stream.writeSize(_current.indirectionTable.Count); + foreach(var v in _current.indirectionTable) + { + writeInstance(v); + } + _current.indirectionTable.Clear(); + _current.indirectionMap.Clear(); + } + + // + // Finally, update the slice flags. + // + _stream.rewriteByte(_current.sliceFlags, _current.sliceFlagsPos); + } + + internal override bool writeOptional(int tag, OptionalFormat format) + { + if(_current == null) + { + return _stream.writeOptionalImpl(tag, format); + } + else + { + if(_stream.writeOptionalImpl(tag, format)) + { + _current.sliceFlags |= Protocol.FLAG_HAS_OPTIONAL_MEMBERS; + return true; + } + else + { + return false; + } + } + } + + private void writeSlicedData(SlicedData slicedData) + { + Debug.Assert(slicedData != null); + + // + // We only remarshal preserved slices if we are using the sliced + // format. Otherwise, we ignore the preserved slices, which + // essentially "slices" the instance into the most-derived type + // known by the sender. + // + if(_encaps.format != FormatType.SlicedFormat) + { + return; + } + + foreach(var info in slicedData.slices) + { + startSlice(info.typeId, info.compactId, info.isLastSlice); + + // + // Write the bytes associated with this slice. + // + _stream.writeBlob(info.bytes); + + if(info.hasOptionalMembers) + { + _current.sliceFlags |= Protocol.FLAG_HAS_OPTIONAL_MEMBERS; + } + + // + // Make sure to also re-write the instance indirection table. + // + if(info.instances != null && info.instances.Length > 0) + { + if(_current.indirectionTable == null) + { + _current.indirectionTable = new List<Value>(); + _current.indirectionMap = new Dictionary<Value, int>(); + } + foreach(var o in info.instances) + { + _current.indirectionTable.Add(o); + } + } + + endSlice(); + } + } + + private void writeInstance(Value v) + { + Debug.Assert(v != null); + + // + // If the instance was already marshaled, just write it's ID. + // + int p; + if(_marshaledMap.TryGetValue(v, out p)) + { + _stream.writeSize(p); + return; + } + + // + // We haven't seen this instance previously, create a new ID, + // insert it into the marshaled map, and write the instance. + // + _marshaledMap.Add(v, ++_valueIdIndex); + + try + { + v.ice_preMarshal(); + } + catch(System.Exception ex) + { + string s = "exception raised by ice_preMarshal:\n" + ex; + _stream.instance().initializationData().logger.warning(s); + } + + _stream.writeSize(1); // Object instance marker. + v.iceWrite(_stream); + } + + private sealed class InstanceData + { + internal InstanceData(InstanceData previous) + { + if(previous != null) + { + previous.next = this; + } + this.previous = previous; + next = null; + } + + // Instance attributes + internal SliceType sliceType; + internal bool firstSlice; + + // Slice attributes + internal byte sliceFlags; + internal int writeSlice; // Position of the slice data members + internal int sliceFlagsPos; // Position of the slice flags + internal List<Value> indirectionTable; + internal Dictionary<Value, int> indirectionMap; + + internal InstanceData previous; + internal InstanceData next; + } + + private InstanceData _current; + + private int _valueIdIndex; // The ID of the next instance to marhsal + } + + private sealed class Encaps + { + internal void reset() + { + encoder = null; + } + + internal void setEncoding(EncodingVersion encoding) + { + this.encoding = encoding; + encoding_1_0 = encoding.Equals(Util.Encoding_1_0); + } + + internal int start; + internal EncodingVersion encoding; + internal bool encoding_1_0; + internal FormatType format = FormatType.DefaultFormat; + + internal EncapsEncoder encoder; + + internal Encaps next; + } + + // + // The encoding version to use when there's no encapsulation to + // read from or write to. This is for example used to read message + // headers or when the user is using the streaming API with no + // encapsulation. + // + private EncodingVersion _encoding; + + private bool isEncoding_1_0() + { + return _encapsStack != null ? _encapsStack.encoding_1_0 : _encoding.Equals(Util.Encoding_1_0); + } + + private Encaps _encapsStack; + private Encaps _encapsCache; + + private void initEncaps() + { + if(_encapsStack == null) // Lazy initialization + { + _encapsStack = _encapsCache; + if(_encapsStack != null) + { + _encapsCache = _encapsCache.next; + } + else + { + _encapsStack = new Encaps(); + } + _encapsStack.setEncoding(_encoding); + } + + if(_encapsStack.format == FormatType.DefaultFormat) + { + _encapsStack.format = _instance.defaultsAndOverrides().defaultFormat; + } + + if(_encapsStack.encoder == null) // Lazy initialization. + { + if(_encapsStack.encoding_1_0) + { + _encapsStack.encoder = new EncapsEncoder10(this, _encapsStack); + } + else + { + _encapsStack.encoder = new EncapsEncoder11(this, _encapsStack); + } + } + } + } + + /// <summary> + /// Base class for writing class instances to an output stream. + /// </summary> + public abstract class ValueWriter : Value + { + /// <summary> + /// Writes the state of this Slice class instance to an output stream. + /// </summary> + /// <param name="outStream">The stream to write to.</param> + public abstract void write(OutputStream outStream); + + public override void iceWrite(OutputStream os) + { + write(os); + } + + public override void iceRead(InputStream istr) + { + Debug.Assert(false); + } + } + +} diff --git a/csharp/src/Ice/Patcher.cs b/csharp/src/Ice/Patcher.cs index f69103b7603..f89db7bf5bc 100644 --- a/csharp/src/Ice/Patcher.cs +++ b/csharp/src/Ice/Patcher.cs @@ -10,60 +10,34 @@ using System; using System.Collections.Generic; using System.Reflection; -using System.Diagnostics; namespace IceInternal { - public interface IPatcher + public sealed class ParamPatcher<T> where T : Ice.Value { - void patch(Ice.Object v); - string type(); - } - - public abstract class Patcher : IPatcher, Ice.ReadObjectCallback - { - public Patcher(string type) + public ParamPatcher(string type) { _type = type; } - public abstract void patch(Ice.Object v); - - public virtual string type() - { - return _type; - } - - public virtual void invoke(Ice.Object v) - { - patch(v); - } - - private string _type; - } - - public sealed class ParamPatcher<T> : Patcher - { - public ParamPatcher(string type) : base(type) - { - } - - public override void patch(Ice.Object v) + public void patch(Ice.Value v) { if(v != null && !typeof(T).IsAssignableFrom(v.GetType())) { - IceInternal.Ex.throwUOE(type(), v.ice_id()); + Ex.throwUOE(_type, v.ice_id()); } value = (T)v; } public T value; + private string _type; } - public sealed class CustomSeqPatcher<T> : Patcher + public sealed class CustomSeqPatcher<T> where T : Ice.Value { - public CustomSeqPatcher(string type, IEnumerable<T> seq, int index) : base(type) + public CustomSeqPatcher(string type, IEnumerable<T> seq, int index) { + _type = type; _seq = seq; _seqType = seq.GetType(); _index = index; @@ -71,11 +45,11 @@ namespace IceInternal setInvokeInfo(_seqType); } - public override void patch(Ice.Object v) + public void patch(Ice.Value v) { if(v != null && !typeof(T).IsAssignableFrom(v.GetType())) { - IceInternal.Ex.throwUOE(type(), v.ice_id()); + Ex.throwUOE(_type, v.ice_id()); } InvokeInfo info = getInvokeInfo(_seqType); @@ -205,80 +179,50 @@ namespace IceInternal private static Type[] _params = new Type[] { typeof(T) }; private static Dictionary<Type, InvokeInfo> _methodTable = new Dictionary<Type, InvokeInfo>(); + private string _type; private IEnumerable<T> _seq; private Type _seqType; private int _index; // The index at which to patch the sequence. } - public sealed class ArrayPatcher<T> : Patcher + public sealed class ArrayPatcher<T> where T : Ice.Value { - public ArrayPatcher(string type, T[] seq, int index) : base(type) + public ArrayPatcher(string type, T[] seq, int index) { + _type = type; _seq = seq; _index = index; } - public override void patch(Ice.Object v) + public void patch(Ice.Value v) { if(v != null && !typeof(T).IsAssignableFrom(v.GetType())) { - IceInternal.Ex.throwUOE(type(), v.ice_id()); + Ex.throwUOE(_type, v.ice_id()); } _seq[_index] = (T)v; } + private string _type; private T[] _seq; private int _index; // The index at which to patch the array. } - public sealed class SequencePatcher<T> : Patcher + public sealed class ListPatcher<T> where T : Ice.Value { - public SequencePatcher(string type, IceInternal.CollectionBase<T> seq, int index) : base(type) - { - _seq = seq; - _index = index; - } - - public override void patch(Ice.Object v) - { - if(v != null && !typeof(T).IsAssignableFrom(v.GetType())) - { - IceInternal.Ex.throwUOE(type(), v.ice_id()); - } - - int count = _seq.Count; - if(_index >= count) // Need to grow the sequence. - { - for(int i = count; i < _index; i++) - { - _seq.Add(default(T)); - } - _seq.Add((T)v); - } - else - { - _seq[_index] = (T)v; - } - } - - private IceInternal.CollectionBase<T> _seq; - private int _index; // The index at which to patch the sequence. - } - - public sealed class ListPatcher<T> : Patcher - { - public ListPatcher(string type, List<T> seq, int index) : base(type) + public ListPatcher(string type, List<T> seq, int index) { + _type = type; _seq = seq; _index = index; } - public override void patch(Ice.Object v) + public void patch(Ice.Value v) { if(v != null && !typeof(T).IsAssignableFrom(v.GetType())) { - IceInternal.Ex.throwUOE(type(), v.ice_id()); + Ex.throwUOE(_type, v.ice_id()); } int count = _seq.Count; @@ -296,6 +240,7 @@ namespace IceInternal } } + private string _type; private List<T> _seq; private int _index; // The index at which to patch the sequence. } diff --git a/csharp/src/Ice/PluginManagerI.cs b/csharp/src/Ice/PluginManagerI.cs index 3f225f3e29e..867722430d2 100644 --- a/csharp/src/Ice/PluginManagerI.cs +++ b/csharp/src/Ice/PluginManagerI.cs @@ -7,7 +7,6 @@ // // ********************************************************************** -#if !SILVERLIGHT namespace Ice { using System; @@ -57,15 +56,13 @@ namespace Ice { p.plugin.initialize(); } - catch(PluginInitializationException ex) + catch(PluginInitializationException) { - throw ex; + throw; } catch(System.Exception ex) { - PluginInitializationException e = new PluginInitializationException(ex); - e.reason = "plugin `" + p.name + "' initialization failed"; - throw e; + throw new PluginInitializationException(String.Format("plugin `{0}' initialization failed", p.name), ex); } initializedPlugins.Add(p.plugin); } @@ -171,8 +168,8 @@ namespace Ice } catch(System.Exception ex) { - Ice.Util.getProcessLogger().warning("unexpected exception raised by plug-in `" + - p.name + "' destruction:\n" + ex.ToString()); + Util.getProcessLogger().warning("unexpected exception raised by plug-in `" + + p.name + "' destruction:\n" + ex.ToString()); } } } @@ -357,7 +354,7 @@ namespace Ice // string err = "unable to load plug-in `" + entryPoint + "': "; int sepPos = entryPoint.IndexOf(':'); - if(sepPos != -1 && IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows) + if(sepPos != -1) { const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; if(entryPoint.Length > 3 && @@ -405,37 +402,6 @@ namespace Ice } catch(System.Exception ex) { -#if COMPACT - // - // IceSSL is not supported with the Compact Framework. - // - if(name == "IceSSL") - { - if(!_sslWarnOnce) - { - _communicator.getLogger().warning( - "IceSSL plug-in not loaded: IceSSL is not supported with the .NET Compact Framework"); - _sslWarnOnce = true; - } - return; - } -#else - // - // IceSSL is not yet supported with Mono. We avoid throwing an exception in that case, - // so the same configuration can be used with Mono or Visual C#. - // - if(IceInternal.AssemblyUtil.runtime_ == IceInternal.AssemblyUtil.Runtime.Mono && name == "IceSSL") - { - if(!_sslWarnOnce) - { - _communicator.getLogger().warning( - "IceSSL plug-in not loaded: IceSSL is not supported with Mono"); - _sslWarnOnce = true; - } - return; - } -#endif - PluginInitializationException e = new PluginInitializationException(); e.reason = err + "unable to load assembly: `" + assemblyName + "': " + ex.ToString(); throw e; @@ -467,13 +433,13 @@ namespace Ice throw e; } } - catch(System.InvalidCastException ex) + catch(InvalidCastException ex) { PluginInitializationException e = new PluginInitializationException(ex); e.reason = err + "InvalidCastException to Ice.PluginFactory"; throw e; } - catch(System.UnauthorizedAccessException ex) + catch(UnauthorizedAccessException ex) { PluginInitializationException e = new PluginInitializationException(ex); e.reason = err + "UnauthorizedAccessException: " + ex.ToString(); @@ -494,7 +460,7 @@ namespace Ice catch(PluginInitializationException ex) { ex.reason = err + ex.reason; - throw ex; + throw; } catch(System.Exception ex) { @@ -537,7 +503,5 @@ namespace Ice private Communicator _communicator; private ArrayList _plugins; private bool _initialized; - private static bool _sslWarnOnce = false; } } -#endif diff --git a/csharp/src/Ice/PropertiesAdminI.cs b/csharp/src/Ice/PropertiesAdminI.cs index 84f209efa2f..5fa6a69064a 100644 --- a/csharp/src/Ice/PropertiesAdminI.cs +++ b/csharp/src/Ice/PropertiesAdminI.cs @@ -7,6 +7,7 @@ // // ********************************************************************** +using System; using System.Collections.Generic; namespace Ice @@ -29,10 +30,10 @@ namespace IceInternal { sealed class PropertiesAdminI : Ice.PropertiesAdminDisp_, Ice.NativePropertiesAdmin { - internal PropertiesAdminI(Ice.Properties properties, Ice.Logger logger) + internal PropertiesAdminI(Instance instance) { - _properties = properties; - _logger = logger; + _properties = instance.initializationData().properties; + _logger = instance.initializationData().logger; } public override string @@ -40,16 +41,15 @@ namespace IceInternal { return _properties.getProperty(name); } - + public override Dictionary<string, string> getPropertiesForPrefix(string name, Ice.Current current) { return _properties.getPropertiesForPrefix(name); } - - public override void setProperties_async(Ice.AMD_PropertiesAdmin_setProperties cb, - Dictionary<string, string> props, - Ice.Current current) + + public override void + setProperties(Dictionary<string, string> props, Ice.Current current) { lock(this) { @@ -177,19 +177,8 @@ namespace IceInternal _properties.setProperty(e.Key, ""); } - // - // Send the response now so that we do not block the client during the call to the update callback. - // - cb.ice_response(); - if(_updateCallbacks.Count > 0) { - // - // Copy the callbacks to allow callbacks to update the callbacks. - // - List<Ice.PropertiesAdminUpdateCallback> callbacks = - new List<Ice.PropertiesAdminUpdateCallback>(_updateCallbacks); - Dictionary<string, string> changes = new Dictionary<string, string>(added); foreach(KeyValuePair<string, string> e in changed) { @@ -199,16 +188,20 @@ namespace IceInternal { changes.Add(e.Key, e.Value); } - - foreach(Ice.PropertiesAdminUpdateCallback callback in callbacks) + + // Copy callbacks to allow callbacks to update callbacks + foreach(var callback in new List<Ice.PropertiesAdminUpdateCallback>(_updateCallbacks)) { try { callback.updated(changes); } - catch(System.Exception) + catch(Exception ex) { - // Ignore. + if(_properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 1) + { + _logger.warning("properties admin update callback raised unexpected exception:\n" + ex); + } } } } diff --git a/csharp/src/Ice/PropertiesI.cs b/csharp/src/Ice/PropertiesI.cs index 55fb36bab1e..7d8c9569ffd 100644 --- a/csharp/src/Ice/PropertiesI.cs +++ b/csharp/src/Ice/PropertiesI.cs @@ -84,12 +84,12 @@ namespace Ice pv.used = true; try { - return System.Int32.Parse(pv.val, CultureInfo.InvariantCulture); + return int.Parse(pv.val, CultureInfo.InvariantCulture); } - catch(System.FormatException) + catch(FormatException) { - Ice.Util.getProcessLogger().warning("numeric property " + key + - " set to non-numeric value, defaulting to " + val); + Util.getProcessLogger().warning("numeric property " + key + + " set to non-numeric value, defaulting to " + val); return val; } } @@ -120,8 +120,8 @@ namespace Ice string[] result = IceUtilInternal.StringUtil.splitString(pv.val, ", \t\r\n"); if(result == null) { - Ice.Util.getProcessLogger().warning("mismatched quotes in property " + key - + "'s value, returning default value"); + Util.getProcessLogger().warning("mismatched quotes in property " + key + + "'s value, returning default value"); return val; } else @@ -142,7 +142,7 @@ namespace Ice { if(prefix.Length == 0 || s.StartsWith(prefix, StringComparison.Ordinal)) { - PropertyValue pv = (PropertyValue)_properties[s]; + PropertyValue pv = _properties[s]; pv.used = true; result[s] = pv.val; } @@ -162,13 +162,13 @@ namespace Ice } if(key == null || key.Length == 0) { - throw new Ice.InitializationException("Attempt to set property with empty key"); + throw new InitializationException("Attempt to set property with empty key"); } // // Check if the property is legal. // - Logger logger = Ice.Util.getProcessLogger(); + Logger logger = Util.getProcessLogger(); int dotPos = key.IndexOf('.'); if(dotPos != -1) { @@ -313,12 +313,7 @@ namespace Ice public void load(string file) { -#if UNITY - throw new FeatureNotSupportedException("File I/O not supported in UNITY build"); -#else -# if !SILVERLIGHT - if(IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows && - (file.StartsWith("HKLM\\", StringComparison.Ordinal))) + if(file.StartsWith("HKLM\\", StringComparison.Ordinal)) { RegistryKey iceKey = Registry.LocalMachine.OpenSubKey(file.Substring(5)); if(iceKey == null) @@ -339,7 +334,6 @@ namespace Ice } else { -# endif try { using(System.IO.StreamReader sr = new System.IO.StreamReader(file)) @@ -349,14 +343,11 @@ namespace Ice } catch(System.IO.IOException ex) { - Ice.FileException fe = new Ice.FileException(ex); + FileException fe = new FileException(ex); fe.path = file; throw fe; } -# if !SILVERLIGHT } -# endif -#endif } public Properties ice_clone_() @@ -429,7 +420,7 @@ namespace Ice } else { - _properties["Ice.ProgramName"] = new PropertyValue(System.AppDomain.CurrentDomain.FriendlyName, true); + _properties["Ice.ProgramName"] = new PropertyValue(AppDomain.CurrentDomain.FriendlyName, true); } bool loadConfigFiles = false; @@ -447,10 +438,10 @@ namespace Ice loadConfigFiles = true; string[] arr = new string[args.Length - 1]; - System.Array.Copy(args, 0, arr, 0, i); + Array.Copy(args, 0, arr, 0, i); if(i < args.Length - 1) { - System.Array.Copy(args, i + 1, arr, i, args.Length - i - 1); + Array.Copy(args, i + 1, arr, i, args.Length - i - 1); } args = arr; } @@ -648,7 +639,7 @@ namespace Ice if((state == ParseStateKey && key.Length != 0) || (state == ParseStateValue && key.Length == 0)) { - Ice.Util.getProcessLogger().warning("invalid config file entry: \"" + line + "\""); + Util.getProcessLogger().warning("invalid config file entry: \"" + line + "\""); return; } else if(key.Length == 0) @@ -662,17 +653,14 @@ namespace Ice private void loadConfig() { string val = getProperty("Ice.Config"); - -#if !COMPACT && !SILVERLIGHT if(val.Length == 0 || val.Equals("1")) { - string s = System.Environment.GetEnvironmentVariable("ICE_CONFIG"); + string s = Environment.GetEnvironmentVariable("ICE_CONFIG"); if(s != null && s.Length != 0) { val = s; } } -#endif if(val.Length > 0) { diff --git a/csharp/src/Ice/PropertyNames.cs b/csharp/src/Ice/PropertyNames.cs index 4ea6718b2dd..21456d3ec85 100644 --- a/csharp/src/Ice/PropertyNames.cs +++ b/csharp/src/Ice/PropertyNames.cs @@ -6,7 +6,7 @@ // ICE_LICENSE file included in this distribution. // // ********************************************************************** -// Generated by makeprops.py from file ./config/PropertyNames.xml, Wed Nov 2 09:46:48 2016 +// Generated by makeprops.py from file ../config/PropertyNames.xml, Fri Feb 10 17:05:23 2017 // IMPORTANT: Do not edit this file -- any edits made here will be lost! @@ -165,6 +165,7 @@ namespace IceInternal new Property(@"^Ice\.ThreadPool\.Server\.ThreadIdleTime$", false, null), new Property(@"^Ice\.ThreadPool\.Server\.ThreadPriority$", false, null), new Property(@"^Ice\.ThreadPriority$", false, null), + new Property(@"^Ice\.ToStringMode$", false, null), new Property(@"^Ice\.Trace\.Admin\.Properties$", false, null), new Property(@"^Ice\.Trace\.Admin\.Logger$", false, null), new Property(@"^Ice\.Trace\.Locator$", false, null), @@ -597,6 +598,7 @@ namespace IceInternal new Property(@"^IceGrid\.Node\.RedirectErrToOut$", false, null), new Property(@"^IceGrid\.Node\.Trace\.Activator$", false, null), new Property(@"^IceGrid\.Node\.Trace\.Adapter$", false, null), + new Property(@"^IceGrid\.Node\.Trace\.Admin$", false, null), new Property(@"^IceGrid\.Node\.Trace\.Patch$", false, null), new Property(@"^IceGrid\.Node\.Trace\.Replica$", false, null), new Property(@"^IceGrid\.Node\.Trace\.Server$", false, null), @@ -709,7 +711,6 @@ namespace IceInternal new Property(@"^IceGrid\.Registry\.Client\.ThreadPool\.ThreadPriority$", false, null), new Property(@"^IceGrid\.Registry\.Client\.MessageSizeMax$", false, null), new Property(@"^IceGrid\.Registry\.CryptPasswords$", false, null), - new Property(@"^IceGrid\.Registry\.Data$", false, null), new Property(@"^IceGrid\.Registry\.DefaultTemplates$", false, null), new Property(@"^IceGrid\.Registry\.Discovery\.ACM\.Timeout$", false, null), new Property(@"^IceGrid\.Registry\.Discovery\.ACM\.Heartbeat$", false, null), @@ -790,6 +791,8 @@ namespace IceInternal new Property(@"^IceGrid\.Registry\.Internal\.ThreadPool\.ThreadIdleTime$", false, null), new Property(@"^IceGrid\.Registry\.Internal\.ThreadPool\.ThreadPriority$", false, null), new Property(@"^IceGrid\.Registry\.Internal\.MessageSizeMax$", false, null), + new Property(@"^IceGrid\.Registry\.LMDB\.MapSize$", false, null), + new Property(@"^IceGrid\.Registry\.LMDB\.Path$", false, null), new Property(@"^IceGrid\.Registry\.NodeSessionTimeout$", false, null), new Property(@"^IceGrid\.Registry\.PermissionsVerifier\.EndpointSelection$", false, null), new Property(@"^IceGrid\.Registry\.PermissionsVerifier\.ConnectionCached$", false, null), @@ -891,6 +894,7 @@ namespace IceInternal new Property(@"^IceGrid\.Registry\.SSLPermissionsVerifier\.CollocationOptimized$", false, null), new Property(@"^IceGrid\.Registry\.SSLPermissionsVerifier\.Context\.[^\s]+$", false, null), new Property(@"^IceGrid\.Registry\.SSLPermissionsVerifier$", false, null), + new Property(@"^IceGrid\.Registry\.Trace\.Admin$", false, null), new Property(@"^IceGrid\.Registry\.Trace\.Application$", false, null), new Property(@"^IceGrid\.Registry\.Trace\.Adapter$", false, null), new Property(@"^IceGrid\.Registry\.Trace\.Locator$", false, null), @@ -904,13 +908,6 @@ namespace IceInternal new Property(@"^IceGrid\.Registry\.Trace\.Topic$", false, null), new Property(@"^IceGrid\.Registry\.Trace\.TopicManager$", false, null), new Property(@"^IceGrid\.Registry\.UserAccounts$", false, null), - new Property(@"^IceGrid\.SQL\.DatabaseType$", false, null), - new Property(@"^IceGrid\.SQL\.EncodingVersion$", false, null), - new Property(@"^IceGrid\.SQL\.HostName$", false, null), - new Property(@"^IceGrid\.SQL\.Port$", false, null), - new Property(@"^IceGrid\.SQL\.DatabaseName$", false, null), - new Property(@"^IceGrid\.SQL\.UserName$", false, null), - new Property(@"^IceGrid\.SQL\.Password$", false, null), null }; @@ -987,10 +984,8 @@ namespace IceInternal new Property(@"^IceSSL\.EntropyDaemon$", false, null), new Property(@"^IceSSL\.FindCert$", false, null), new Property(@"^IceSSL\.FindCert\.[^\s]+$", true, null), - new Property(@"^IceSSL\.ImportCert\.[^\s]+$", true, null), new Property(@"^IceSSL\.InitOpenSSL$", false, null), new Property(@"^IceSSL\.KeyFile$", true, null), - new Property(@"^IceSSL\.KeySet$", true, null), new Property(@"^IceSSL\.Keychain$", false, null), new Property(@"^IceSSL\.KeychainPassword$", false, null), new Property(@"^IceSSL\.Keystore$", false, null), @@ -999,7 +994,6 @@ namespace IceInternal new Property(@"^IceSSL\.Password$", false, null), new Property(@"^IceSSL\.PasswordCallback$", false, null), new Property(@"^IceSSL\.PasswordRetryMax$", false, null), - new Property(@"^IceSSL\.PersistKeySet$", true, null), new Property(@"^IceSSL\.Protocols$", false, null), new Property(@"^IceSSL\.ProtocolVersionMax$", false, null), new Property(@"^IceSSL\.ProtocolVersionMin$", false, null), @@ -1026,6 +1020,13 @@ namespace IceInternal null }; + public static Property[] IceBTProps = + { + new Property(@"^IceBT\.RcvSize$", false, null), + new Property(@"^IceBT\.SndSize$", false, null), + null + }; + public static Property[] Glacier2Props = { new Property(@"^Glacier2\.AddConnectionContext$", false, null), @@ -1225,6 +1226,7 @@ namespace IceInternal IcePatch2ClientProps, IceSSLProps, IceStormAdminProps, + IceBTProps, Glacier2Props, Glacier2CryptPermissionsVerifierProps, FreezeProps, @@ -1245,6 +1247,7 @@ namespace IceInternal "IcePatch2Client", "IceSSL", "IceStormAdmin", + "IceBT", "Glacier2", "Glacier2CryptPermissionsVerifier", "Freeze", diff --git a/csharp/src/Ice/Protocol.cs b/csharp/src/Ice/Protocol.cs index 105a610c4a4..651079964ce 100644 --- a/csharp/src/Ice/Protocol.cs +++ b/csharp/src/Ice/Protocol.cs @@ -9,8 +9,7 @@ namespace IceInternal { - - sealed class Protocol + public sealed class Protocol { // // Size of the Ice protocol header @@ -29,8 +28,7 @@ namespace IceInternal // // The magic number at the front of each message // - internal static readonly byte[] magic - = new byte[] { (byte)0x49, (byte)0x63, (byte)0x65, (byte)0x50 }; // 'I', 'c', 'e', 'P' + internal static readonly byte[] magic = new byte[] { 0x49, 0x63, 0x65, 0x50 }; // 'I', 'c', 'e', 'P' // // The current Ice protocol and encoding version @@ -42,6 +40,16 @@ namespace IceInternal internal const byte encodingMajor = 1; internal const byte encodingMinor = 1; + + public const byte OPTIONAL_END_MARKER = 0xFF; + + public const byte FLAG_HAS_TYPE_ID_STRING = (1<<0); + public const byte FLAG_HAS_TYPE_ID_INDEX = (1<<1); + public const byte FLAG_HAS_TYPE_ID_COMPACT = (1<<1 | 1<<0); + public const byte FLAG_HAS_OPTIONAL_MEMBERS = (1<<2); + public const byte FLAG_HAS_INDIRECTION_TABLE = (1<<3); + public const byte FLAG_HAS_SLICE_SIZE = (1<<4); + public const byte FLAG_IS_LAST_SLICE = (1<<5); // // The Ice protocol message types @@ -54,37 +62,34 @@ namespace IceInternal internal static readonly byte[] requestHdr = new byte[] { - IceInternal.Protocol.magic[0], IceInternal.Protocol.magic[1], IceInternal.Protocol.magic[2], - IceInternal.Protocol.magic[3], - IceInternal.Protocol.protocolMajor, IceInternal.Protocol.protocolMinor, - IceInternal.Protocol.protocolEncodingMajor, IceInternal.Protocol.protocolEncodingMinor, - IceInternal.Protocol.requestMsg, - (byte)0, // Compression status. - (byte)0, (byte)0, (byte)0, (byte)0, // Message size (placeholder). - (byte)0, (byte)0, (byte)0, (byte)0 // Request ID (placeholder). + magic[0], magic[1], magic[2], magic[3], + protocolMajor, protocolMinor, + protocolEncodingMajor, protocolEncodingMinor, + requestMsg, + 0, // Compression status. + 0, 0, 0, 0, // Message size (placeholder). + 0, 0, 0, 0 // Request ID (placeholder). }; internal static readonly byte[] requestBatchHdr = new byte[] { - IceInternal.Protocol.magic[0], IceInternal.Protocol.magic[1], IceInternal.Protocol.magic[2], - IceInternal.Protocol.magic[3], - IceInternal.Protocol.protocolMajor, IceInternal.Protocol.protocolMinor, - IceInternal.Protocol.protocolEncodingMajor, IceInternal.Protocol.protocolEncodingMinor, - IceInternal.Protocol.requestBatchMsg, - (byte)0, // Compression status. - (byte)0, (byte)0, (byte)0, (byte)0, // Message size (placeholder). - (byte)0, (byte)0, (byte)0, (byte)0 // Number of requests in batch (placeholder). + magic[0], magic[1], magic[2], magic[3], + protocolMajor, protocolMinor, + protocolEncodingMajor, protocolEncodingMinor, + requestBatchMsg, + 0, // Compression status. + 0, 0, 0, 0, // Message size (placeholder). + 0, 0, 0, 0 // Number of requests in batch (placeholder). }; internal static readonly byte[] replyHdr = new byte[] { - IceInternal.Protocol.magic[0], IceInternal.Protocol.magic[1], IceInternal.Protocol.magic[2], - IceInternal.Protocol.magic[3], - IceInternal.Protocol.protocolMajor, IceInternal.Protocol.protocolMinor, - IceInternal.Protocol.protocolEncodingMajor, IceInternal.Protocol.protocolEncodingMinor, - IceInternal.Protocol.replyMsg, - (byte)0, // Compression status. - (byte)0, (byte)0, (byte)0, (byte)0 // Message size (placeholder). + magic[0], magic[1], magic[2], magic[3], + protocolMajor, protocolMinor, + protocolEncodingMajor, protocolEncodingMinor, + replyMsg, + 0, // Compression status. + 0, 0, 0, 0 // Message size (placeholder). }; internal static void @@ -96,7 +101,7 @@ namespace IceInternal } } - internal static void + public static void checkSupportedProtocolEncoding(Ice.EncodingVersion v) { if(v.major != protocolEncodingMajor || v.minor > protocolEncodingMinor) diff --git a/csharp/src/Ice/ProtocolInstance.cs b/csharp/src/Ice/ProtocolInstance.cs index 809f3fdce77..6cd500e44f1 100644 --- a/csharp/src/Ice/ProtocolInstance.cs +++ b/csharp/src/Ice/ProtocolInstance.cs @@ -7,11 +7,10 @@ // // ********************************************************************** +using System.Net; + namespace IceInternal { - using System.Net; - using System.Collections.Generic; - public class ProtocolInstance { public ProtocolInstance(Ice.Communicator communicator, short type, string protocol, bool secure) @@ -113,13 +112,11 @@ namespace IceInternal return instance_.messageSizeMax(); } -#if !SILVERLIGHT public void resolve(string host, int port, Ice.EndpointSelectionType type, IPEndpointI endpt, EndpointI_connectors callback) { instance_.endpointHostResolver().resolve(host, port, type, endpt, callback); } -#endif public BufSizeWarnInfo getBufSizeWarn(short type) { diff --git a/csharp/src/Ice/ProtocolPluginFacade.cs b/csharp/src/Ice/ProtocolPluginFacade.cs index 0aae07fcbfe..53530099625 100644 --- a/csharp/src/Ice/ProtocolPluginFacade.cs +++ b/csharp/src/Ice/ProtocolPluginFacade.cs @@ -38,7 +38,7 @@ namespace IceInternal public ProtocolPluginFacadeI(Ice.Communicator communicator) { _communicator = communicator; - _instance = IceInternal.Util.getInstance(communicator); + _instance = Util.getInstance(communicator); } // diff --git a/csharp/src/Ice/Proxy.cs b/csharp/src/Ice/Proxy.cs index 09032d8b4fc..a26a0559b91 100644 --- a/csharp/src/Ice/Proxy.cs +++ b/csharp/src/Ice/Proxy.cs @@ -8,31 +8,35 @@ // ********************************************************************** using System; -using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Runtime.Serialization; +using System.Threading; +using System.Threading.Tasks; +using System.ComponentModel; + using IceUtilInternal; -using Ice.Instrumentation; +using IceInternal; namespace Ice { /// <summary> /// Delegate for a successful <code>ice_isA</code> invocation. - /// <param name="ret__">True if the remote object supports the type, false otherwise.</param> + /// <param name="ret">True if the remote object supports the type, false otherwise.</param> /// </summary> - public delegate void Callback_Object_ice_isA(bool ret__); + public delegate void Callback_Object_ice_isA(bool ret); /// <summary> /// Delegate for a successful <code>ice_ids</code> invocation. - /// <param name="ret__">The array of Slice type ids supported by the remote object.</param> + /// <param name="ret">The array of Slice type ids supported by the remote object.</param> /// </summary> - public delegate void Callback_Object_ice_ids(string[] ret__); + public delegate void Callback_Object_ice_ids(string[] ret); /// <summary> /// Delegate for a successful <code>ice_id</code> invocation. - /// <param name="ret__">The Slice type id of the most-derived interface supported by the remote object.</param> + /// <param name="ret">The Slice type id of the most-derived interface supported by the remote object.</param> /// </summary> - public delegate void Callback_Object_ice_id(string ret__); + public delegate void Callback_Object_ice_id(string ret); /// <summary> /// Delegate for a successful <code>ice_ping</code> invocation. @@ -41,17 +45,54 @@ namespace Ice /// <summary> /// Delegate for a successful <code>ice_invoke</code> invocation. - /// <param name="ret__">True if the invocation succeeded, or false if the invocation + /// <param name="ret">True if the invocation succeeded, or false if the invocation /// raised a user exception.</param> /// <param name="outEncaps">The encoded out-parameters or user exception.</param> /// </summary> - public delegate void Callback_Object_ice_invoke(bool ret__, byte[] outEncaps); + public delegate void Callback_Object_ice_invoke(bool ret, byte[] outEncaps); /// <summary> /// Delegate for a successful <code>ice_getConnection</code> invocation. - /// <param name="ret__">The connection used by the proxy.</param> + /// <param name="ret">The connection used by the proxy.</param> /// </summary> - public delegate void Callback_Object_ice_getConnection(Connection ret__); + public delegate void Callback_Object_ice_getConnection(Connection ret); + + /// <summary> + /// Value type to allow differenciate between a context that is explicity set to + /// empty (empty or null dictionary) and a context that has non been set. + /// </summary> + public struct OptionalContext + { + private OptionalContext(Dictionary<string, string> ctx) + { + _ctx = ctx == null ? _emptyContext : ctx; + } + + /// <summary> + /// Implicit conversion between Dictionary<string, string> and + /// OptionalContext. + /// </summary> + /// <param name="ctx">Dictionary to convert.</param> + /// <returns>OptionalContext value representing the dictionary</returns> + public static implicit operator OptionalContext(Dictionary<string, string> ctx) + { + return new OptionalContext(ctx); + } + + /// <summary> + /// Implicit conversion between OptionalContext and + /// Dictionary<string, string> + /// </summary> + /// <param name="value">OptionalContext value to convert</param> + /// <returns>The Dictionary object.</returns> + public static implicit operator Dictionary<string, string>(OptionalContext value) + { + return value._ctx; + } + + private Dictionary<string, string> _ctx; + static private Dictionary<string, string> _emptyContext = new Dictionary<string, string>(); + } /// <summary> /// Base interface of all object proxies. @@ -67,210 +108,204 @@ namespace Ice /// <summary> /// Tests whether this object supports a specific Slice interface. /// </summary> - /// <param name="id__">The type ID of the Slice interface to test against.</param> - /// <returns>True if the target object has the interface specified by id__ or derives - /// from the interface specified by id__.</returns> - bool ice_isA(string id__); - - /// <summary> - /// Tests whether this object supports a specific Slice interface. - /// </summary> - /// <param name="id__">The type ID of the Slice interface to test against.</param> - /// <param name="context__">The context dictionary for the invocation.</param> - /// <returns>True if the target object has the interface specified by id__ or derives - /// from the interface specified by id__.</returns> - bool ice_isA(string id__, Dictionary<string, string> context__); + /// <param name="id">The type ID of the Slice interface to test against.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <returns>True if the target object has the interface specified by id or derives + /// from the interface specified by id.</returns> + bool ice_isA(string id, OptionalContext context = new OptionalContext()); /// <summary> /// Tests whether this object supports a specific Slice interface. /// </summary> /// <param name="id">The type ID of the Slice interface to test against.</param> - /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_isA> begin_ice_isA(string id); - + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + Task<bool> ice_isAAsync(string id, + OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()); /// <summary> /// Tests whether this object supports a specific Slice interface. /// </summary> /// <param name="id">The type ID of the Slice interface to test against.</param> - /// <param name="context__">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_isA> begin_ice_isA(string id, Dictionary<string, string> context__); + AsyncResult begin_ice_isA(string id, AsyncCallback callback, object cookie); /// <summary> /// Tests whether this object supports a specific Slice interface. /// </summary> /// <param name="id">The type ID of the Slice interface to test against.</param> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_isA(string id, AsyncCallback cb__, object cookie__); + AsyncResult begin_ice_isA(string id, OptionalContext context, AsyncCallback callback, object cookie); /// <summary> /// Tests whether this object supports a specific Slice interface. /// </summary> /// <param name="id">The type ID of the Slice interface to test against.</param> - /// <param name="context__">The context dictionary for the invocation.</param> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_isA(string id, Dictionary<string, string> context__, AsyncCallback cb__, object cookie__); + AsyncResult<Callback_Object_ice_isA> begin_ice_isA(string id, OptionalContext context = new OptionalContext()); /// <summary> /// Tests whether this object supports a specific Slice interface. /// </summary> - /// <param name="r__">The asynchronous result object returned by <code>begin_ice_isA</code>.</param> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_isA</code>.</param> /// <returns>True if the object supports the Slice interface, false otherwise.</returns> - bool end_ice_isA(AsyncResult r__); - - /// <summary> - /// Tests whether the target object of this proxy can be reached. - /// </summary> - void ice_ping(); + bool end_ice_isA(AsyncResult result); /// <summary> /// Tests whether the target object of this proxy can be reached. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> - void ice_ping(Dictionary<string, string> context__); + /// <param name="context">The context dictionary for the invocation.</param> + void ice_ping(OptionalContext context = new OptionalContext()); /// <summary> /// Tests whether the target object of this proxy can be reached. /// </summary> - /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_ping> begin_ice_ping(); + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + Task ice_pingAsync(OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()); /// <summary> /// Tests whether the target object of this proxy can be reached. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_ping> begin_ice_ping(Dictionary<string, string> context__); + AsyncResult begin_ice_ping(AsyncCallback callback, object cookie); /// <summary> /// Tests whether the target object of this proxy can be reached. /// </summary> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_ping(AsyncCallback cb__, object cookie__); + AsyncResult begin_ice_ping(OptionalContext context, AsyncCallback callback, object cookie); /// <summary> /// Tests whether the target object of this proxy can be reached. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_ping(Dictionary<string, string> context__, AsyncCallback cb__, object cookie__); + AsyncResult<Callback_Object_ice_ping> begin_ice_ping(OptionalContext context = new OptionalContext()); /// <summary> /// Tests whether the target object of this proxy can be reached. /// </summary> - /// <param name="r__">The asynchronous result object returned by <code>begin_ice_ping</code>.</param> - void end_ice_ping(AsyncResult r__); - - /// <summary> - /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. - /// </summary> - /// <returns>The Slice type IDs of the interfaces supported by the target object, in base-to-derived - /// order. The first element of the returned array is always ::Ice::Object.</returns> - string[] ice_ids(); + /// <param name="result">The asynchronous result object returned by <code>begin_ice_ping</code>.</param> + void end_ice_ping(AsyncResult result); /// <summary> /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>The Slice type IDs of the interfaces supported by the target object, in base-to-derived /// order. The first element of the returned array is always ::Ice::Object.</returns> - string[] ice_ids(Dictionary<string, string> context__); + string[] ice_ids(OptionalContext context = new OptionalContext()); /// <summary> /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. /// </summary> - /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_ids> begin_ice_ids(); + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + Task<string[]> ice_idsAsync(OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()); /// <summary> /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_ids> begin_ice_ids(Dictionary<string, string> context__); + AsyncResult begin_ice_ids(AsyncCallback callback, object cookie); /// <summary> /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. /// </summary> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_ids(AsyncCallback cb__, object cookie__); + AsyncResult begin_ice_ids(OptionalContext context, AsyncCallback callback, object cookie); /// <summary> /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_ids(Dictionary<string, string> context__, AsyncCallback cb__, object cookie__); + AsyncResult<Callback_Object_ice_ids> begin_ice_ids(OptionalContext context = new OptionalContext()); /// <summary> /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. /// </summary> - /// <param name="r__">The asynchronous result object returned by <code>begin_ice_ids</code>.</param> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_ids</code>.</param> /// <returns>The Slice type IDs of the interfaces supported by the target object, in base-to-derived /// order. The first element of the returned array is always ::Ice::Object.</returns> - string[] end_ice_ids(AsyncResult r__); - - /// <summary> - /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. - /// </summary> - /// <returns>The Slice type ID of the most-derived interface.</returns> - string ice_id(); + string[] end_ice_ids(AsyncResult result); /// <summary> /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>The Slice type ID of the most-derived interface.</returns> - string ice_id(Dictionary<string, string> context__); + string ice_id(OptionalContext context = new OptionalContext()); /// <summary> /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. /// </summary> - /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_id> begin_ice_id(); + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + Task<string> ice_idAsync(OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()); /// <summary> /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_id> begin_ice_id(Dictionary<string, string> context__); + AsyncResult begin_ice_id(AsyncCallback callback, object cookie); /// <summary> /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. /// </summary> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_id(AsyncCallback cb__, object cookie__); + AsyncResult begin_ice_id(OptionalContext context, AsyncCallback callback, object cookie); /// <summary> /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_id(Dictionary<string, string> context__, AsyncCallback cb__, object cookie__); + AsyncResult<Callback_Object_ice_id> begin_ice_id(OptionalContext context = new OptionalContext()); /// <summary> /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. /// </summary> - /// <param name="r__">The asynchronous result object returned by <code>begin_ice_id</code>.</param> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_id</code>.</param> /// <returns>The Slice type ID of the most-derived interface.</returns> - string end_ice_id(AsyncResult r__); + string end_ice_id(AsyncResult result); /// <summary> /// Invokes an operation dynamically. @@ -280,29 +315,14 @@ namespace Ice /// <param name="inEncaps">The encoded in-parameters for the operation.</param> /// <param name="outEncaps">The encoded out-paramaters and return value /// for the operation. The return value follows any out-parameters.</param> - /// <returns>If the operation completed successfully, the return value - /// is true. If the operation raises a user exception, - /// the return value is false; in this case, outEncaps - /// contains the encoded user exception. If the operation raises a run-time exception, - /// it throws it directly.</returns> - bool ice_invoke(string operation, OperationMode mode, byte[] inEncaps, out byte[] outEncaps); - - /// <summary> - /// Invokes an operation dynamically. - /// </summary> - /// <param name="operation">The name of the operation to invoke.</param> - /// <param name="mode">The operation mode (normal or idempotent).</param> - /// <param name="inEncaps">The encoded in-parameters for the operation.</param> - /// <param name="outEncaps">The encoded out-paramaters and return value - /// for the operation. The return value follows any out-parameters.</param> - /// <param name="context__">The context dictionary for the invocation.</param> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>If the operation completed successfully, the return value /// is true. If the operation raises a user exception, /// the return value is false; in this case, outEncaps /// contains the encoded user exception. If the operation raises a run-time exception, /// it throws it directly.</returns> bool ice_invoke(string operation, OperationMode mode, byte[] inEncaps, out byte[] outEncaps, - Dictionary<string, string> context__); + OptionalContext context = new OptionalContext()); /// <summary> /// Invokes an operation dynamically. @@ -310,9 +330,17 @@ namespace Ice /// <param name="operation">The name of the operation to invoke.</param> /// <param name="mode">The operation mode (normal or idempotent).</param> /// <param name="inEncaps">The encoded in-parameters for the operation.</param> - /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_invoke> begin_ice_invoke(string operation, OperationMode mode, - byte[] inEncaps); + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + Task<Object_Ice_invokeResult> + ice_invokeAsync(string operation, + OperationMode mode, + byte[] inEncaps, + OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()); /// <summary> /// Invokes an operation dynamically. @@ -320,11 +348,14 @@ namespace Ice /// <param name="operation">The name of the operation to invoke.</param> /// <param name="mode">The operation mode (normal or idempotent).</param> /// <param name="inEncaps">The encoded in-parameters for the operation.</param> - /// <param name="context__">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_invoke> begin_ice_invoke(string operation, OperationMode mode, - byte[] inEncaps, - Dictionary<string, string> context__); + AsyncResult begin_ice_invoke(string operation, + OperationMode mode, + byte[] inEncaps, + AsyncCallback callback, + object cookie); /// <summary> /// Invokes an operation dynamically. @@ -332,11 +363,16 @@ namespace Ice /// <param name="operation">The name of the operation to invoke.</param> /// <param name="mode">The operation mode (normal or idempotent).</param> /// <param name="inEncaps">The encoded in-parameters for the operation.</param> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_invoke(string operation, OperationMode mode, byte[] inEncaps, AsyncCallback cb__, - object cookie__); + AsyncResult begin_ice_invoke(string operation, + OperationMode mode, + byte[] inEncaps, + OptionalContext context, + AsyncCallback callback, + object cookie); /// <summary> /// Invokes an operation dynamically. @@ -344,24 +380,24 @@ namespace Ice /// <param name="operation">The name of the operation to invoke.</param> /// <param name="mode">The operation mode (normal or idempotent).</param> /// <param name="inEncaps">The encoded in-parameters for the operation.</param> - /// <param name="context__">The context dictionary for the invocation.</param> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_invoke(string operation, OperationMode mode, byte[] inEncaps, - Dictionary<string, string> context__, AsyncCallback cb__, object cookie__); + AsyncResult<Callback_Object_ice_invoke> begin_ice_invoke(string operation, + OperationMode mode, + byte[] inEncaps, + OptionalContext context = new OptionalContext()); /// <summary> /// Completes a dynamic invocation. /// </summary> /// <param name="outEncaps">The encoded out parameters or user exception.</param> - /// <param name="r__">The asynchronous result object returned by <code>begin_ice_invoke</code>.</param> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_invoke</code>.</param> /// <returns>If the operation completed successfully, the return value /// is true. If the operation raises a user exception, /// the return value is false; in this case, outEncaps /// contains the encoded user exception. If the operation raises a run-time exception, /// it throws it directly.</returns> - bool end_ice_invoke(out byte[] outEncaps, AsyncResult r__); + bool end_ice_invoke(out byte[] outEncaps, AsyncResult result); /// <summary> /// Returns the identity embedded in this proxy. @@ -502,11 +538,11 @@ namespace Ice /// </summary> /// <param name="e">The encoding version to use to marshal requests parameters.</param> /// <returns>The new proxy with the specified encoding version.</returns> - ObjectPrx ice_encodingVersion(Ice.EncodingVersion e); + ObjectPrx ice_encodingVersion(EncodingVersion e); /// <summary>Returns the encoding version used to marshal requests parameters.</summary> /// <returns>The encoding version.</returns> - Ice.EncodingVersion ice_getEncodingVersion(); + EncodingVersion ice_getEncodingVersion(); /// <summary> /// Returns whether this proxy prefers secure endpoints. @@ -529,27 +565,27 @@ namespace Ice /// </summary> /// <returns>The router for the proxy. If no router is configured for the proxy, the return value /// is null.</returns> - Ice.RouterPrx ice_getRouter(); + RouterPrx ice_getRouter(); /// <summary> /// Creates a new proxy that is identical to this proxy, except for the router. /// </summary> /// <param name="router">The router for the new proxy.</param> /// <returns>The new proxy with the specified router.</returns> - ObjectPrx ice_router(Ice.RouterPrx router); + ObjectPrx ice_router(RouterPrx router); /// <summary> /// Returns the locator for this proxy. /// </summary> /// <returns>The locator for this proxy. If no locator is configured, the return value is null.</returns> - Ice.LocatorPrx ice_getLocator(); + LocatorPrx ice_getLocator(); /// <summary> /// Creates a new proxy that is identical to this proxy, except for the locator. /// </summary> /// <param name="locator">The locator for the new proxy.</param> /// <returns>The new proxy with the specified locator.</returns> - ObjectPrx ice_locator(Ice.LocatorPrx locator); + ObjectPrx ice_locator(LocatorPrx locator); /// <summary> /// Returns whether this proxy uses collocation optimization. @@ -664,23 +700,32 @@ namespace Ice /// <summary> /// Asynchronously gets the connection for this proxy. /// </summary> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + Task<Connection> ice_getConnectionAsync(IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()); + + /// <summary> + /// Asynchronously gets the connection for this proxy. + /// </summary> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult<Callback_Object_ice_getConnection> begin_ice_getConnection(); + AsyncResult begin_ice_getConnection(AsyncCallback callback, object cookie); /// <summary> /// Asynchronously gets the connection for this proxy. /// </summary> - /// <param name="cb__">A callback to be invoked when the invocation completes.</param> - /// <param name="cookie__">Application-specific data to be stored in the result.</param> /// <returns>An asynchronous result object.</returns> - AsyncResult begin_ice_getConnection(AsyncCallback cb__, object cookie__); + AsyncResult<Callback_Object_ice_getConnection> begin_ice_getConnection(); /// <summary> /// Asynchronously gets the connection for this proxy. /// </summary> - /// <param name="r__">The asynchronous result object returned by <code>begin_ice_getConnection</code>.</param> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_getConnection</code>.</param> /// <returns>The connection.</returns> - Connection end_ice_getConnection(AsyncResult r__); + Connection end_ice_getConnection(AsyncResult result); /// <summary> /// Returns the cached Connection for this proxy. If the proxy does not yet have an established @@ -693,21 +738,104 @@ namespace Ice Connection ice_getCachedConnection(); /// <summary> - /// Flushes any pending batched requests for this communicator. The call blocks until the flush is complete. + /// Flushes any pending batched requests for this proxy. The call blocks until the flush is complete. /// </summary> void ice_flushBatchRequests(); - AsyncResult begin_ice_flushBatchRequests(); - AsyncResult begin_ice_flushBatchRequests(AsyncCallback cb__, object cookie__); + /// <summary> + /// Asynchronously flushes any pending batched requests for this proxy. + /// </summary> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + Task ice_flushBatchRequestsAsync(IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()); + + /// <summary> + /// Asynchronously flushes any pending batched requests for this proxy. + /// </summary> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + AsyncResult begin_ice_flushBatchRequests(AsyncCallback callback = null, object cookie = null); + + /// <summary> + /// Flushes any pending batched requests for this proxy. The call blocks until the flush is complete. + /// </summary> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_getConnection</code>.</param> + void end_ice_flushBatchRequests(AsyncResult result); - void end_ice_flushBatchRequests(AsyncResult r__); + /// <summary> + /// Write a proxy to the output stream. + /// </summary> + /// <param name="os">Output stream object to write the proxy.</param> + [EditorBrowsable(EditorBrowsableState.Never)] + void iceWrite(OutputStream os); } /// <summary> + /// Represent the result of the ice_invokeAsync operation + /// </summary> + public struct Object_Ice_invokeResult + { + public Object_Ice_invokeResult(bool returnValue, byte[] outEncaps) + { + this.returnValue = returnValue; + this.outEncaps = outEncaps; + } + + /// <summary> + /// If the operation completed successfully, the return value + /// is true. If the operation raises a user exception, + /// the return value is false; in this case, outEncaps + /// contains the encoded user exception. + /// </summary> + public bool returnValue; + + /// <summary> + /// The encoded out-paramaters and return value for the operation. + /// The return value follows any out-parameters. If returnValue is + /// false it contains the encoded user exception. + /// </summary> + public byte[] outEncaps; + }; + + /// <summary> /// Base class of all object proxies. /// </summary> - public class ObjectPrxHelperBase : ObjectPrx + [Serializable] + public class ObjectPrxHelperBase : ObjectPrx, ISerializable { + public ObjectPrxHelperBase() + { + } + + public ObjectPrxHelperBase(SerializationInfo info, StreamingContext context) + { + Instance instance = null; + + if(context.Context is Communicator) + { + instance = IceInternal.Util.getInstance(context.Context as Communicator); + } + else if(context.Context is Instance) + { + instance = context.Context as Instance; + } + else + { + throw new ArgumentException("Cannot deserialize proxy: Ice.Communicator not found in StreamingContext"); + } + + var proxy = (ObjectPrxHelperBase)instance.proxyFactory().stringToProxy(info.GetString("proxy")); + _reference = proxy._reference; + Debug.Assert(proxy._requestHandler == null); + } + + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue("proxy", ToString()); + } + /// <summary> /// Returns a hash code for this proxy. /// </summary> @@ -738,553 +866,464 @@ namespace Ice /// <summary> /// Tests whether this object supports a specific Slice interface. /// </summary> - /// <param name="id__">The type ID of the Slice interface to test against.</param> - /// <returns>True if the target object has the interface specified by id__ or derives - /// from the interface specified by id__.</returns> - public bool ice_isA(string id__) + /// <param name="id">The type ID of the Slice interface to test against.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <returns>True if the target object has the interface specified by id or derives + /// from the interface specified by id.</returns> + public bool ice_isA(string id, OptionalContext context = new OptionalContext()) { - return ice_isA(id__, null, false); + try + { + return iceI_ice_isAAsync(id, context, null, CancellationToken.None, true).Result; + } + catch(AggregateException ex) + { + throw ex.InnerException; + } } /// <summary> /// Tests whether this object supports a specific Slice interface. /// </summary> - /// <param name="id__">The type ID of the Slice interface to test against.</param> - /// <param name="context__">The context dictionary for the invocation.</param> - /// <returns>True if the target object has the interface specified by id__ or derives - /// from the interface specified by id__.</returns> - public bool ice_isA(string id__, Dictionary<string, string> context__) - { - return ice_isA(id__, context__, true); - } - - private bool ice_isA(string id__, Dictionary<string, string> context__, bool explicitCtx__) + /// <param name="id">The type ID of the Slice interface to test against.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + public Task<bool> ice_isAAsync(string id, + OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()) { - checkTwowayOnly__(__ice_isA_name); - return end_ice_isA(begin_ice_isA(id__, context__, explicitCtx__, true, null, null)); + return iceI_ice_isAAsync(id, context, progress, cancel, false); } - public AsyncResult<Callback_Object_ice_isA> begin_ice_isA(string id) + private Task<bool> + iceI_ice_isAAsync(string id, OptionalContext context, IProgress<bool> progress, CancellationToken cancel, + bool synchronous) { - return begin_ice_isA(id, null, false, false, null, null); + var completed = new OperationTaskCompletionCallback<bool>(progress, cancel); + iceI_ice_isA(id, context, completed, synchronous); + return completed.Task; } - public AsyncResult<Callback_Object_ice_isA> begin_ice_isA(string id, Dictionary<string, string> context__) + /// <summary> + /// Tests whether this object supports a specific Slice interface. + /// </summary> + /// <param name="id">The type ID of the Slice interface to test against.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult begin_ice_isA(string id, AsyncCallback callback, object cookie) { - return begin_ice_isA(id, context__, true, false, null, null); + return iceI_begin_ice_isA(id, new OptionalContext(), callback, cookie, false); } - public AsyncResult begin_ice_isA(string id, AsyncCallback cb__, object cookie__) + /// <summary> + /// Tests whether this object supports a specific Slice interface. + /// </summary> + /// <param name="id">The type ID of the Slice interface to test against.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult begin_ice_isA(string id, OptionalContext context, AsyncCallback callback, object cookie) { - return begin_ice_isA(id, null, false, false, cb__, cookie__); + return iceI_begin_ice_isA(id, context, callback, cookie, false); } - public AsyncResult begin_ice_isA(string id, Dictionary<string, string> context__, AsyncCallback cb__, - object cookie__) + /// <summary> + /// Tests whether this object supports a specific Slice interface. + /// </summary> + /// <param name="id">The type ID of the Slice interface to test against.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult<Callback_Object_ice_isA> + begin_ice_isA(string id, OptionalContext context = new OptionalContext()) { - return begin_ice_isA(id, context__, true, false, cb__, cookie__); + return iceI_begin_ice_isA(id, context, null, null, false); } - internal const string __ice_isA_name = "ice_isA"; + private const string _ice_isA_name = "ice_isA"; - public bool end_ice_isA(AsyncResult r__) + /// <summary> + /// Tests whether this object supports a specific Slice interface. + /// </summary> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_isA</code>.</param> + /// <returns>True if the object supports the Slice interface, false otherwise.</returns> + public bool end_ice_isA(AsyncResult result) { - IceInternal.OutgoingAsync outAsync__ = IceInternal.OutgoingAsync.check(r__, this, __ice_isA_name); - try - { - if(!outAsync__.wait()) - { - try - { - outAsync__.throwUserException(); - } - catch(Ice.UserException ex__) - { - throw new Ice.UnknownUserException(ex__.ice_name(), ex__); - } - } - bool ret__; - IceInternal.BasicStream is__ = outAsync__.startReadParams(); - ret__ = is__.readBool(); - outAsync__.endReadParams(); - return ret__; - } - finally - { - if(outAsync__ != null) - { - outAsync__.cacheMessageBuffers(); - } - } + var resultI = AsyncResultI.check(result, this, _ice_isA_name); + return ((OutgoingAsyncT<bool>)resultI.OutgoingAsync).getResult(resultI.wait()); } - private AsyncResult<Callback_Object_ice_isA> begin_ice_isA(string id, - Dictionary<string, string> context__, - bool explicitCtx__, - bool synchronous__, - Ice.AsyncCallback cb__, - object cookie__) + private AsyncResult<Callback_Object_ice_isA> + iceI_begin_ice_isA(string id, Dictionary<string, string> context, AsyncCallback callback, object cookie, + bool synchronous) { - checkAsyncTwowayOnly__(__ice_isA_name); - - IceInternal.TwowayOutgoingAsync<Callback_Object_ice_isA> result__ = - getTwowayOutgoingAsync<Callback_Object_ice_isA>(__ice_isA_name, ice_isA_completed__, cookie__); - if(cb__ != null) - { - result__.whenCompletedWithAsyncCallback(cb__); - } - - try - { - result__.prepare(__ice_isA_name, OperationMode.Nonmutating, context__, explicitCtx__, synchronous__); - IceInternal.BasicStream os__ = result__.startWriteParams(FormatType.DefaultFormat); - os__.writeString(id); - result__.endWriteParams(); - result__.invoke(); - } - catch(Ice.Exception ex__) - { - result__.abort(ex__); - } - return result__; - } - - protected IceInternal.TwowayOutgoingAsync<T> - getTwowayOutgoingAsync<T>(string operation, IceInternal.ProxyTwowayCallback<T> cb, - object cookie) { - bool haveEntry = false; - IceInternal.BasicStream iss = null; - IceInternal.BasicStream os = null; - - if(_reference.getInstance().cacheMessageBuffers() > 0) - { - lock(this) + var completed = new OperationAsyncResultCompletionCallback<Callback_Object_ice_isA, bool>( + (Callback_Object_ice_isA cb, bool result) => { - if(_streamCache != null && _streamCache.Count > 0) + if(cb != null) { - haveEntry = true; - iss = _streamCache.First.Value.iss; - os = _streamCache.First.Value.os; - - _streamCache.RemoveFirst(); + cb.Invoke(result); } - } - } - if(!haveEntry) - { - return new IceInternal.TwowayOutgoingAsync<T>(this, operation, cb, cookie); - } - else - { - return new IceInternal.TwowayOutgoingAsync<T>(this, operation, cb, cookie, iss, os); - } - } - - protected IceInternal.OnewayOutgoingAsync<T> - getOnewayOutgoingAsync<T>(string operation, IceInternal.ProxyOnewayCallback<T> cb, - object cookie) { - bool haveEntry = false; - IceInternal.BasicStream iss = null; - IceInternal.BasicStream os = null; - - if(_reference.getInstance().cacheMessageBuffers() > 0) - { - lock(this) - { - if(_streamCache != null && _streamCache.Count > 0) - { - haveEntry = true; - iss = _streamCache.First.Value.iss; - os = _streamCache.First.Value.os; - _streamCache.RemoveFirst(); - } - } - } - if(!haveEntry) - { - return new IceInternal.OnewayOutgoingAsync<T>(this, operation, cb, cookie); - } - else - { - return new IceInternal.OnewayOutgoingAsync<T>(this, operation, cb, cookie, iss, os); - } + }, this, _ice_isA_name, cookie, callback); + iceI_ice_isA(id, context, completed, synchronous); + return completed; } - public void - cacheMessageBuffers(IceInternal.BasicStream iss, IceInternal.BasicStream os) + private void iceI_ice_isA(string id, + Dictionary<string, string> context, + OutgoingAsyncCompletionCallback completed, + bool synchronous) { - lock(this) - { - if(_streamCache == null) - { - _streamCache = new LinkedList<StreamCacheEntry>(); - } - StreamCacheEntry cacheEntry; - cacheEntry.iss = iss; - cacheEntry.os = os; - _streamCache.AddLast(cacheEntry); - } + iceCheckAsyncTwowayOnly(_ice_isA_name); + getOutgoingAsync<bool>(completed).invoke(_ice_isA_name, + OperationMode.Nonmutating, + FormatType.DefaultFormat, + context, + synchronous, + (OutputStream os) => { os.writeString(id); }, + null, + (InputStream iss) => { return iss.readBool(); }); } - private void ice_isA_completed__(AsyncResult r__, Callback_Object_ice_isA cb__, Ice.ExceptionCallback excb__) + /// <summary> + /// Tests whether the target object of this proxy can be reached. + /// </summary> + /// <param name="context">The context dictionary for the invocation.</param> + public void ice_ping(OptionalContext context = new OptionalContext()) { - bool ret__; try { - ret__ = end_ice_isA(r__); - } - catch(Ice.Exception ex__) - { - if(excb__ != null) - { - excb__(ex__); - } - return; + iceI_ice_pingAsync(context, null, CancellationToken.None, true).Wait(); } - if(cb__ != null) + catch(AggregateException ex) { - cb__(ret__); + throw ex.InnerException; } } /// <summary> /// Tests whether the target object of this proxy can be reached. /// </summary> - public void ice_ping() - { - ice_ping(null, false); - } - - /// <summary> - /// Tests whether the target object of this proxy can be reached. - /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> - public void ice_ping(Dictionary<string, string> context__) - { - ice_ping(context__, true); - } - - private void ice_ping(Dictionary<string, string> context__, bool explicitCtx__) + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + public Task ice_pingAsync(OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()) { - end_ice_ping(begin_ice_ping(context__, explicitCtx__, true, null, null)); + return iceI_ice_pingAsync(context, progress, cancel, false); } - public AsyncResult<Callback_Object_ice_ping> begin_ice_ping() + private Task + iceI_ice_pingAsync(OptionalContext context, IProgress<bool> progress, CancellationToken cancel, bool synchronous) { - return begin_ice_ping(null, false, false, null, null); + var completed = new OperationTaskCompletionCallback<object>(progress, cancel); + iceI_ice_ping(context, completed, synchronous); + return completed.Task; } - public AsyncResult<Callback_Object_ice_ping> begin_ice_ping(Dictionary<string, string> context__) + /// <summary> + /// Tests whether the target object of this proxy can be reached. + /// </summary> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult begin_ice_ping(AsyncCallback callback, object cookie) { - return begin_ice_ping(context__, true, false, null, null); + return iceI_begin_ice_ping(new OptionalContext(), callback, cookie, false); } - public AsyncResult begin_ice_ping(AsyncCallback cb__, object cookie__) + /// <summary> + /// Tests whether the target object of this proxy can be reached. + /// </summary> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult begin_ice_ping(OptionalContext context, AsyncCallback callback, object cookie) { - return begin_ice_ping(null, false, false, cb__, cookie__); + return iceI_begin_ice_ping(context, callback, cookie, false); } - public AsyncResult begin_ice_ping(Dictionary<string, string> context__, AsyncCallback cb__, object cookie__) + /// <summary> + /// Tests whether the target object of this proxy can be reached. + /// </summary> + /// <param name="context">The context dictionary for the invocation.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult<Callback_Object_ice_ping> + begin_ice_ping(OptionalContext context = new OptionalContext()) { - return begin_ice_ping(null, false, false, cb__, cookie__); + return iceI_begin_ice_ping(context, null, null, false); } - internal const string __ice_ping_name = "ice_ping"; + private const string _ice_ping_name = "ice_ping"; - public void end_ice_ping(AsyncResult r__) + /// <summary> + /// Tests whether the target object of this proxy can be reached. + /// </summary> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_ping</code>.</param> + public void end_ice_ping(AsyncResult result) { - end__(r__, __ice_ping_name); + var resultI = AsyncResultI.check(result, this, _ice_ping_name); + ((OutgoingAsyncT<object>)resultI.OutgoingAsync).getResult(resultI.wait()); } - private AsyncResult<Callback_Object_ice_ping> begin_ice_ping(Dictionary<string, string> context__, - bool explicitCtx__, - bool synchronous__, - Ice.AsyncCallback cb__, - object cookie__) + private AsyncResult<Callback_Object_ice_ping> iceI_begin_ice_ping(Dictionary<string, string> context, + AsyncCallback callback, + object cookie, + bool synchronous) { - IceInternal.OnewayOutgoingAsync<Callback_Object_ice_ping> result__ = - getOnewayOutgoingAsync<Callback_Object_ice_ping>(__ice_ping_name, ice_ping_completed__, cookie__); - if(cb__ != null) - { - result__.whenCompletedWithAsyncCallback(cb__); - } - - try - { - result__.prepare(__ice_ping_name, OperationMode.Nonmutating, context__, explicitCtx__, synchronous__); - result__.writeEmptyParams(); - result__.invoke(); - } - catch(Ice.Exception ex__) - { - result__.abort(ex__); - } - return result__; + var completed = new OperationAsyncResultCompletionCallback<Callback_Object_ice_ping, object>( + (Callback_Object_ice_ping cb, object result) => + { + if(cb != null) + { + cb.Invoke(); + } + }, this, _ice_ping_name, cookie, callback); + iceI_ice_ping(context, completed, synchronous); + return completed; } - private void ice_ping_completed__(Callback_Object_ice_ping cb) + private void iceI_ice_ping(Dictionary<string, string> context, OutgoingAsyncCompletionCallback completed, + bool synchronous) { - if(cb != null) - { - cb(); - } + getOutgoingAsync<object>(completed).invoke(_ice_ping_name, + OperationMode.Nonmutating, + FormatType.DefaultFormat, + context, + synchronous); } /// <summary> /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. /// </summary> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>The Slice type IDs of the interfaces supported by the target object, in base-to-derived /// order. The first element of the returned array is always ::Ice::Object.</returns> - public string[] ice_ids() + public string[] ice_ids(OptionalContext context = new OptionalContext()) { - return ice_ids(null, false); + try + { + return iceI_ice_idsAsync(context, null, CancellationToken.None, true).Result; + } + catch(AggregateException ex) + { + throw ex.InnerException; + } } /// <summary> /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> - /// <returns>The Slice type IDs of the interfaces supported by the target object, in base-to-derived - /// order. The first element of the returned array is always ::Ice::Object.</returns> - public string[] ice_ids(Dictionary<string, string> context__) - { - return ice_ids(context__, true); - } - - private string[] ice_ids(Dictionary<string, string> context__, bool explicitCtx__) + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + public Task<string[]> + ice_idsAsync(OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()) { - - checkTwowayOnly__(__ice_ids_name); - return end_ice_ids(begin_ice_ids(context__, explicitCtx__, true, null, null)); + return iceI_ice_idsAsync(context, progress, cancel, false); } - public AsyncResult<Callback_Object_ice_ids> begin_ice_ids() + private Task<string[]> iceI_ice_idsAsync(OptionalContext context, IProgress<bool> progress, CancellationToken cancel, + bool synchronous) { - return begin_ice_ids(null, false, false, null, null); + var completed = new OperationTaskCompletionCallback<string[]>(progress, cancel); + iceI_ice_ids(context, completed, false); + return completed.Task; } - public AsyncResult<Callback_Object_ice_ids> begin_ice_ids(Dictionary<string, string> context__) + /// <summary> + /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. + /// </summary> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult begin_ice_ids(AsyncCallback callback, object cookie) { - return begin_ice_ids(context__, true, false, null, null); + return iceI_begin_ice_ids(new OptionalContext(), callback, cookie, false); } - public AsyncResult begin_ice_ids(AsyncCallback cb__, object cookie__) + /// <summary> + /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. + /// </summary> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult + begin_ice_ids(OptionalContext context, AsyncCallback callback, object cookie) { - return begin_ice_ids(null, false, false, cb__, cookie__); + return iceI_begin_ice_ids(context, callback, cookie, false); } - public AsyncResult begin_ice_ids(Dictionary<string, string> context__, AsyncCallback cb__, object cookie__) + public AsyncResult<Callback_Object_ice_ids> + begin_ice_ids(OptionalContext context = new OptionalContext()) { - return begin_ice_ids(null, false, false, cb__, cookie__); + return iceI_begin_ice_ids(context, null, null, false); } - internal const string __ice_ids_name = "ice_ids"; + private const string _ice_ids_name = "ice_ids"; - public string[] end_ice_ids(AsyncResult r__) + private AsyncResult<Callback_Object_ice_ids> + iceI_begin_ice_ids(Dictionary<string, string> context, AsyncCallback callback, object cookie, bool synchronous) { - IceInternal.OutgoingAsync outAsync__ = IceInternal.OutgoingAsync.check(r__, this, __ice_ids_name); - try - { - if(!outAsync__.wait()) + var completed = new OperationAsyncResultCompletionCallback<Callback_Object_ice_ids, string[]>( + (Callback_Object_ice_ids cb, string[] result) => { - try - { - outAsync__.throwUserException(); - } - catch(Ice.UserException ex__) + if(cb != null) { - throw new Ice.UnknownUserException(ex__.ice_name(), ex__); + cb.Invoke(result); } - } - string[] ret__; - IceInternal.BasicStream is__ = outAsync__.startReadParams(); - ret__ = is__.readStringSeq(); - outAsync__.endReadParams(); - return ret__; - } - finally - { - if(outAsync__ != null) - { - outAsync__.cacheMessageBuffers(); - } - } + }, this, _ice_ids_name, cookie, callback); + iceI_ice_ids(context, completed, synchronous); + return completed; } - private AsyncResult<Callback_Object_ice_ids> begin_ice_ids(Dictionary<string, string> context__, - bool explicitCtx__, - bool synchronous__, - Ice.AsyncCallback cb__, - object cookie__) + /// <summary> + /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy. + /// </summary> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_ids</code>.</param> + /// <returns>The Slice type IDs of the interfaces supported by the target object, in base-to-derived + /// order. The first element of the returned array is always ::Ice::Object.</returns> + public string[] end_ice_ids(AsyncResult result) { - checkAsyncTwowayOnly__(__ice_ids_name); - - IceInternal.TwowayOutgoingAsync<Callback_Object_ice_ids> result__ = - getTwowayOutgoingAsync<Callback_Object_ice_ids>(__ice_ids_name, ice_ids_completed__, cookie__); - if(cb__ != null) - { - result__.whenCompletedWithAsyncCallback(cb__); - } - - try - { - result__.prepare(__ice_ids_name, OperationMode.Nonmutating, context__, explicitCtx__, synchronous__); - result__.writeEmptyParams(); - result__.invoke(); - } - catch(Ice.Exception ex__) - { - result__.abort(ex__); - } - return result__; + var resultI = AsyncResultI.check(result, this, _ice_ids_name); + return ((OutgoingAsyncT<string[]>)resultI.OutgoingAsync).getResult(resultI.wait()); } - private void ice_ids_completed__(AsyncResult r__, Callback_Object_ice_ids cb__, Ice.ExceptionCallback excb__) + private void iceI_ice_ids(Dictionary<string, string> context, OutgoingAsyncCompletionCallback completed, + bool synchronous) { - string[] ret__; - try - { - ret__ = end_ice_ids(r__); - } - catch(Ice.Exception ex__) - { - if(excb__ != null) - { - excb__(ex__); - } - return; - } - if(cb__ != null) - { - cb__(ret__); - } + iceCheckAsyncTwowayOnly(_ice_ids_name); + getOutgoingAsync<string[]>(completed).invoke(_ice_ids_name, + OperationMode.Nonmutating, + FormatType.DefaultFormat, + context, + synchronous, + read: (InputStream iss) => { return iss.readStringSeq(); }); } /// <summary> /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. /// </summary> /// <returns>The Slice type ID of the most-derived interface.</returns> - public string ice_id() + public string ice_id(OptionalContext context = new OptionalContext()) { - return ice_id(null, false); + try + { + return iceI_ice_idAsync(context, null, CancellationToken.None, true).Result; + } + catch(AggregateException ex) + { + throw ex.InnerException; + } } /// <summary> /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. /// </summary> - /// <param name="context__">The context dictionary for the invocation.</param> - /// <returns>The Slice type ID of the most-derived interface.</returns> - public string ice_id(Dictionary<string, string> context__) - { - return ice_id(context__, true); - } - - private string ice_id(Dictionary<string, string> context__, bool explicitCtx__) + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + public Task<string> ice_idAsync(OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()) { - checkTwowayOnly__(__ice_id_name); - return end_ice_id(begin_ice_id(context__, explicitCtx__, true, null, null)); + return iceI_ice_idAsync(context, progress, cancel, false); } - public AsyncResult<Callback_Object_ice_id> begin_ice_id() + private Task<string> + iceI_ice_idAsync(OptionalContext context, IProgress<bool> progress, CancellationToken cancel, bool synchronous) { - return begin_ice_id(null, false, false, null, null); + var completed = new OperationTaskCompletionCallback<string>(progress, cancel); + iceI_ice_id(context, completed, synchronous); + return completed.Task; } - public AsyncResult<Callback_Object_ice_id> begin_ice_id(Dictionary<string, string> context__) + /// <summary> + /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. + /// </summary> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult begin_ice_id(AsyncCallback callback, object cookie) { - return begin_ice_id(context__, true, false, null, null); + return iceI_begin_ice_id(new OptionalContext(), callback, cookie, false); } - public AsyncResult begin_ice_id(AsyncCallback cb__, object cookie__) + /// <summary> + /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. + /// </summary> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult + begin_ice_id(OptionalContext context, AsyncCallback callback, object cookie) { - return begin_ice_id(null, false, false, cb__, cookie__); + return iceI_begin_ice_id(context, callback, cookie, false); } - public AsyncResult begin_ice_id(Dictionary<string, string> context__, AsyncCallback cb__, object cookie__) + /// <summary> + /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. + /// </summary> + /// <param name="context">The context dictionary for the invocation.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult<Callback_Object_ice_id> + begin_ice_id(OptionalContext context = new OptionalContext()) { - return begin_ice_id(null, false, false, cb__, cookie__); + return iceI_begin_ice_id(context, null, null, false); } - internal const string __ice_id_name = "ice_id"; + private const string _ice_id_name = "ice_id"; - public string end_ice_id(AsyncResult r__) + private AsyncResult<Callback_Object_ice_id> + iceI_begin_ice_id(Dictionary<string, string> context, AsyncCallback callback, object cookie, bool synchronous) { - IceInternal.OutgoingAsync outAsync__ = IceInternal.OutgoingAsync.check(r__, this, __ice_id_name); - try - { - if(!outAsync__.wait()) + var completed = new OperationAsyncResultCompletionCallback<Callback_Object_ice_id, string>( + (Callback_Object_ice_id cb, string result) => { - try + if(cb != null) { - outAsync__.throwUserException(); + cb.Invoke(result); } - catch(Ice.UserException ex__) - { - throw new Ice.UnknownUserException(ex__.ice_name(), ex__); - } - } - string ret__; - IceInternal.BasicStream is__ = outAsync__.startReadParams(); - ret__ = is__.readString(); - outAsync__.endReadParams(); - return ret__; - } - finally - { - if(outAsync__ != null) - { - outAsync__.cacheMessageBuffers(); - } - } + }, this, _ice_id_name, cookie, callback); + iceI_ice_id(context, completed, synchronous); + return completed; } - private AsyncResult<Callback_Object_ice_id> begin_ice_id(Dictionary<string, string> context__, - bool explicitCtx__, - bool synchronous__, - Ice.AsyncCallback cb__, - object cookie__) + /// <summary> + /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy. + /// </summary> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_id</code>.</param> + /// <returns>The Slice type ID of the most-derived interface.</returns> + public string end_ice_id(AsyncResult result) { - checkAsyncTwowayOnly__(__ice_id_name); - - IceInternal.TwowayOutgoingAsync<Callback_Object_ice_id> result__ = - getTwowayOutgoingAsync<Callback_Object_ice_id>(__ice_id_name, ice_id_completed__, cookie__); - if(cb__ != null) - { - result__.whenCompletedWithAsyncCallback(cb__); - } - - try - { - result__.prepare(__ice_id_name, OperationMode.Nonmutating, context__, explicitCtx__, synchronous__); - result__.writeEmptyParams(); - result__.invoke(); - } - catch(Ice.Exception ex__) - { - result__.abort(ex__); - } - return result__; + var resultI = AsyncResultI.check(result, this, _ice_id_name); + return ((OutgoingAsyncT<string>)resultI.OutgoingAsync).getResult(resultI.wait()); } - private void ice_id_completed__(AsyncResult r__, Callback_Object_ice_id cb__, Ice.ExceptionCallback excb__) + private void iceI_ice_id(Dictionary<string, string> context, + OutgoingAsyncCompletionCallback completed, + bool synchronous) { - string ret__; - try - { - ret__ = end_ice_id(r__); - } - catch(Ice.Exception ex__) - { - if(excb__ != null) - { - excb__(ex__); - } - return; - } - if(cb__ != null) - { - cb__(ret__); - } + iceCheckAsyncTwowayOnly(_ice_id_name); + getOutgoingAsync<string>(completed).invoke(_ice_id_name, + OperationMode.Nonmutating, + FormatType.DefaultFormat, + context, + synchronous, + read: (InputStream iss) => { return iss.readString(); }); } /// <summary> @@ -1295,14 +1334,28 @@ namespace Ice /// <param name="inEncaps">The encoded in-parameters for the operation.</param> /// <param name="outEncaps">The encoded out-paramaters and return value /// for the operation. The return value follows any out-parameters.</param> + /// <param name="context">The context dictionary for the invocation.</param> /// <returns>If the operation completed successfully, the return value /// is true. If the operation raises a user exception, /// the return value is false; in this case, outEncaps /// contains the encoded user exception. If the operation raises a run-time exception, /// it throws it directly.</returns> - public bool ice_invoke(string operation, OperationMode mode, byte[] inEncaps, out byte[] outEncaps) + public bool ice_invoke(string operation, + OperationMode mode, + byte[] inEncaps, + out byte[] outEncaps, + OptionalContext context = new OptionalContext()) { - return ice_invoke(operation, mode, inEncaps, out outEncaps, null, false); + try + { + var result = iceI_ice_invokeAsync(operation, mode, inEncaps, context, null, CancellationToken.None, true).Result; + outEncaps = result.outEncaps; + return result.returnValue; + } + catch(AggregateException ex) + { + throw ex.InnerException; + } } /// <summary> @@ -1311,132 +1364,134 @@ namespace Ice /// <param name="operation">The name of the operation to invoke.</param> /// <param name="mode">The operation mode (normal or idempotent).</param> /// <param name="inEncaps">The encoded in-parameters for the operation.</param> - /// <param name="outEncaps">The encoded out-paramaters and return value - /// for the operation. The return value follows any out-parameters.</param> /// <param name="context">The context dictionary for the invocation.</param> - /// <returns>If the operation completed successfully, the return value - /// is true. If the operation raises a user exception, - /// the return value is false; in this case, outEncaps - /// contains the encoded user exception. If the operation raises a run-time exception, - /// it throws it directly.</returns> - public bool ice_invoke(string operation, OperationMode mode, byte[] inEncaps, out byte[] outEncaps, - Dictionary<string, string> context) - { - return ice_invoke(operation, mode, inEncaps, out outEncaps, context, true); - } - - private bool ice_invoke(string operation, OperationMode mode, byte[] inEncaps, out byte[] outEncaps, - Dictionary<string, string> context, bool explicitCtx) + /// <param name="progress">Sent progress provider.</param> + /// <param name="cancel">A cancellation token that receives the cancellation requests.</param> + /// <returns>The task object representing the asynchronous operation.</returns> + public Task<Object_Ice_invokeResult> + ice_invokeAsync(string operation, + OperationMode mode, + byte[] inEncaps, + OptionalContext context = new OptionalContext(), + IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()) { - return end_ice_invoke(out outEncaps, begin_ice_invoke(operation, mode, inEncaps, context, explicitCtx, true, null, null)); + return iceI_ice_invokeAsync(operation, mode, inEncaps, context, progress, cancel, false); } - public AsyncResult<Callback_Object_ice_invoke> begin_ice_invoke(string operation, - OperationMode mode, - byte[] inEncaps) + private Task<Object_Ice_invokeResult> + iceI_ice_invokeAsync(string operation, + OperationMode mode, + byte[] inEncaps, + OptionalContext context, + IProgress<bool> progress, + CancellationToken cancel, + bool synchronous) { - return begin_ice_invoke(operation, mode, inEncaps, null, false, false, null, null); + var completed = new InvokeTaskCompletionCallback(progress, cancel); + iceI_ice_invoke(operation, mode, inEncaps, context, completed, synchronous); + return completed.Task; } - public AsyncResult<Callback_Object_ice_invoke> begin_ice_invoke(string operation, - OperationMode mode, - byte[] inEncaps, - Dictionary<string, string> context__) + /// <summary> + /// Invokes an operation dynamically. + /// </summary> + /// <param name="operation">The name of the operation to invoke.</param> + /// <param name="mode">The operation mode (normal or idempotent).</param> + /// <param name="inEncaps">The encoded in-parameters for the operation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult + begin_ice_invoke(string operation, + OperationMode mode, + byte[] inEncaps, + AsyncCallback callback, + object cookie) { - return begin_ice_invoke(operation, mode, inEncaps, context__, true, false, null, null); + return iceI_begin_ice_invoke(operation, mode, inEncaps, new OptionalContext(), callback, cookie, false); } - public AsyncResult begin_ice_invoke(string operation, OperationMode mode, byte[] inEncaps, AsyncCallback cb__, - object cookie__) + /// <summary> + /// Invokes an operation dynamically. + /// </summary> + /// <param name="operation">The name of the operation to invoke.</param> + /// <param name="mode">The operation mode (normal or idempotent).</param> + /// <param name="inEncaps">The encoded in-parameters for the operation.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <param name="callback">A callback to be invoked when the invocation completes.</param> + /// <param name="cookie">Application-specific data to be stored in the result.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult + begin_ice_invoke(string operation, + OperationMode mode, + byte[] inEncaps, + OptionalContext context, + AsyncCallback callback, + object cookie) { - return begin_ice_invoke(operation, mode, inEncaps, null, false, false, cb__, cookie__); + return iceI_begin_ice_invoke(operation, mode, inEncaps, context, callback, cookie, false); } - public AsyncResult begin_ice_invoke(string operation, OperationMode mode, byte[] inEncaps, - Dictionary<string, string> context__, AsyncCallback cb__, object cookie__) + /// <summary> + /// Invokes an operation dynamically. + /// </summary> + /// <param name="operation">The name of the operation to invoke.</param> + /// <param name="mode">The operation mode (normal or idempotent).</param> + /// <param name="inEncaps">The encoded in-parameters for the operation.</param> + /// <param name="context">The context dictionary for the invocation.</param> + /// <returns>An asynchronous result object.</returns> + public AsyncResult<Callback_Object_ice_invoke> + begin_ice_invoke(string operation, + OperationMode mode, + byte[] inEncaps, + OptionalContext context = new OptionalContext()) { - return begin_ice_invoke(operation, mode, inEncaps, null, false, false, cb__, cookie__); + return iceI_begin_ice_invoke(operation, mode, inEncaps, context, null, null, false); } - internal const string __ice_invoke_name = "ice_invoke"; + private const string _ice_invoke_name = "ice_invoke"; - public bool end_ice_invoke(out byte[] outEncaps, AsyncResult r__) + /// <summary> + /// Completes a dynamic invocation. + /// </summary> + /// <param name="outEncaps">The encoded out parameters or user exception.</param> + /// <param name="result">The asynchronous result object returned by <code>begin_ice_invoke</code>.</param> + /// <returns>If the operation completed successfully, the return value + /// is true. If the operation raises a user exception, + /// the return value is false; in this case, outEncaps + /// contains the encoded user exception. If the operation raises a run-time exception, + /// it throws it directly.</returns> + public bool end_ice_invoke(out byte[] outEncaps, AsyncResult result) { - IceInternal.OutgoingAsync outAsync__ = IceInternal.OutgoingAsync.check(r__, this, __ice_invoke_name); - try - { - bool ok = outAsync__.wait(); - if(_reference.getMode() == IceInternal.Reference.Mode.ModeTwoway) - { - outEncaps = outAsync__.readParamEncaps(); - } - else - { - outEncaps = null; // Satisfy compiler - } - return ok; - } - finally - { - if(outAsync__ != null) - { - outAsync__.cacheMessageBuffers(); - } - } - + var resultI = AsyncResultI.check(result, this, _ice_invoke_name); + var r = ((InvokeOutgoingAsyncT)resultI.OutgoingAsync).getResult(resultI.wait()); + outEncaps = r.outEncaps; + return r.returnValue; } - private AsyncResult<Callback_Object_ice_invoke> begin_ice_invoke(string operation, - OperationMode mode, - byte[] inEncaps, - Dictionary<string, string> context__, - bool explicitCtx__, - bool synchronous__, - Ice.AsyncCallback cb__, - object cookie__) + private AsyncResult<Callback_Object_ice_invoke> + iceI_begin_ice_invoke(string operation, + OperationMode mode, + byte[] inEncaps, + Dictionary<string, string> context, + AsyncCallback callback, + object cookie, + bool synchronous) { - IceInternal.TwowayOutgoingAsync<Callback_Object_ice_invoke> result__ = - getTwowayOutgoingAsync<Callback_Object_ice_invoke>(__ice_invoke_name, ice_invoke_completed__, cookie__); - if(cb__ != null) - { - result__.whenCompletedWithAsyncCallback(cb__); - } - - try - { - result__.prepare(operation, mode, context__, explicitCtx__, synchronous__); - result__.writeParamEncaps(inEncaps); - result__.invoke(); - } - catch(Ice.Exception ex__) - { - result__.abort(ex__); - } - return result__; + var completed = new InvokeAsyncResultCompletionCallback(this, _ice_invoke_name, cookie, callback); + iceI_ice_invoke(operation, mode, inEncaps, context, completed, synchronous); + return completed; } - private void ice_invoke_completed__(AsyncResult r__, - Callback_Object_ice_invoke cb__, - Ice.ExceptionCallback excb__) + private void iceI_ice_invoke(string operation, + OperationMode mode, + byte[] inEncaps, + Dictionary<string, string> context, + OutgoingAsyncCompletionCallback completed, + bool synchronous) { - byte[] outEncaps; - bool ret__; - try - { - ret__ = end_ice_invoke(out outEncaps, r__); - } - catch(Ice.Exception ex__) - { - if(excb__ != null) - { - excb__(ex__); - } - return; - } - if(cb__ != null) - { - cb__(ret__, outEncaps); - } + getInvokeOutgoingAsync(completed).invoke(operation, mode, inEncaps, context, synchronous); } /// <summary> @@ -1465,7 +1520,7 @@ namespace Ice } else { - ObjectPrxHelperBase proxy = new ObjectPrxHelperBase(); + var proxy = new ObjectPrxHelperBase(); proxy.setup(_reference.changeIdentity(newIdentity)); return proxy; } @@ -1519,7 +1574,7 @@ namespace Ice } else { - ObjectPrxHelperBase proxy = new ObjectPrxHelperBase(); + var proxy = new ObjectPrxHelperBase(); proxy.setup(_reference.changeFacet(newFacet)); return proxy; } @@ -1579,10 +1634,10 @@ namespace Ice } else { - IceInternal.EndpointI[] endpts = new IceInternal.EndpointI[newEndpoints.Length]; + var endpts = new EndpointI[newEndpoints.Length]; for(int i = 0; i < newEndpoints.Length; ++i) { - endpts[i] = (IceInternal.EndpointI)newEndpoints[i]; + endpts[i] = (EndpointI)newEndpoints[i]; } return newInstance(_reference.changeEndpoints(endpts)); } @@ -1605,7 +1660,7 @@ namespace Ice { if(newTimeout < -1) { - throw new System.ArgumentException("invalid value passed to ice_locatorCacheTimeout: " + newTimeout); + throw new ArgumentException("invalid value passed to ice_locatorCacheTimeout: " + newTimeout); } if(newTimeout == _reference.getLocatorCacheTimeout()) { @@ -1634,7 +1689,7 @@ namespace Ice { if(newTimeout < 1 && newTimeout != -1 && newTimeout != -2) { - throw new System.ArgumentException("invalid value passed to ice_invocationTimeout: " + newTimeout); + throw new ArgumentException("invalid value passed to ice_invocationTimeout: " + newTimeout); } if(newTimeout == _reference.getInvocationTimeout()) { @@ -1732,7 +1787,7 @@ namespace Ice /// </summary> /// <param name="e">The encoding version to use to marshal requests parameters.</param> /// <returns>The new proxy with the specified encoding version.</returns> - public ObjectPrx ice_encodingVersion(Ice.EncodingVersion e) + public ObjectPrx ice_encodingVersion(EncodingVersion e) { if(e.Equals(_reference.getEncoding())) { @@ -1746,7 +1801,7 @@ namespace Ice /// <summary>Returns the encoding version used to marshal requests parameters.</summary> /// <returns>The encoding version.</returns> - public Ice.EncodingVersion ice_getEncodingVersion() + public EncodingVersion ice_getEncodingVersion() { return _reference.getEncoding(); } @@ -1785,9 +1840,9 @@ namespace Ice /// </summary> /// <returns>The router for the proxy. If no router is configured for the proxy, the return value /// is null.</returns> - public Ice.RouterPrx ice_getRouter() + public RouterPrx ice_getRouter() { - IceInternal.RouterInfo ri = _reference.getRouterInfo(); + RouterInfo ri = _reference.getRouterInfo(); return ri != null ? ri.getRouter() : null; } @@ -1798,7 +1853,7 @@ namespace Ice /// <returns>The new proxy with the specified router.</returns> public ObjectPrx ice_router(RouterPrx router) { - IceInternal.Reference @ref = _reference.changeRouter(router); + Reference @ref = _reference.changeRouter(router); if(@ref.Equals(_reference)) { return this; @@ -1813,9 +1868,9 @@ namespace Ice /// Returns the locator for this proxy. /// </summary> /// <returns>The locator for this proxy. If no locator is configured, the return value is null.</returns> - public Ice.LocatorPrx ice_getLocator() + public LocatorPrx ice_getLocator() { - IceInternal.LocatorInfo li = _reference.getLocatorInfo(); + var li = _reference.getLocatorInfo(); return li != null ? li.getLocator() : null; } @@ -1826,7 +1881,7 @@ namespace Ice /// <returns>The new proxy with the specified locator.</returns> public ObjectPrx ice_locator(LocatorPrx locator) { - IceInternal.Reference @ref = _reference.changeLocator(locator); + var @ref = _reference.changeLocator(locator); if(@ref.Equals(_reference)) { return this; @@ -1869,13 +1924,13 @@ namespace Ice /// <returns>A new proxy that uses twoway invocations.</returns> public ObjectPrx ice_twoway() { - if(_reference.getMode() == IceInternal.Reference.Mode.ModeTwoway) + if(_reference.getMode() == Reference.Mode.ModeTwoway) { return this; } else { - return newInstance(_reference.changeMode(IceInternal.Reference.Mode.ModeTwoway)); + return newInstance(_reference.changeMode(Reference.Mode.ModeTwoway)); } } @@ -1885,7 +1940,7 @@ namespace Ice /// <returns>True if this proxy uses twoway invocations; false, otherwise.</returns> public bool ice_isTwoway() { - return _reference.getMode() == IceInternal.Reference.Mode.ModeTwoway; + return _reference.getMode() == Reference.Mode.ModeTwoway; } /// <summary> @@ -1894,13 +1949,13 @@ namespace Ice /// <returns>A new proxy that uses oneway invocations.</returns> public ObjectPrx ice_oneway() { - if(_reference.getMode() == IceInternal.Reference.Mode.ModeOneway) + if(_reference.getMode() == Reference.Mode.ModeOneway) { return this; } else { - return newInstance(_reference.changeMode(IceInternal.Reference.Mode.ModeOneway)); + return newInstance(_reference.changeMode(Reference.Mode.ModeOneway)); } } @@ -1910,7 +1965,7 @@ namespace Ice /// <returns>True if this proxy uses oneway invocations; false, otherwise.</returns> public bool ice_isOneway() { - return _reference.getMode() == IceInternal.Reference.Mode.ModeOneway; + return _reference.getMode() == Reference.Mode.ModeOneway; } /// <summary> @@ -1919,13 +1974,13 @@ namespace Ice /// <returns>A new proxy that uses batch oneway invocations.</returns> public ObjectPrx ice_batchOneway() { - if(_reference.getMode() == IceInternal.Reference.Mode.ModeBatchOneway) + if(_reference.getMode() == Reference.Mode.ModeBatchOneway) { return this; } else { - return newInstance(_reference.changeMode(IceInternal.Reference.Mode.ModeBatchOneway)); + return newInstance(_reference.changeMode(Reference.Mode.ModeBatchOneway)); } } @@ -1935,7 +1990,7 @@ namespace Ice /// <returns>True if this proxy uses batch oneway invocations; false, otherwise.</returns> public bool ice_isBatchOneway() { - return _reference.getMode() == IceInternal.Reference.Mode.ModeBatchOneway; + return _reference.getMode() == Reference.Mode.ModeBatchOneway; } /// <summary> @@ -1944,13 +1999,13 @@ namespace Ice /// <returns>A new proxy that uses datagram invocations.</returns> public ObjectPrx ice_datagram() { - if(_reference.getMode() == IceInternal.Reference.Mode.ModeDatagram) + if(_reference.getMode() == Reference.Mode.ModeDatagram) { return this; } else { - return newInstance(_reference.changeMode(IceInternal.Reference.Mode.ModeDatagram)); + return newInstance(_reference.changeMode(Reference.Mode.ModeDatagram)); } } @@ -1960,7 +2015,7 @@ namespace Ice /// <returns>True if this proxy uses datagram invocations; false, otherwise.</returns> public bool ice_isDatagram() { - return _reference.getMode() == IceInternal.Reference.Mode.ModeDatagram; + return _reference.getMode() == Reference.Mode.ModeDatagram; } /// <summary> @@ -1969,13 +2024,13 @@ namespace Ice /// <returns>A new proxy that uses batch datagram invocations.</returns> public ObjectPrx ice_batchDatagram() { - if(_reference.getMode() == IceInternal.Reference.Mode.ModeBatchDatagram) + if(_reference.getMode() == Reference.Mode.ModeBatchDatagram) { return this; } else { - return newInstance(_reference.changeMode(IceInternal.Reference.Mode.ModeBatchDatagram)); + return newInstance(_reference.changeMode(Reference.Mode.ModeBatchDatagram)); } } @@ -1985,7 +2040,7 @@ namespace Ice /// <returns>True if this proxy uses batch datagram invocations; false, otherwise.</returns> public bool ice_isBatchDatagram() { - return _reference.getMode() == IceInternal.Reference.Mode.ModeBatchDatagram; + return _reference.getMode() == Reference.Mode.ModeBatchDatagram; } /// <summary> @@ -1995,7 +2050,7 @@ namespace Ice /// <returns>A new proxy with the specified compression setting.</returns> public ObjectPrx ice_compress(bool co) { - IceInternal.Reference @ref = _reference.changeCompress(co); + var @ref = _reference.changeCompress(co); if(@ref.Equals(_reference)) { return this; @@ -2015,9 +2070,9 @@ namespace Ice { if(t < 1 && t != -1) { - throw new System.ArgumentException("invalid value passed to ice_timeout: " + t); + throw new ArgumentException("invalid value passed to ice_timeout: " + t); } - IceInternal.Reference @ref = _reference.changeTimeout(t); + var @ref = _reference.changeTimeout(t); if(@ref.Equals(_reference)) { return this; @@ -2036,7 +2091,7 @@ namespace Ice /// <returns>A new proxy with the specified connection ID.</returns> public ObjectPrx ice_connectionId(string connectionId) { - IceInternal.Reference @ref = _reference.changeConnectionId(connectionId); + var @ref = _reference.changeConnectionId(connectionId); if(@ref.Equals(_reference)) { return this; @@ -2065,74 +2120,116 @@ namespace Ice /// collocated object.</exception> public Connection ice_getConnection() { - return end_ice_getConnection(begin_ice_getConnection()); + try + { + return ice_getConnectionAsync().Result; + } + catch(AggregateException ex) + { + throw ex.InnerException; + } } - public AsyncResult<Callback_Object_ice_getConnection> begin_ice_getConnection() + private class ProxyGetConnectionAsyncCallback : ProxyAsyncResultCompletionCallback<Callback_Object_ice_getConnection> { - return begin_ice_getConnectionInternal(null, null); - } + public ProxyGetConnectionAsyncCallback(ObjectPrxHelperBase proxy, string operation, object cookie, + AsyncCallback cb) : + base(proxy, operation, cookie, cb) + { + } - internal const string __ice_getConnection_name = "ice_getConnection"; + protected override AsyncCallback getCompletedCallback() + { + return (AsyncResult result) => + { + try + { + result.throwLocalException(); + if(responseCallback_ != null) + { + responseCallback_.Invoke(((ProxyGetConnection)OutgoingAsync).getConnection()); + } - public AsyncResult begin_ice_getConnection(Ice.AsyncCallback cb, object cookie) - { - return begin_ice_getConnectionInternal(cb, cookie); + } + catch(Exception ex) + { + if(exceptionCallback_ != null) + { + exceptionCallback_.Invoke(ex); + } + } + }; + } } - public Connection end_ice_getConnection(Ice.AsyncResult r) + public class GetConnectionTaskCompletionCallback : TaskCompletionCallback<Connection> { - IceInternal.ProxyGetConnection outAsync = - IceInternal.ProxyGetConnection.check(r, this, __ice_getConnection_name); - outAsync.wait(); - return ice_getCachedConnection(); - } + public GetConnectionTaskCompletionCallback(ObjectPrx proxy, + IProgress<bool> progress, + CancellationToken cancellationToken) : + base(progress, cancellationToken) + { + _proxy = proxy; + } - private AsyncResult<Callback_Object_ice_getConnection> begin_ice_getConnectionInternal(Ice.AsyncCallback cb, - object cookie) - { - IceInternal.ProxyGetConnection result = new IceInternal.ProxyGetConnection(this, - __ice_getConnection_name, - ice_getConnection_completed__, - cookie); - if(cb != null) + public override bool handleResponse(bool ok, OutgoingAsyncBase og) { - result.whenCompletedWithAsyncCallback(cb); + SetResult(((ProxyGetConnection)og).getConnection()); + return false; } + + private ObjectPrx _proxy; + } + + public Task<Connection> ice_getConnectionAsync(IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()) + { + var completed = new GetConnectionTaskCompletionCallback(this, progress, cancel); + var outgoing = new ProxyGetConnection(this, completed); try { - result.invoke(); + outgoing.invoke(_ice_getConnection_name); } - catch(Ice.Exception ex) + catch(Exception ex) { - result.abort(ex); + outgoing.abort(ex); } - return result; + return completed.Task; } + public AsyncResult<Callback_Object_ice_getConnection> begin_ice_getConnection() + { + return begin_ice_getConnectionInternal(null, null); + } + private const string _ice_getConnection_name = "ice_getConnection"; - private void ice_getConnection_completed__(AsyncResult r, - Callback_Object_ice_getConnection cb, - Ice.ExceptionCallback excb) + public AsyncResult begin_ice_getConnection(AsyncCallback cb, object cookie) { - Connection ret; + return begin_ice_getConnectionInternal(cb, cookie); + } + + public Connection end_ice_getConnection(AsyncResult r) + { + var resultI = AsyncResultI.check(r, this, _ice_getConnection_name); + resultI.wait(); + return ((ProxyGetConnection)resultI.OutgoingAsync).getConnection(); + } + + private AsyncResult<Callback_Object_ice_getConnection> begin_ice_getConnectionInternal(AsyncCallback callback, + object cookie) + { + var completed = new ProxyGetConnectionAsyncCallback(this, _ice_getConnection_name, cookie, callback); + var outgoing = new ProxyGetConnection(this, completed); try { - ret = end_ice_getConnection(r); + outgoing.invoke(_ice_getConnection_name); } - catch(Ice.Exception ex) + catch(Exception ex) { - if(excb != null) - { - excb(ex); - } - return; - } - if(cb != null) - { - cb(ret); + outgoing.abort(ex); } + return completed; } /// <summary> @@ -2145,7 +2242,7 @@ namespace Ice /// collocated object.</exception> public Connection ice_getCachedConnection() { - IceInternal.RequestHandler handler; + RequestHandler handler; lock(this) { handler = _requestHandler; @@ -2169,41 +2266,91 @@ namespace Ice /// </summary> public void ice_flushBatchRequests() { - end_ice_flushBatchRequests(begin_ice_flushBatchRequests()); + try + { + ice_flushBatchRequestsAsync().Wait(); + } + catch(AggregateException ex) + { + throw ex.InnerException; + } } - internal const string __ice_flushBatchRequests_name = "ice_flushBatchRequests"; + internal const string _ice_flushBatchRequests_name = "ice_flushBatchRequests"; - public AsyncResult begin_ice_flushBatchRequests() + public Task ice_flushBatchRequestsAsync(IProgress<bool> progress = null, + CancellationToken cancel = new CancellationToken()) { - return begin_ice_flushBatchRequests(null, null); + var completed = new FlushBatchTaskCompletionCallback(progress, cancel); + var outgoing = new ProxyFlushBatchAsync(this, completed); + try + { + outgoing.invoke(_ice_flushBatchRequests_name); + } + catch(Exception ex) + { + outgoing.abort(ex); + } + return completed.Task; } - public AsyncResult begin_ice_flushBatchRequests(Ice.AsyncCallback cb, object cookie) + private class ProxyFlushBatchRequestsAsyncCallback : AsyncResultCompletionCallback { - IceInternal.ProxyFlushBatch result = new IceInternal.ProxyFlushBatch(this, - __ice_flushBatchRequests_name, - cookie); - if(cb != null) + public ProxyFlushBatchRequestsAsyncCallback(ObjectPrx proxy, + string operation, + object cookie, + AsyncCallback callback) : + base(proxy.ice_getCommunicator(), ((ObjectPrxHelperBase)proxy).iceReference().getInstance(), + operation, cookie, callback) + { + _proxy = proxy; + } + + public override ObjectPrx getProxy() { - result.whenCompletedWithAsyncCallback(cb); + return _proxy; } + + protected override AsyncCallback getCompletedCallback() + { + return (AsyncResult result) => + { + try + { + result.throwLocalException(); + } + catch(Exception ex) + { + if(exceptionCallback_ != null) + { + exceptionCallback_.Invoke(ex); + } + } + }; + } + + private ObjectPrx _proxy; + } + + public AsyncResult begin_ice_flushBatchRequests(AsyncCallback cb = null, object cookie = null) + { + var completed = new ProxyFlushBatchRequestsAsyncCallback(this, _ice_flushBatchRequests_name, cookie, cb); + var outgoing = new ProxyFlushBatchAsync(this, completed); try { - result.invoke(); + outgoing.invoke(_ice_flushBatchRequests_name); } - catch(Ice.Exception ex) + catch(Exception ex) { - result.abort(ex); + outgoing.abort(ex); } - return result; + return completed; } - public void end_ice_flushBatchRequests(Ice.AsyncResult r) + public void end_ice_flushBatchRequests(AsyncResult r) { - IceInternal.ProxyFlushBatch outAsync = - IceInternal.ProxyFlushBatch.check(r, this, __ice_flushBatchRequests_name); - outAsync.wait(); + var resultI = AsyncResultI.check(r, this, _ice_flushBatchRequests_name); + resultI.wait(); } /// <summary> @@ -2214,8 +2361,8 @@ namespace Ice /// <returns>True if this proxy is equal to r; false, otherwise.</returns> public override bool Equals(object r) { - ObjectPrxHelperBase rhs = r as ObjectPrxHelperBase; - return object.ReferenceEquals(rhs, null) ? false : _reference.Equals(rhs._reference); + var rhs = r as ObjectPrxHelperBase; + return ReferenceEquals(rhs, null) ? false : _reference.Equals(rhs._reference); } /// <summary> @@ -2227,7 +2374,7 @@ namespace Ice /// <returns>True if the proxies are equal; false, otherwise.</returns> public static bool Equals(ObjectPrxHelperBase lhs, ObjectPrxHelperBase rhs) { - return object.ReferenceEquals(lhs, null) ? object.ReferenceEquals(rhs, null) : lhs.Equals(rhs); + return ReferenceEquals(lhs, null) ? ReferenceEquals(rhs, null) : lhs.Equals(rhs); } /// <summary> @@ -2254,25 +2401,35 @@ namespace Ice return !Equals(lhs, rhs); } - public IceInternal.Reference reference__() + [EditorBrowsable(EditorBrowsableState.Never)] + public void iceWrite(OutputStream os) + { + _reference.getIdentity().ice_writeMembers(os); + _reference.streamWrite(os); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public Reference iceReference() { return _reference; } - public void copyFrom__(ObjectPrx from) + [EditorBrowsable(EditorBrowsableState.Never)] + public void iceCopyFrom(ObjectPrx from) { lock(from) { - ObjectPrxHelperBase h = (ObjectPrxHelperBase)from; + var h = (ObjectPrxHelperBase)from; _reference = h._reference; _requestHandler = h._requestHandler; } } - public int handleException__(Exception ex, IceInternal.RequestHandler handler, OperationMode mode, bool sent, + [EditorBrowsable(EditorBrowsableState.Never)] + public int iceHandleException(Exception ex, RequestHandler handler, OperationMode mode, bool sent, ref int cnt) { - updateRequestHandler__(handler, null); // Clear the request handler + iceUpdateRequestHandler(handler, null); // Clear the request handler // // We only retry local exception, system exceptions aren't retried. @@ -2314,7 +2471,8 @@ namespace Ice } } - public void checkTwowayOnly__(string name) + [EditorBrowsable(EditorBrowsableState.Never)] + public void iceCheckAsyncTwowayOnly(string name) { // // No mutex lock necessary, there is nothing mutable in this @@ -2323,58 +2481,12 @@ namespace Ice if(!ice_isTwoway()) { - TwowayOnlyException ex = new TwowayOnlyException(); - ex.operation = name; - throw ex; - } - } - - public void checkAsyncTwowayOnly__(string name) - { - // - // No mutex lock necessary, there is nothing mutable in this - // operation. - // - - if(!ice_isTwoway()) - { - throw new System.ArgumentException("`" + name + "' can only be called with a twoway proxy"); - } - } - - public void end__(AsyncResult r, string operation) - { - IceInternal.ProxyOutgoingAsyncBase result = IceInternal.ProxyOutgoingAsyncBase.check(r, this, operation); - try - { - bool ok = result.wait(); - if(_reference.getMode() == IceInternal.Reference.Mode.ModeTwoway) - { - IceInternal.OutgoingAsync outAsync = (IceInternal.OutgoingAsync)result; - if(!ok) - { - try - { - outAsync.throwUserException(); - } - catch(Ice.UserException ex) - { - throw new Ice.UnknownUserException(ex.ice_name(), ex); - } - } - outAsync.readEmptyParams(); - } - } - finally - { - if(result != null) - { - result.cacheMessageBuffers(); - } + throw new ArgumentException("`" + name + "' can only be called with a twoway proxy"); } } - public IceInternal.RequestHandler getRequestHandler__() + [EditorBrowsable(EditorBrowsableState.Never)] + public RequestHandler iceGetRequestHandler() { if(_reference.getCacheConnection()) { @@ -2389,8 +2501,9 @@ namespace Ice return _reference.getRequestHandler(this); } - public IceInternal.BatchRequestQueue - getBatchRequestQueue__() + [EditorBrowsable(EditorBrowsableState.Never)] + public BatchRequestQueue + iceGetBatchRequestQueue() { lock(this) { @@ -2402,8 +2515,9 @@ namespace Ice } } - public IceInternal.RequestHandler - setRequestHandler__(IceInternal.RequestHandler handler) + [EditorBrowsable(EditorBrowsableState.Never)] + public RequestHandler + iceSetRequestHandler(RequestHandler handler) { if(_reference.getCacheConnection()) { @@ -2419,7 +2533,8 @@ namespace Ice return handler; } - public void updateRequestHandler__(IceInternal.RequestHandler previous, IceInternal.RequestHandler handler) + [EditorBrowsable(EditorBrowsableState.Never)] + public void iceUpdateRequestHandler(RequestHandler previous, RequestHandler handler) { if(_reference.getCacheConnection() && previous != null) { @@ -2440,36 +2555,243 @@ namespace Ice } } - // - // Only for use by IceInternal.ProxyFactory - // - public void setup(IceInternal.Reference @ref) + protected OutgoingAsyncT<T> + getOutgoingAsync<T>(OutgoingAsyncCompletionCallback completed) + { + bool haveEntry = false; + InputStream iss = null; + OutputStream os = null; + + if(_reference.getInstance().cacheMessageBuffers() > 0) + { + lock(this) + { + if(_streamCache != null && _streamCache.Count > 0) + { + haveEntry = true; + iss = _streamCache.First.Value.iss; + os = _streamCache.First.Value.os; + + _streamCache.RemoveFirst(); + } + } + } + if(!haveEntry) + { + return new OutgoingAsyncT<T>(this, completed); + } + else + { + return new OutgoingAsyncT<T>(this, completed, os, iss); + } + } + + private class InvokeOutgoingAsyncT : OutgoingAsync + { + public InvokeOutgoingAsyncT(ObjectPrxHelperBase prx, + OutgoingAsyncCompletionCallback completionCallback, + OutputStream os = null, + InputStream iss = null) : base(prx, completionCallback, os, iss) + { + } + + public void invoke(string operation, OperationMode mode, byte[] inParams, + Dictionary<string, string> context, bool synchronous) + { + try + { + prepare(operation, mode, context, synchronous); + if(inParams == null || inParams.Length == 0) + { + os_.writeEmptyEncapsulation(encoding_); + } + else + { + os_.writeEncapsulation(inParams); + } + invoke(operation); + } + catch(Exception ex) + { + abort(ex); + } + } + + public Object_Ice_invokeResult + getResult(bool ok) + { + try + { + var ret = new Object_Ice_invokeResult(); + EncodingVersion encoding; + if(proxy_.iceReference().getMode() == Reference.Mode.ModeTwoway) + { + ret.outEncaps = is_.readEncapsulation(out encoding); + } + else + { + ret.outEncaps = null; + } + ret.returnValue = ok; + return ret; + } + finally + { + cacheMessageBuffers(); + } + } + } + + public class InvokeAsyncResultCompletionCallback : ProxyAsyncResultCompletionCallback<Callback_Object_ice_invoke> + { + public InvokeAsyncResultCompletionCallback(ObjectPrxHelperBase proxy, + string operation, + object cookie, + AsyncCallback callback) : + base(proxy, operation, cookie, callback) + { + } + + override protected AsyncCallback getCompletedCallback() + { + return (AsyncResult r) => + { + Debug.Assert(r == this); + try + { + Object_Ice_invokeResult result = ((InvokeOutgoingAsyncT)outgoing_).getResult(wait()); + try + { + if(responseCallback_ != null) + { + responseCallback_.Invoke(result.returnValue, result.outEncaps); + } + } + catch(Exception ex) + { + throw new AggregateException(ex); + } + } + catch(Exception ex) + { + if(exceptionCallback_ != null) + { + exceptionCallback_.Invoke(ex); + } + } + }; + } + }; + + private class InvokeTaskCompletionCallback : TaskCompletionCallback<Object_Ice_invokeResult> + { + public InvokeTaskCompletionCallback(IProgress<bool> progress, CancellationToken cancellationToken) : + base(progress, cancellationToken) + { + } + + public override bool handleSent(bool done, bool alreadySent) + { + if(done) + { + var result = new Object_Ice_invokeResult(); + result.returnValue = true; + SetResult(result); + } + return base.handleSent(false, alreadySent); + } + + public override bool handleResponse(bool ok, OutgoingAsyncBase og) + { + SetResult(((InvokeOutgoingAsyncT)og).getResult(ok)); + return false; + } + } + + private InvokeOutgoingAsyncT + getInvokeOutgoingAsync(OutgoingAsyncCompletionCallback completed) + { + bool haveEntry = false; + InputStream iss = null; + OutputStream os = null; + + if(_reference.getInstance().cacheMessageBuffers() > 0) + { + lock(this) + { + if(_streamCache != null && _streamCache.Count > 0) + { + haveEntry = true; + iss = _streamCache.First.Value.iss; + os = _streamCache.First.Value.os; + + _streamCache.RemoveFirst(); + } + } + } + if(!haveEntry) + { + return new InvokeOutgoingAsyncT(this, completed); + } + else + { + return new InvokeOutgoingAsyncT(this, completed, os, iss); + } + } + + /// <summary> + /// Only for internal use by OutgoingAsync + /// </summary> + /// <param name="iss"></param> + /// <param name="os"></param> + [EditorBrowsable(EditorBrowsableState.Never)] + public void + cacheMessageBuffers(InputStream iss, OutputStream os) + { + lock(this) + { + if(_streamCache == null) + { + _streamCache = new LinkedList<StreamCacheEntry>(); + } + StreamCacheEntry cacheEntry; + cacheEntry.iss = iss; + cacheEntry.os = os; + _streamCache.AddLast(cacheEntry); + } + } + + /// <summary> + /// Only for internal use by ProxyFactory + /// </summary> + /// <param name="ref"></param> + [EditorBrowsable(EditorBrowsableState.Never)] + public void setup(Reference @ref) { // // No need to synchronize, as this operation is only called // upon initial initialization. // - Debug.Assert(_reference == null); Debug.Assert(_requestHandler == null); _reference = @ref; } - private ObjectPrxHelperBase newInstance(IceInternal.Reference @ref) + private ObjectPrxHelperBase newInstance(Reference @ref) { - ObjectPrxHelperBase proxy = (ObjectPrxHelperBase)Activator.CreateInstance(GetType()); + var proxy = (ObjectPrxHelperBase)Activator.CreateInstance(GetType()); proxy.setup(@ref); return proxy; } - private IceInternal.Reference _reference; - private IceInternal.RequestHandler _requestHandler; - private IceInternal.BatchRequestQueue _batchRequestQueue; + private Reference _reference; + private RequestHandler _requestHandler; + private BatchRequestQueue _batchRequestQueue; private struct StreamCacheEntry { - public IceInternal.BasicStream iss; - public IceInternal.BasicStream os; + public InputStream iss; + public OutputStream os; } private LinkedList<StreamCacheEntry> _streamCache; @@ -2521,14 +2843,14 @@ namespace Ice { try { - ObjectPrx bb = b.ice_facet(f); - bool ok = bb.ice_isA("::Ice::Object"); + var bb = b.ice_facet(f); + var ok = bb.ice_isA("::Ice::Object"); Debug.Assert(ok); ObjectPrxHelper h = new ObjectPrxHelper(); - h.copyFrom__(bb); + h.iceCopyFrom(bb); d = h; } - catch(Ice.FacetNotExistException) + catch(FacetNotExistException) { } } @@ -2552,14 +2874,14 @@ namespace Ice { try { - ObjectPrx bb = b.ice_facet(f); - bool ok = bb.ice_isA("::Ice::Object", ctx); + var bb = b.ice_facet(f); + var ok = bb.ice_isA("::Ice::Object", ctx); Debug.Assert(ok); ObjectPrxHelper h = new ObjectPrxHelper(); - h.copyFrom__(bb); + h.iceCopyFrom(bb); d = h; } - catch(Ice.FacetNotExistException) + catch(FacetNotExistException) { } } @@ -2589,9 +2911,9 @@ namespace Ice ObjectPrx d = null; if(b != null) { - ObjectPrx bb = b.ice_facet(f); - ObjectPrxHelper h = new ObjectPrxHelper(); - h.copyFrom__(bb); + var bb = b.ice_facet(f); + var h = new ObjectPrxHelper(); + h.iceCopyFrom(bb); d = h; } return d; @@ -2605,7 +2927,7 @@ namespace Ice /// <returns>The type id, "::Ice::Object".</returns> public static string ice_staticId() { - return Ice.ObjectImpl.ice_staticId(); + return ObjectImpl.ice_staticId(); } } } diff --git a/csharp/src/Ice/ProxyFactory.cs b/csharp/src/Ice/ProxyFactory.cs index b5272ab45c7..4e7afb0b001 100644 --- a/csharp/src/Ice/ProxyFactory.cs +++ b/csharp/src/Ice/ProxyFactory.cs @@ -17,53 +17,52 @@ namespace IceInternal { public Ice.ObjectPrx stringToProxy(string str) { - Reference r = instance_.referenceFactory().create(str, null); + Reference r = _instance.referenceFactory().create(str, null); return referenceToProxy(r); } - + public string proxyToString(Ice.ObjectPrx proxy) { if(proxy != null) { Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase) proxy; - return h.reference__().ToString(); + return h.iceReference().ToString(); } else { return ""; } } - + public Ice.ObjectPrx propertyToProxy(string prefix) { - string proxy = instance_.initializationData().properties.getProperty(prefix); - Reference r = instance_.referenceFactory().create(proxy, prefix); + string proxy = _instance.initializationData().properties.getProperty(prefix); + Reference r = _instance.referenceFactory().create(proxy, prefix); return referenceToProxy(r); } - public Dictionary<string, string> - proxyToProperty(Ice.ObjectPrx proxy, string prefix) + public Dictionary<string, string> proxyToProperty(Ice.ObjectPrx proxy, string prefix) { if(proxy != null) { Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase) proxy; - return h.reference__().toProperty(prefix); + return h.iceReference().toProperty(prefix); } else { return new Dictionary<string, string>(); } } - - public Ice.ObjectPrx streamToProxy(BasicStream s) + + public Ice.ObjectPrx streamToProxy(Ice.InputStream s) { Ice.Identity ident = new Ice.Identity(); - ident.read__(s); - - Reference r = instance_.referenceFactory().create(ident, s); + ident.ice_readMembers(s); + + Reference r = _instance.referenceFactory().create(ident, s); return referenceToProxy(r); } - + public Ice.ObjectPrx referenceToProxy(Reference r) { if(r != null) @@ -77,29 +76,11 @@ namespace IceInternal return null; } } - - public void proxyToStream(Ice.ObjectPrx proxy, BasicStream s) - { - if(proxy != null) - { - Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase)proxy; - Reference r = h.reference__(); - r.getIdentity().write__(s); - r.streamWrite(s); - } - else - { - Ice.Identity ident = new Ice.Identity(); - ident.name = ""; - ident.category = ""; - ident.write__(s); - } - } - + public int checkRetryAfterException(Ice.LocalException ex, Reference @ref, ref int cnt) { - TraceLevels traceLevels = instance_.traceLevels(); - Ice.Logger logger = instance_.initializationData().logger; + TraceLevels traceLevels = _instance.traceLevels(); + Ice.Logger logger = _instance.initializationData().logger; // // We don't retry batch requests because the exception might have caused @@ -189,12 +170,13 @@ namespace IceInternal throw ex; } - // - // Don't retry if the communicator is destroyed or object adapter - // deactivated. + // Don't retry if the communicator is destroyed, object adapter is deactivated, + // or connection is manually closed. // - if(ex is Ice.CommunicatorDestroyedException || ex is Ice.ObjectAdapterDeactivatedException) + if(ex is Ice.CommunicatorDestroyedException || + ex is Ice.ObjectAdapterDeactivatedException || + ex is Ice.ConnectionManuallyClosedException) { throw ex; } @@ -202,7 +184,7 @@ namespace IceInternal // // Don't retry invocation timeouts. // - if(ex is Ice.InvocationTimeoutException || ex is Ice.InvocationCanceledException) + if(ex is Ice.InvocationTimeoutException || ex is Ice.InvocationCanceledException) { throw ex; } @@ -252,36 +234,36 @@ namespace IceInternal // internal ProxyFactory(Instance instance) { - instance_ = instance; - - string[] arr = instance_.initializationData().properties.getPropertyAsList("Ice.RetryIntervals"); + _instance = instance; + + string[] arr = _instance.initializationData().properties.getPropertyAsList("Ice.RetryIntervals"); if(arr.Length > 0) { _retryIntervals = new int[arr.Length]; - + for (int i = 0; i < arr.Length; i++) { int v; - + try { - v = System.Int32.Parse(arr[i], CultureInfo.InvariantCulture); + v = int.Parse(arr[i], CultureInfo.InvariantCulture); } catch(System.FormatException) { v = 0; } - + // // If -1 is the first value, no retry and wait intervals. - // + // if(i == 0 && v == -1) { _retryIntervals = new int[0]; break; } - + _retryIntervals[i] = v > 0?v:0; } } @@ -291,8 +273,8 @@ namespace IceInternal _retryIntervals[0] = 0; } } - - private Instance instance_; + + private Instance _instance; private int[] _retryIntervals; } diff --git a/csharp/src/Ice/ProxyIdentityKey.cs b/csharp/src/Ice/ProxyIdentityKey.cs index 6bfa9cad658..e566e6ffa02 100644 --- a/csharp/src/Ice/ProxyIdentityKey.cs +++ b/csharp/src/Ice/ProxyIdentityKey.cs @@ -27,7 +27,7 @@ namespace Ice public int GetHashCode(object obj) { int h = 5381; - IceInternal.HashUtil.hashAdd(ref h, ((Ice.ObjectPrx)obj).ice_getIdentity()); + IceInternal.HashUtil.hashAdd(ref h, ((ObjectPrx)obj).ice_getIdentity()); return h; } @@ -55,18 +55,18 @@ namespace Ice /// 0, otherwise.</returns> public int Compare(object obj1, object obj2) { - Ice.ObjectPrx proxy1 = obj1 as Ice.ObjectPrx; + ObjectPrx proxy1 = obj1 as ObjectPrx; if(obj1 != null && proxy1 == null) { - throw new System.ArgumentException("Argument must be derived from Ice.ObjectPrx", "obj1"); + throw new ArgumentException("Argument must be derived from Ice.ObjectPrx", "obj1"); } - Ice.ObjectPrx proxy2 = obj2 as Ice.ObjectPrx; + ObjectPrx proxy2 = obj2 as ObjectPrx; if(obj2 != null && proxy2 == null) { - throw new System.ArgumentException("Argument must be derived from Ice.ObjectPrx", "obj2"); + throw new ArgumentException("Argument must be derived from Ice.ObjectPrx", "obj2"); } - return Ice.Util.proxyIdentityCompare(proxy1, proxy2); + return Util.proxyIdentityCompare(proxy1, proxy2); } } @@ -84,8 +84,8 @@ namespace Ice /// <returns>The hash value for the proxy based on the identity and facet.</returns> public int GetHashCode(object obj) { - Ice.ObjectPrx o = (Ice.ObjectPrx)obj; - Ice.Identity identity = o.ice_getIdentity(); + ObjectPrx o = (ObjectPrx)obj; + Identity identity = o.ice_getIdentity(); string facet = o.ice_getFacet(); int h = 5381; IceInternal.HashUtil.hashAdd(ref h, identity); @@ -117,18 +117,18 @@ namespace Ice /// 0, otherwise.</returns> public int Compare(object obj1, object obj2) { - Ice.ObjectPrx proxy1 = obj1 as Ice.ObjectPrx; + ObjectPrx proxy1 = obj1 as ObjectPrx; if(obj1 != null && proxy1 == null) { - throw new System.ArgumentException("Argument must be derived from Ice.ObjectPrx", "obj1"); + throw new ArgumentException("Argument must be derived from Ice.ObjectPrx", "obj1"); } - Ice.ObjectPrx proxy2 = obj2 as Ice.ObjectPrx; + ObjectPrx proxy2 = obj2 as ObjectPrx; if(obj2 != null && proxy2 == null) { - throw new System.ArgumentException("Argument must be derived from Ice.ObjectPrx", "obj2"); + throw new ArgumentException("Argument must be derived from Ice.ObjectPrx", "obj2"); } - return Ice.Util.proxyIdentityAndFacetCompare(proxy1, proxy2); + return Util.proxyIdentityAndFacetCompare(proxy1, proxy2); } } diff --git a/csharp/src/Ice/Reference.cs b/csharp/src/Ice/Reference.cs index f1134b36ae3..80b985544db 100644 --- a/csharp/src/Ice/Reference.cs +++ b/csharp/src/Ice/Reference.cs @@ -8,7 +8,6 @@ // ********************************************************************** using System; -using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; @@ -35,7 +34,7 @@ namespace IceInternal public Mode getMode() { - return mode_; + return _mode; } public bool getSecure() @@ -45,43 +44,43 @@ namespace IceInternal public Ice.ProtocolVersion getProtocol() { - return protocol_; + return _protocol; } public Ice.EncodingVersion getEncoding() { - return encoding_; + return _encoding; } public Ice.Identity getIdentity() { - return identity_; + return _identity; } public string getFacet() { - return facet_; + return _facet; } public Instance getInstance() { - return instance_; + return _instance; } public Dictionary<string, string> getContext() { - return context_; + return _context; } public int getInvocationTimeout() { - return invocationTimeout_; + return _invocationTimeout; } public Ice.Communicator getCommunicator() { - return communicator_; + return _communicator; } public abstract EndpointI[] getEndpoints(); @@ -93,7 +92,7 @@ namespace IceInternal public abstract bool getPreferSecure(); public abstract Ice.EndpointSelectionType getEndpointSelection(); public abstract int getLocatorCacheTimeout(); - public abstract String getConnectionId(); + public abstract string getConnectionId(); // // The change* methods (here and in derived classes) create @@ -106,26 +105,26 @@ namespace IceInternal { newContext = _emptyContext; } - Reference r = instance_.referenceFactory().copy(this); + Reference r = _instance.referenceFactory().copy(this); if(newContext.Count == 0) { - r.context_ = _emptyContext; + r._context = _emptyContext; } else { - r.context_ = new Dictionary<string, string>(newContext); + r._context = new Dictionary<string, string>(newContext); } return r; } public Reference changeMode(Mode newMode) { - if(newMode == mode_) + if(newMode == _mode) { return this; } - Reference r = instance_.referenceFactory().copy(this); - r.mode_ = newMode; + Reference r = _instance.referenceFactory().copy(this); + r._mode = newMode; return r; } @@ -135,52 +134,52 @@ namespace IceInternal { return this; } - Reference r = instance_.referenceFactory().copy(this); + Reference r = _instance.referenceFactory().copy(this); r.secure_ = newSecure; return r; } public Reference changeIdentity(Ice.Identity newIdentity) { - if(newIdentity.Equals(identity_)) + if(newIdentity.Equals(_identity)) { return this; } - Reference r = instance_.referenceFactory().copy(this); - r.identity_ = newIdentity; // Identity is a value type, therefore a copy of newIdentity is made. + Reference r = _instance.referenceFactory().copy(this); + r._identity = newIdentity; // Identity is a value type, therefore a copy of newIdentity is made. return r; } public Reference changeFacet(string newFacet) { - if(newFacet.Equals(facet_)) + if(newFacet.Equals(_facet)) { return this; } - Reference r = instance_.referenceFactory().copy(this); - r.facet_ = newFacet; + Reference r = _instance.referenceFactory().copy(this); + r._facet = newFacet; return r; } public Reference changeInvocationTimeout(int newTimeout) { - if(newTimeout == invocationTimeout_) + if(newTimeout == _invocationTimeout) { return this; } - Reference r = instance_.referenceFactory().copy(this); - r.invocationTimeout_ = newTimeout; + Reference r = _instance.referenceFactory().copy(this); + r._invocationTimeout = newTimeout; return r; } public virtual Reference changeEncoding(Ice.EncodingVersion newEncoding) { - if(newEncoding.Equals(encoding_)) + if(newEncoding.Equals(_encoding)) { return this; } - Reference r = instance_.referenceFactory().copy(this); - r.encoding_ = newEncoding; + Reference r = _instance.referenceFactory().copy(this); + r._encoding = newEncoding; return r; } @@ -191,7 +190,7 @@ namespace IceInternal return this; } - Reference r = instance_.referenceFactory().copy(this); + Reference r = _instance.referenceFactory().copy(this); r.compress_ = newCompress; r.overrideCompress_ = true; return r; @@ -219,32 +218,51 @@ namespace IceInternal return hashValue_; } int h = 5381; - IceInternal.HashUtil.hashAdd(ref h, mode_); - IceInternal.HashUtil.hashAdd(ref h, secure_); - IceInternal.HashUtil.hashAdd(ref h, identity_); - IceInternal.HashUtil.hashAdd(ref h, context_); - IceInternal.HashUtil.hashAdd(ref h, facet_); - IceInternal.HashUtil.hashAdd(ref h, overrideCompress_); + HashUtil.hashAdd(ref h, _mode); + HashUtil.hashAdd(ref h, secure_); + HashUtil.hashAdd(ref h, _identity); + HashUtil.hashAdd(ref h, _context); + HashUtil.hashAdd(ref h, _facet); + HashUtil.hashAdd(ref h, overrideCompress_); if(overrideCompress_) { - IceInternal.HashUtil.hashAdd(ref h, compress_); + HashUtil.hashAdd(ref h, compress_); } - IceInternal.HashUtil.hashAdd(ref h, protocol_); - IceInternal.HashUtil.hashAdd(ref h, encoding_); - IceInternal.HashUtil.hashAdd(ref h, invocationTimeout_); + HashUtil.hashAdd(ref h, _protocol); + HashUtil.hashAdd(ref h, _encoding); + HashUtil.hashAdd(ref h, _invocationTimeout); hashValue_ = h; hashInitialized_ = true; return hashValue_; } } + public bool getCompressOverride(out bool compress) + { + DefaultsAndOverrides defaultsAndOverrides = getInstance().defaultsAndOverrides(); + if(defaultsAndOverrides.overrideCompress) + { + compress = defaultsAndOverrides.overrideCompressValue; + } + else if(overrideCompress_) + { + compress = compress_; + } + else + { + compress = false; + return false; + } + return true; + } + public abstract bool isIndirect(); public abstract bool isWellKnown(); // // Marshal the reference. // - public virtual void streamWrite(BasicStream s) + public virtual void streamWrite(Ice.OutputStream s) { // // Don't write the identity here. Operations calling streamWrite @@ -254,24 +272,24 @@ namespace IceInternal // // For compatibility with the old FacetPath. // - if(facet_.Length == 0) + if(_facet.Length == 0) { s.writeStringSeq(null); } else { - string[] facetPath = { facet_ }; + string[] facetPath = { _facet }; s.writeStringSeq(facetPath); } - s.writeByte((byte)mode_); + s.writeByte((byte)_mode); s.writeBool(secure_); - if(!s.getWriteEncoding().Equals(Ice.Util.Encoding_1_0)) + if(!s.getEncoding().Equals(Ice.Util.Encoding_1_0)) { - protocol_.write__(s); - encoding_.write__(s); + _protocol.ice_writeMembers(s); + _encoding.ice_writeMembers(s); } // Derived class writes the remainder of the reference. @@ -291,12 +309,14 @@ namespace IceInternal // StringBuilder s = new StringBuilder(); + Ice.ToStringMode toStringMode = _instance.toStringMode(); + // // If the encoded identity string contains characters which // the reference parser uses as separators, then we enclose // the identity string in quotes. // - string id = instance_.identityToString(identity_); + string id = Ice.Util.identityToString(_identity, toStringMode); if(IceUtilInternal.StringUtil.findFirstOf(id, " :@") != -1) { s.Append('"'); @@ -308,7 +328,7 @@ namespace IceInternal s.Append(id); } - if(facet_.Length > 0) + if(_facet.Length > 0) { // // If the encoded facet string contains characters which @@ -316,7 +336,7 @@ namespace IceInternal // the facet string in quotes. // s.Append(" -f "); - string fs = IceUtilInternal.StringUtil.escapeString(facet_, ""); + string fs = IceUtilInternal.StringUtil.escapeString(_facet, "", toStringMode); if(IceUtilInternal.StringUtil.findFirstOf(fs, " :@") != -1) { s.Append('"'); @@ -329,7 +349,7 @@ namespace IceInternal } } - switch(mode_) + switch(_mode) { case Mode.ModeTwoway: { @@ -367,7 +387,7 @@ namespace IceInternal s.Append(" -s"); } - if(!protocol_.Equals(Ice.Util.Protocol_1_0)) + if(!_protocol.Equals(Ice.Util.Protocol_1_0)) { // // We only print the protocol if it's not 1.0. It's fine as @@ -376,7 +396,7 @@ namespace IceInternal // stringToProxy. // s.Append(" -p "); - s.Append(Ice.Util.protocolVersionToString(protocol_)); + s.Append(Ice.Util.protocolVersionToString(_protocol)); } // @@ -385,7 +405,7 @@ namespace IceInternal // stringToProxy (and won't use Ice.Default.EncodingVersion). // s.Append(" -e "); - s.Append(Ice.Util.encodingVersionToString(encoding_)); + s.Append(Ice.Util.encodingVersionToString(_encoding)); return s.ToString(); @@ -406,7 +426,7 @@ namespace IceInternal Reference r = (Reference)obj; // Guaranteed to succeed. - if(mode_ != r.mode_) + if(_mode != r._mode) { return false; } @@ -416,17 +436,17 @@ namespace IceInternal return false; } - if(!identity_.Equals(r.identity_)) + if(!_identity.Equals(r._identity)) { return false; } - if(!Ice.CollectionComparer.Equals(context_, r.context_)) + if(!Ice.CollectionComparer.Equals(_context, r._context)) { return false; } - if(!facet_.Equals(r.facet_)) + if(!_facet.Equals(r._facet)) { return false; } @@ -440,17 +460,17 @@ namespace IceInternal return false; } - if(!protocol_.Equals(r.protocol_)) + if(!_protocol.Equals(r._protocol)) { return false; } - if(!encoding_.Equals(r.encoding_)) + if(!_encoding.Equals(r._encoding)) { return false; } - if(invocationTimeout_ != r.invocationTimeout_) + if(_invocationTimeout != r._invocationTimeout) { return false; } @@ -458,7 +478,7 @@ namespace IceInternal return true; } - public Object Clone() + public object Clone() { // // A member-wise copy is safe because the members are immutable. @@ -470,17 +490,17 @@ namespace IceInternal protected bool hashInitialized_; private static Dictionary<string, string> _emptyContext = new Dictionary<string, string>(); - private Instance instance_; - private Ice.Communicator communicator_; + private Instance _instance; + private Ice.Communicator _communicator; - private Mode mode_; - private Ice.Identity identity_; - private Dictionary<string, string> context_; - private string facet_; + private Mode _mode; + private Ice.Identity _identity; + private Dictionary<string, string> _context; + private string _facet; protected bool secure_; - private Ice.ProtocolVersion protocol_; - private Ice.EncodingVersion encoding_; - private int invocationTimeout_; + private Ice.ProtocolVersion _protocol; + private Ice.EncodingVersion _encoding; + private int _invocationTimeout; protected bool overrideCompress_; protected bool compress_; // Only used if _overrideCompress == true @@ -503,22 +523,22 @@ namespace IceInternal Debug.Assert(identity.category != null); Debug.Assert(facet != null); - instance_ = instance; - communicator_ = communicator; - mode_ = mode; - identity_ = identity; - context_ = context != null ? new Dictionary<string, string>(context) : _emptyContext; - facet_ = facet; - protocol_ = protocol; - encoding_ = encoding; - invocationTimeout_ = invocationTimeout; + _instance = instance; + _communicator = communicator; + _mode = mode; + _identity = identity; + _context = context != null ? new Dictionary<string, string>(context) : _emptyContext; + _facet = facet; + _protocol = protocol; + _encoding = encoding; + _invocationTimeout = invocationTimeout; secure_ = secure; hashInitialized_ = false; overrideCompress_ = false; compress_ = false; } - protected static System.Random rand_ = new System.Random(unchecked((int)System.DateTime.Now.Ticks)); + protected static Random rand_ = new Random(unchecked((int)DateTime.Now.Ticks)); } public class FixedReference : Reference @@ -527,7 +547,7 @@ namespace IceInternal Ice.Communicator communicator, Ice.Identity identity, string facet, - Reference.Mode mode, + Mode mode, bool secure, Ice.EncodingVersion encoding, Ice.ConnectionI connection) @@ -651,12 +671,7 @@ namespace IceInternal return false; } - public override void streamWrite(BasicStream s) - { - throw new Ice.FixedProxyException(); - } - - public override string ToString() + public override void streamWrite(Ice.OutputStream s) { throw new Ice.FixedProxyException(); } @@ -670,9 +685,9 @@ namespace IceInternal { switch(getMode()) { - case Reference.Mode.ModeTwoway: - case Reference.Mode.ModeOneway: - case Reference.Mode.ModeBatchOneway: + case Mode.ModeTwoway: + case Mode.ModeOneway: + case Mode.ModeBatchOneway: { if(_fixedConnection.endpoint().datagram()) { @@ -681,8 +696,8 @@ namespace IceInternal break; } - case Reference.Mode.ModeDatagram: - case Reference.Mode.ModeBatchDatagram: + case Mode.ModeDatagram: + case Mode.ModeBatchDatagram: { if(!_fixedConnection.endpoint().datagram()) { @@ -713,7 +728,7 @@ namespace IceInternal _fixedConnection.throwException(); // Throw in case our connection is already destroyed. - bool compress; + bool compress = false; if(defaultsAndOverrides.overrideCompress) { compress = defaultsAndOverrides.overrideCompressValue; @@ -722,14 +737,8 @@ namespace IceInternal { compress = compress_; } - else - { - compress = _fixedConnection.endpoint().compress(); - } - return ((Ice.ObjectPrxHelperBase)proxy).setRequestHandler__(new ConnectionRequestHandler(this, - _fixedConnection, - compress)); + return proxy.iceSetRequestHandler(new ConnectionRequestHandler(this, _fixedConnection, compress)); } public override BatchRequestQueue getBatchRequestQueue() @@ -739,7 +748,7 @@ namespace IceInternal public override bool Equals(object obj) { - if(object.ReferenceEquals(this, obj)) + if(ReferenceEquals(this, obj)) { return true; } @@ -851,7 +860,7 @@ namespace IceInternal public override Reference changeEndpoints(EndpointI[] newEndpoints) { - if(Array.Equals(newEndpoints, _endpoints)) + if(Equals(newEndpoints, _endpoints)) { return this; } @@ -1005,7 +1014,7 @@ namespace IceInternal return _endpoints.Length == 0 && _adapterId.Length == 0; } - public override void streamWrite(BasicStream s) + public override void streamWrite(Ice.OutputStream s) { base.streamWrite(s); @@ -1058,7 +1067,7 @@ namespace IceInternal // the reference parser uses as separators, then we enclose // the adapter id string in quotes. // - string a = IceUtilInternal.StringUtil.escapeString(_adapterId, null); + string a = IceUtilInternal.StringUtil.escapeString(_adapterId, null, getInstance().toStringMode()); if(IceUtilInternal.StringUtil.findFirstOf(a, " :@") != -1) { s.Append('"'); @@ -1089,7 +1098,7 @@ namespace IceInternal if(_routerInfo != null) { Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase)_routerInfo.getRouter(); - Dictionary<String, String> routerProperties = h.reference__().toProperty(prefix + ".Router"); + Dictionary<string, string> routerProperties = h.iceReference().toProperty(prefix + ".Router"); foreach(KeyValuePair<string, string> entry in routerProperties) { properties[entry.Key] = entry.Value; @@ -1099,7 +1108,7 @@ namespace IceInternal if(_locatorInfo != null) { Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase)_locatorInfo.getLocator(); - Dictionary<String, String> locatorProperties = h.reference__().toProperty(prefix + ".Locator"); + Dictionary<string, string> locatorProperties = h.iceReference().toProperty(prefix + ".Locator"); foreach(KeyValuePair<string, string> entry in locatorProperties) { properties[entry.Key] = entry.Value; @@ -1119,7 +1128,7 @@ namespace IceInternal if(!hashInitialized_) { int h = base.GetHashCode(); // Initializes hashValue_. - IceInternal.HashUtil.hashAdd(ref h, _adapterId); + HashUtil.hashAdd(ref h, _adapterId); hashValue_ = h; } return hashValue_; @@ -1128,7 +1137,7 @@ namespace IceInternal public override bool Equals(object obj) { - if(Object.ReferenceEquals(this, obj)) + if(ReferenceEquals(this, obj)) { return true; } @@ -1195,7 +1204,6 @@ namespace IceInternal return true; } - private sealed class RouterEndpointsCallback : RouterInfo.GetClientEndpointsCallback { internal RouterEndpointsCallback(RoutableReference ir, GetConnectionCallback cb) @@ -1352,7 +1360,7 @@ namespace IceInternal Ice.Communicator communicator, Ice.Identity identity, string facet, - Reference.Mode mode, + Mode mode, bool secure, Ice.ProtocolVersion protocol, Ice.EncodingVersion encoding, @@ -1419,7 +1427,7 @@ namespace IceInternal // for(int i = 0; i < allEndpoints.Length; i++) { - if(!(allEndpoints[i] is IceInternal.OpaqueEndpointI)) + if(!(allEndpoints[i] is OpaqueEndpointI)) { endpoints.Add(allEndpoints[i]); } @@ -1430,9 +1438,9 @@ namespace IceInternal // switch(getMode()) { - case Reference.Mode.ModeTwoway: - case Reference.Mode.ModeOneway: - case Reference.Mode.ModeBatchOneway: + case Mode.ModeTwoway: + case Mode.ModeOneway: + case Mode.ModeBatchOneway: { // // Filter out datagram endpoints. @@ -1449,8 +1457,8 @@ namespace IceInternal break; } - case Reference.Mode.ModeDatagram: - case Reference.Mode.ModeBatchDatagram: + case Mode.ModeDatagram: + case Mode.ModeBatchDatagram: { // // Filter out non-datagram endpoints. @@ -1622,14 +1630,14 @@ namespace IceInternal } } - private class EndpointComparator : IComparer<IceInternal.EndpointI> + private class EndpointComparator : IComparer<EndpointI> { public EndpointComparator(bool preferSecure) { _preferSecure = preferSecure; } - public int Compare(IceInternal.EndpointI le, IceInternal.EndpointI re) + public int Compare(EndpointI le, EndpointI re) { bool ls = le.secure(); bool rs = re.secure(); diff --git a/csharp/src/Ice/ReferenceFactory.cs b/csharp/src/Ice/ReferenceFactory.cs index 1ae453e0937..e839b1a95ee 100644 --- a/csharp/src/Ice/ReferenceFactory.cs +++ b/csharp/src/Ice/ReferenceFactory.cs @@ -8,7 +8,6 @@ // ********************************************************************** using System; -using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; @@ -57,13 +56,13 @@ namespace IceInternal // Create new reference // return new FixedReference( - instance_, + _instance, _communicator, ident, "", // Facet connection.endpoint().datagram() ? Reference.Mode.ModeDatagram : Reference.Mode.ModeTwoway, connection.endpoint().secure(), - instance_.defaultsAndOverrides().defaultEncoding, + _instance.defaultsAndOverrides().defaultEncoding, connection); } @@ -135,7 +134,7 @@ namespace IceInternal // // Parsing the identity may raise IdentityParseException. // - Ice.Identity ident = instance_.stringToIdentity(idstr); + Ice.Identity ident = Ice.Util.stringToIdentity(idstr); if(ident.name.Length == 0) { @@ -170,7 +169,7 @@ namespace IceInternal string facet = ""; Reference.Mode mode = Reference.Mode.ModeTwoway; bool secure = false; - Ice.EncodingVersion encoding = instance_.defaultsAndOverrides().defaultEncoding; + Ice.EncodingVersion encoding = _instance.defaultsAndOverrides().defaultEncoding; Ice.ProtocolVersion protocol = Ice.Util.Protocol_1_0; string adapter = ""; @@ -261,9 +260,9 @@ namespace IceInternal try { - facet = IceUtilInternal.StringUtil.unescapeString(argument, 0, argument.Length); + facet = IceUtilInternal.StringUtil.unescapeString(argument, 0, argument.Length, ""); } - catch(System.ArgumentException argEx) + catch(ArgumentException argEx) { Ice.ProxyParseException e = new Ice.ProxyParseException(); e.str = "invalid facet in `" + s + "': " + argEx.Message; @@ -422,14 +421,14 @@ namespace IceInternal int quote = beg; while(true) { - quote = s.IndexOf((System.Char) '\"', quote); + quote = s.IndexOf('\"', quote); if(quote == -1 || end < quote) { break; } else { - quote = s.IndexOf((System.Char) '\"', ++quote); + quote = s.IndexOf('\"', ++quote); if(quote == -1) { break; @@ -451,7 +450,7 @@ namespace IceInternal } string es = s.Substring(beg, end - beg); - EndpointI endp = instance_.endpointFactoryManager().create(es, false); + EndpointI endp = _instance.endpointFactoryManager().create(es, false); if(endp != null) { endpoints.Add(endp); @@ -469,7 +468,7 @@ namespace IceInternal throw e2; } else if(unknownEndpoints.Count != 0 && - instance_.initializationData().properties.getPropertyAsIntWithDefault( + _instance.initializationData().properties.getPropertyAsIntWithDefault( "Ice.Warn.Endpoints", 1) > 0) { StringBuilder msg = new StringBuilder("Proxy contains unknown endpoints:"); @@ -477,10 +476,10 @@ namespace IceInternal for(int idx = 0; idx < sz; ++idx) { msg.Append(" `"); - msg.Append((string)unknownEndpoints[idx]); + msg.Append(unknownEndpoints[idx]); msg.Append("'"); } - instance_.initializationData().logger.warning(msg.ToString()); + _instance.initializationData().logger.warning(msg.ToString()); } EndpointI[] ep = endpoints.ToArray(); @@ -529,9 +528,9 @@ namespace IceInternal try { - adapter = IceUtilInternal.StringUtil.unescapeString(adapterstr, 0, adapterstr.Length); + adapter = IceUtilInternal.StringUtil.unescapeString(adapterstr, 0, adapterstr.Length, ""); } - catch(System.ArgumentException argEx) + catch(ArgumentException argEx) { Ice.ProxyParseException e = new Ice.ProxyParseException(); e.str = "invalid adapter id in `" + s + "': " + argEx.Message; @@ -551,7 +550,7 @@ namespace IceInternal throw ex; } - public Reference create(Ice.Identity ident, BasicStream s) + public Reference create(Ice.Identity ident, Ice.InputStream s) { // // Don't read the identity here. Operations calling this @@ -581,7 +580,7 @@ namespace IceInternal facet = ""; } - int mode = (int)s.readByte(); + int mode = s.readByte(); if(mode < 0 || mode > (int)Reference.Mode.ModeLast) { throw new Ice.ProxyUnmarshalException(); @@ -591,12 +590,12 @@ namespace IceInternal Ice.ProtocolVersion protocol; Ice.EncodingVersion encoding; - if(!s.getReadEncoding().Equals(Ice.Util.Encoding_1_0)) + if(!s.getEncoding().Equals(Ice.Util.Encoding_1_0)) { protocol = new Ice.ProtocolVersion(); - protocol.read__(s); + protocol.ice_readMembers(s); encoding = new Ice.EncodingVersion(); - encoding.read__(s); + encoding.ice_readMembers(s); } else { @@ -613,7 +612,7 @@ namespace IceInternal endpoints = new EndpointI[sz]; for(int i = 0; i < sz; i++) { - endpoints[i] = instance_.endpointFactoryManager().read(s); + endpoints[i] = _instance.endpointFactoryManager().read(s); } } else @@ -631,7 +630,7 @@ namespace IceInternal return this; } - ReferenceFactory factory = new ReferenceFactory(instance_, _communicator); + ReferenceFactory factory = new ReferenceFactory(_instance, _communicator); factory._defaultLocator = _defaultLocator; factory._defaultRouter = defaultRouter; return factory; @@ -649,7 +648,7 @@ namespace IceInternal return this; } - ReferenceFactory factory = new ReferenceFactory(instance_, _communicator); + ReferenceFactory factory = new ReferenceFactory(_instance, _communicator); factory._defaultLocator = defaultLocator; factory._defaultRouter = _defaultRouter; return factory; @@ -665,7 +664,7 @@ namespace IceInternal // internal ReferenceFactory(Instance instance, Ice.Communicator communicator) { - instance_ = instance; + _instance = instance; _communicator = communicator; } @@ -683,14 +682,14 @@ namespace IceInternal }; private void - checkForUnknownProperties(String prefix) + checkForUnknownProperties(string prefix) { // // Do not warn about unknown properties if Ice prefix, ie Ice, Glacier2, etc // - for(int i = 0; IceInternal.PropertyNames.clPropNames[i] != null; ++i) + for(int i = 0; PropertyNames.clPropNames[i] != null; ++i) { - if(prefix.StartsWith(IceInternal.PropertyNames.clPropNames[i] + ".", StringComparison.Ordinal)) + if(prefix.StartsWith(PropertyNames.clPropNames[i] + ".", StringComparison.Ordinal)) { return; } @@ -698,8 +697,8 @@ namespace IceInternal List<string> unknownProps = new List<string>(); Dictionary<string, string> props - = instance_.initializationData().properties.getPropertiesForPrefix(prefix + "."); - foreach(String prop in props.Keys) + = _instance.initializationData().properties.getPropertiesForPrefix(prefix + "."); + foreach(string prop in props.Keys) { bool valid = false; for(int i = 0; i < _suffixes.Length; ++i) @@ -728,7 +727,7 @@ namespace IceInternal message.Append("\n "); message.Append(s); } - instance_.initializationData().logger.warning(message.ToString()); + _instance.initializationData().logger.warning(message.ToString()); } } @@ -742,7 +741,7 @@ namespace IceInternal string adapterId, string propertyPrefix) { - DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides(); + DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides(); // // Default local proxy options. @@ -750,17 +749,17 @@ namespace IceInternal LocatorInfo locatorInfo = null; if(_defaultLocator != null) { - if(!((Ice.ObjectPrxHelperBase)_defaultLocator).reference__().getEncoding().Equals(encoding)) + if(!((Ice.ObjectPrxHelperBase)_defaultLocator).iceReference().getEncoding().Equals(encoding)) { - locatorInfo = instance_.locatorManager().get( + locatorInfo = _instance.locatorManager().get( (Ice.LocatorPrx)_defaultLocator.ice_encodingVersion(encoding)); } else { - locatorInfo = instance_.locatorManager().get(_defaultLocator); + locatorInfo = _instance.locatorManager().get(_defaultLocator); } } - RouterInfo routerInfo = instance_.routerManager().get(_defaultRouter); + RouterInfo routerInfo = _instance.routerManager().get(_defaultRouter); bool collocOptimized = defaultsAndOverrides.defaultCollocationOptimization; bool cacheConnection = true; bool preferSecure = defaultsAndOverrides.defaultPreferSecure; @@ -774,7 +773,7 @@ namespace IceInternal // if(propertyPrefix != null && propertyPrefix.Length > 0) { - Ice.Properties properties = instance_.initializationData().properties; + Ice.Properties properties = _instance.initializationData().properties; // // Warn about unknown properties. @@ -790,14 +789,14 @@ namespace IceInternal Ice.LocatorPrx locator = Ice.LocatorPrxHelper.uncheckedCast(_communicator.propertyToProxy(property)); if(locator != null) { - if(!((Ice.ObjectPrxHelperBase)locator).reference__().getEncoding().Equals(encoding)) + if(!((Ice.ObjectPrxHelperBase)locator).iceReference().getEncoding().Equals(encoding)) { - locatorInfo = instance_.locatorManager().get( + locatorInfo = _instance.locatorManager().get( (Ice.LocatorPrx)locator.ice_encodingVersion(encoding)); } else { - locatorInfo = instance_.locatorManager().get(locator); + locatorInfo = _instance.locatorManager().get(locator); } } @@ -809,11 +808,11 @@ namespace IceInternal { string s = "`" + property + "=" + properties.getProperty(property) + "': cannot set a router on a router; setting ignored"; - instance_.initializationData().logger.warning(s); + _instance.initializationData().logger.warning(s); } else { - routerInfo = instance_.routerManager().get(router); + routerInfo = _instance.routerManager().get(router); } } @@ -859,7 +858,7 @@ namespace IceInternal msg.Append(" `"); msg.Append(properties.getProperty(property)); msg.Append("': defaulting to -1"); - instance_.initializationData().logger.warning(msg.ToString()); + _instance.initializationData().logger.warning(msg.ToString()); } } @@ -877,7 +876,7 @@ namespace IceInternal msg.Append(" `"); msg.Append(properties.getProperty(property)); msg.Append("': defaulting to -1"); - instance_.initializationData().logger.warning(msg.ToString()); + _instance.initializationData().logger.warning(msg.ToString()); } } @@ -896,7 +895,7 @@ namespace IceInternal // // Create new reference // - return new RoutableReference(instance_, + return new RoutableReference(_instance, _communicator, ident, facet, @@ -917,7 +916,7 @@ namespace IceInternal context); } - private Instance instance_; + private Instance _instance; private Ice.Communicator _communicator; private Ice.RouterPrx _defaultRouter; private Ice.LocatorPrx _defaultLocator; diff --git a/csharp/src/Ice/RequestHandler.cs b/csharp/src/Ice/RequestHandler.cs index 4a0c8dc4df6..7a5ae7a4111 100644 --- a/csharp/src/Ice/RequestHandler.cs +++ b/csharp/src/Ice/RequestHandler.cs @@ -7,9 +7,6 @@ // // ********************************************************************** -using System.Collections.Generic; -using Ice.Instrumentation; - namespace IceInternal { public interface CancellationHandler @@ -21,7 +18,7 @@ namespace IceInternal { RequestHandler update(RequestHandler previousHandler, RequestHandler newHandler); - bool sendAsyncRequest(ProxyOutgoingAsyncBase @out, out Ice.AsyncCallback cb); + int sendAsyncRequest(ProxyOutgoingAsyncBase @out); Reference getReference(); diff --git a/csharp/src/Ice/RequestHandlerFactory.cs b/csharp/src/Ice/RequestHandlerFactory.cs index 16aef9dc84e..eacec5cb736 100644 --- a/csharp/src/Ice/RequestHandlerFactory.cs +++ b/csharp/src/Ice/RequestHandlerFactory.cs @@ -8,7 +8,6 @@ // ********************************************************************** using System.Collections.Generic; -using System.Diagnostics; namespace IceInternal { @@ -27,7 +26,7 @@ namespace IceInternal Ice.ObjectAdapter adapter = _instance.objectAdapterFactory().findObjectAdapter(proxy); if(adapter != null) { - return proxy.setRequestHandler__(new CollocatedRequestHandler(rf, adapter)); + return proxy.iceSetRequestHandler(new CollocatedRequestHandler(rf, adapter)); } } @@ -55,7 +54,7 @@ namespace IceInternal { rf.getConnection(handler); } - return proxy.setRequestHandler__(handler.connect(proxy)); + return proxy.iceSetRequestHandler(handler.connect(proxy)); } internal void diff --git a/csharp/src/Ice/ResponseHandler.cs b/csharp/src/Ice/ResponseHandler.cs index 896b2250767..2a2adf21983 100644 --- a/csharp/src/Ice/ResponseHandler.cs +++ b/csharp/src/Ice/ResponseHandler.cs @@ -14,9 +14,9 @@ namespace IceInternal { public interface ResponseHandler { - void sendResponse(int requestId, BasicStream os, byte status, bool amd); + void sendResponse(int requestId, Ice.OutputStream os, byte status, bool amd); void sendNoResponse(); bool systemException(int requestId, Ice.SystemException ex, bool amd); void invokeException(int requestId, Ice.LocalException ex, int invokeNum, bool amd); - }; + } } diff --git a/csharp/src/Ice/RetryQueue.cs b/csharp/src/Ice/RetryQueue.cs index 083f2a4e5e5..ed20ec49471 100644 --- a/csharp/src/Ice/RetryQueue.cs +++ b/csharp/src/Ice/RetryQueue.cs @@ -41,13 +41,12 @@ namespace IceInternal { if(_instance.traceLevels().retry >= 1) { - string s = "operation retry canceled\n" + ex; - _instance.initializationData().logger.trace(_instance.traceLevels().retryCat, s); + _instance.initializationData().logger.trace(_instance.traceLevels().retryCat, + string.Format("operation retry canceled\n{0}", ex)); } - Ice.AsyncCallback cb = _outAsync.completed(ex); - if(cb != null) + if(_outAsync.exception(ex)) { - _outAsync.invokeCompletedAsync(cb); + _outAsync.invokeExceptionAsync(); } } } diff --git a/csharp/src/Ice/RouterInfo.cs b/csharp/src/Ice/RouterInfo.cs index 0fb7b57956f..1e1a7bd9057 100644 --- a/csharp/src/Ice/RouterInfo.cs +++ b/csharp/src/Ice/RouterInfo.cs @@ -9,8 +9,6 @@ namespace IceInternal { - - using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -46,9 +44,9 @@ namespace IceInternal } } - public override bool Equals(System.Object obj) + public override bool Equals(object obj) { - if(object.ReferenceEquals(this, obj)) + if(ReferenceEquals(this, obj)) { return true; } @@ -97,15 +95,18 @@ namespace IceInternal return; } - _router.begin_getClientProxy().whenCompleted( - (Ice.ObjectPrx proxy) => - { - callback.setEndpoints(setClientEndpoints(proxy)); - }, - (Ice.Exception ex) => + _router.getClientProxyAsync().ContinueWith( + (t) => { - Debug.Assert(ex is Ice.LocalException); - callback.setException((Ice.LocalException)ex); + try + { + callback.setEndpoints(setClientEndpoints(t.Result)); + } + catch(System.AggregateException ae) + { + Debug.Assert(ae.InnerException is Ice.LocalException); + callback.setException((Ice.LocalException)ae.InnerException); + } }); } @@ -153,18 +154,21 @@ namespace IceInternal return true; } } - _router.begin_addProxies(new Ice.ObjectPrx[] { proxy }).whenCompleted( - (Ice.ObjectPrx[] evictedProxies) => - { - addAndEvictProxies(proxy, evictedProxies); - callback.addedProxy(); - }, - (Ice.Exception ex) => + + _router.addProxiesAsync(new Ice.ObjectPrx[] { proxy }).ContinueWith( + (t) => { - Debug.Assert(ex is Ice.LocalException); - callback.setException((Ice.LocalException)ex); + try + { + addAndEvictProxies(proxy, t.Result); + callback.addedProxy(); + } + catch(System.AggregateException ae) + { + Debug.Assert(ae.InnerException is Ice.LocalException); + callback.setException((Ice.LocalException)ae.InnerException); + } }); - return false; } @@ -203,7 +207,7 @@ namespace IceInternal // // If getClientProxy() return nil, use router endpoints. // - _clientEndpoints = ((Ice.ObjectPrxHelperBase)_router).reference__().getEndpoints(); + _clientEndpoints = ((Ice.ObjectPrxHelperBase)_router).iceReference().getEndpoints(); } else { @@ -219,7 +223,7 @@ namespace IceInternal clientProxy = clientProxy.ice_timeout(_router.ice_getConnection().timeout()); } - _clientEndpoints = ((Ice.ObjectPrxHelperBase)clientProxy).reference__().getEndpoints(); + _clientEndpoints = ((Ice.ObjectPrxHelperBase)clientProxy).iceReference().getEndpoints(); } } return _clientEndpoints; @@ -236,7 +240,7 @@ namespace IceInternal } serverProxy = serverProxy.ice_router(null); // The server proxy cannot be routed. - _serverEndpoints = ((Ice.ObjectPrxHelperBase)serverProxy).reference__().getEndpoints(); + _serverEndpoints = ((Ice.ObjectPrxHelperBase)serverProxy).iceReference().getEndpoints(); return _serverEndpoints; } } diff --git a/csharp/src/Ice/ServantManager.cs b/csharp/src/Ice/ServantManager.cs index f9e836d46cc..7b246a70cc2 100644 --- a/csharp/src/Ice/ServantManager.cs +++ b/csharp/src/Ice/ServantManager.cs @@ -19,7 +19,7 @@ public sealed class ServantManager { lock(this) { - Debug.Assert(instance_ != null); // Must not be called after destruction. + Debug.Assert(_instance != null); // Must not be called after destruction. if(facet == null) { @@ -37,11 +37,11 @@ public sealed class ServantManager if(m.ContainsKey(facet)) { Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); - ex.id = instance_.identityToString(ident); + ex.id = Ice.Util.identityToString(ident, _instance.toStringMode()); ex.kindOfObject = "servant"; if(facet.Length > 0) { - ex.id += " -f " + IceUtilInternal.StringUtil.escapeString(facet, ""); + ex.id += " -f " + IceUtilInternal.StringUtil.escapeString(facet, "", _instance.toStringMode()); } throw ex; } @@ -55,7 +55,7 @@ public sealed class ServantManager { lock(this) { - Debug.Assert(instance_ != null); // Must not be called after destruction. + Debug.Assert(_instance != null); // Must not be called after destruction. Ice.Object obj = null; _defaultServantMap.TryGetValue(category, out obj); if(obj != null) @@ -74,7 +74,7 @@ public sealed class ServantManager { lock(this) { - Debug.Assert(instance_ != null); // Must not be called after destruction. + Debug.Assert(_instance != null); // Must not be called after destruction. if(facet == null) { @@ -87,11 +87,11 @@ public sealed class ServantManager if(m == null || !m.ContainsKey(facet)) { Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); - ex.id = Ice.Util.identityToString(ident); + ex.id = Ice.Util.identityToString(ident, _instance.toStringMode()); ex.kindOfObject = "servant"; if(facet.Length > 0) { - ex.id += " -f " + IceUtilInternal.StringUtil.escapeString(facet, ""); + ex.id += " -f " + IceUtilInternal.StringUtil.escapeString(facet, "", _instance.toStringMode()); } throw ex; } @@ -110,7 +110,7 @@ public sealed class ServantManager { lock(this) { - Debug.Assert(instance_ != null); // Must not be called after destruction. + Debug.Assert(_instance != null); // Must not be called after destruction. Ice.Object obj = null; _defaultServantMap.TryGetValue(category, out obj); @@ -131,14 +131,14 @@ public sealed class ServantManager { lock(this) { - Debug.Assert(instance_ != null); + Debug.Assert(_instance != null); Dictionary<string, Ice.Object> m; _servantMapMap.TryGetValue(ident, out m); if(m == null) { Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); - ex.id = Ice.Util.identityToString(ident); + ex.id = Ice.Util.identityToString(ident, _instance.toStringMode()); ex.kindOfObject = "servant"; throw ex; } @@ -158,7 +158,7 @@ public sealed class ServantManager // requests are received over the bidir connection after the // adapter was deactivated. // - //Debug.Assert(instance_ != null); // Must not be called after destruction. + //Debug.Assert(_instance != null); // Must not be called after destruction. if(facet == null) { @@ -189,7 +189,7 @@ public sealed class ServantManager { lock(this) { - Debug.Assert(instance_ != null); // Must not be called after destruction. + Debug.Assert(_instance != null); // Must not be called after destruction. Ice.Object obj = null; _defaultServantMap.TryGetValue(category, out obj); @@ -201,7 +201,7 @@ public sealed class ServantManager { lock(this) { - Debug.Assert(instance_ != null); // Must not be called after destruction. + Debug.Assert(_instance != null); // Must not be called after destruction. Dictionary<string, Ice.Object> m = _servantMapMap[ident]; if(m != null) @@ -224,7 +224,7 @@ public sealed class ServantManager // adapter was deactivated. // // - //Debug.Assert(instance_ != null); // Must not be called after destruction. + //Debug.Assert(_instance != null); // Must not be called after destruction. Dictionary<string, Ice.Object> m; _servantMapMap.TryGetValue(ident, out m); @@ -244,14 +244,14 @@ public sealed class ServantManager { lock(this) { - Debug.Assert(instance_ != null); // Must not be called after destruction. + Debug.Assert(_instance != null); // Must not be called after destruction. Ice.ServantLocator l; _locatorMap.TryGetValue(category, out l); if(l != null) { Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); - ex.id = IceUtilInternal.StringUtil.escapeString(category, ""); + ex.id = IceUtilInternal.StringUtil.escapeString(category, "", _instance.toStringMode()); ex.kindOfObject = "servant locator"; throw ex; } @@ -264,14 +264,14 @@ public sealed class ServantManager { lock(this) { - Debug.Assert(instance_ != null); // Must not be called after destruction. + Debug.Assert(_instance != null); // Must not be called after destruction. Ice.ServantLocator l; _locatorMap.TryGetValue(category, out l); if(l == null) { Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); - ex.id = IceUtilInternal.StringUtil.escapeString(category, ""); + ex.id = IceUtilInternal.StringUtil.escapeString(category, "", _instance.toStringMode()); ex.kindOfObject = "servant locator"; throw ex; } @@ -291,7 +291,7 @@ public sealed class ServantManager // adapter was deactivated. // // - //Debug.Assert(instance_ != null); // Must not be called after destruction. + //Debug.Assert(_instance != null); // Must not be called after destruction. Ice.ServantLocator result; _locatorMap.TryGetValue(category, out result); @@ -304,7 +304,7 @@ public sealed class ServantManager // public ServantManager(Instance instance, string adapterName) { - instance_ = instance; + _instance = instance; _adapterName = adapterName; } @@ -318,7 +318,7 @@ public sealed class ServantManager // //lock(this) //{ - //IceUtil.Assert.FinalizerAssert(instance_ == null); + //IceUtil.Assert.FinalizerAssert(_instance == null); //} } */ @@ -335,12 +335,12 @@ public sealed class ServantManager // // If the ServantManager has already been destroyed, we're done. // - if(instance_ == null) + if(_instance == null) { return; } - logger = instance_.initializationData().logger; + logger = _instance.initializationData().logger; _servantMapMap.Clear(); @@ -349,7 +349,7 @@ public sealed class ServantManager locatorMap = new Dictionary<string, Ice.ServantLocator>(_locatorMap); _locatorMap.Clear(); - instance_ = null; + _instance = null; } foreach(KeyValuePair<string, Ice.ServantLocator> p in locatorMap) @@ -368,7 +368,7 @@ public sealed class ServantManager } } - private Instance instance_; + private Instance _instance; private readonly string _adapterName; private Dictionary <Ice.Identity, Dictionary<string, Ice.Object>> _servantMapMap = new Dictionary<Ice.Identity, Dictionary<string, Ice.Object>>(); diff --git a/csharp/src/Ice/SliceChecksums.cs b/csharp/src/Ice/SliceChecksums.cs index 00c862a4587..235d1e11429 100644 --- a/csharp/src/Ice/SliceChecksums.cs +++ b/csharp/src/Ice/SliceChecksums.cs @@ -9,7 +9,6 @@ namespace Ice { - using System; using System.Collections; using System.Collections.Generic; @@ -18,8 +17,6 @@ namespace Ice public sealed class SliceChecksums { public static Dictionary<string, string> checksums = new Dictionary<string, string>(); - -#if !COMPACT && !SILVERLIGHT static SliceChecksums() { Type[] types = IceInternal.AssemblyUtil.findTypesWithPrefix("IceInternal.SliceChecksums"); @@ -33,7 +30,6 @@ namespace Ice } } } -#endif } } diff --git a/csharp/src/Ice/SlicedData.cs b/csharp/src/Ice/SlicedData.cs index dc7bee51db4..ab8a79aa93f 100644 --- a/csharp/src/Ice/SlicedData.cs +++ b/csharp/src/Ice/SlicedData.cs @@ -46,9 +46,9 @@ namespace Ice public byte[] bytes; /// <summary> - /// The Ice objects referenced by this slice. + /// The class instances referenced by this slice. /// </summary> - public Ice.Object[] objects; + public Value[] instances; /// <summary> /// Whether or not the slice contains optional members. diff --git a/csharp/src/Ice/Stream.cs b/csharp/src/Ice/Stream.cs deleted file mode 100644 index 91a10752c3e..00000000000 --- a/csharp/src/Ice/Stream.cs +++ /dev/null @@ -1,705 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -using System.Diagnostics; - -namespace Ice -{ - /// <summary> - /// Callback class to inform an application when a Slice class has been unmarshaled - /// from an input stream. - /// </summary> - public interface ReadObjectCallback - { - /// <summary> - /// The Ice run time calls this method when it has fully unmarshaled the state - /// of a Slice class. - /// </summary> - /// <param name="obj">The unmarshaled Slice class.</param> - void invoke(Ice.Object obj); - } - - /// <summary> - /// Interface for input streams used to extract Slice types from a sequence of bytes. - /// </summary> - public interface InputStream - { - /// <summary> - /// Returns the communicator for this input stream. - /// </summary> - /// <returns>The communicator.</returns> - Communicator communicator(); - - /// <summary> - /// Determines the behavior of the stream when extracting Slice objects. - /// A Slice object is "sliced" when a factory cannot be found for a Slice type ID. - /// </summary> - /// <param name="slice">If true (the default), slicing is enabled; if false, - /// slicing is disabled. If slicing is disabled and the stream encounters a Slice type ID - /// during decoding for which no object factory is installed, it raises NoObjectFactoryException.</param> - void sliceObjects(bool slice); - - /// <summary> - /// Extracts a boolean value from the stream. - /// </summary> - /// <returns>The extracted boolean.</returns> - bool readBool(); - - /// <summary> - /// Extracts a sequence of boolean values from the stream. - /// </summary> - /// <returns>The extracted boolean sequence.</returns> - bool[] readBoolSeq(); - - /// <summary> - /// Extracts a byte value from the stream. - /// </summary> - /// <returns>The extracted byte.</returns> - byte readByte(); - - /// <summary> - /// Extracts a sequence of byte values from the stream. - /// </summary> - /// <returns>The extracted byte sequence.</returns> - byte[] readByteSeq(); - - /// <summary> - /// Extracts a serializable .NET object from the stream. - /// </summary> - /// <returns>The deserialized .NET object.</returns> - object readSerializable(); - - /// <summary> - /// Extracts a short value from the stream. - /// </summary> - /// <returns>The extracted short value.</returns> - short readShort(); - - /// <summary> - /// Extracts a sequence of short values from the stream. - /// </summary> - /// <returns>The extracted short sequence.</returns> - short[] readShortSeq(); - - /// <summary> - /// Extracts an integer value from the stream. - /// </summary> - /// <returns>The extracted integer value.</returns> - int readInt(); - - /// <summary> - /// Extracts a sequence of integer values from the stream. - /// </summary> - /// <returns>The extracted integer sequence.</returns> - int[] readIntSeq(); - - /// <summary> - /// Extracts a long value from the stream. - /// </summary> - /// <returns>The extracted long value.</returns> - long readLong(); - - /// <summary> - /// Extracts a sequence of long values from the stream. - /// </summary> - /// <returns>The extracted long sequence.</returns> - long[] readLongSeq(); - - /// <summary> - /// Extracts a float value from the stream. - /// </summary> - /// <returns>The extracted float value.</returns> - float readFloat(); - - /// <summary> - /// Extracts a sequence of float values from the stream. - /// </summary> - /// <returns>The extracted float sequence.</returns> - float[] readFloatSeq(); - - /// <summary> - /// Extracts a double value from the stream. - /// </summary> - /// <returns>The extracted double value.</returns> - double readDouble(); - - /// <summary> - /// Extracts a sequence of double values from the stream. - /// </summary> - /// <returns>The extracted double sequence.</returns> - double[] readDoubleSeq(); - - /// <summary> - /// Extracts a string from the stream. - /// </summary> - /// <returns>The extracted double value.</returns> - string readString(); - - /// <summary> - /// Extracts a sequence of strings from the stream. - /// </summary> - /// <returns>The extracted string sequence.</returns> - string[] readStringSeq(); - - /// <summary> - /// Extracts a size from the stream. - /// </summary> - /// <returns>The extracted size.</returns> - int readSize(); - - /// <summary> - /// Extracts and check a sequence size from the stream. The check ensures not too much memory will - /// be pre-allocated for the sequence. - /// </summary> - /// <param name="minSize">The minimum size of an element of the sequence.</param> - /// <returns>The extracted size.</returns> - int readAndCheckSeqSize(int minSize); - - /// <summary> - /// Extracts a proxy from the stream. - /// </summary> - /// <returns>The extracted proxy.</returns> - ObjectPrx readProxy(); - - /// <summary> - /// Extracts the index of a Slice class from the stream. - /// </summary> - /// <param name="cb">The callback to notify the application when the extracted instance is available. - /// The Ice run time extracts Slice classes in stages. The Ice run time calls ReadObjectCallback.invoke - /// when the corresponding instance has been fully unmarshaled.</param> - void readObject(ReadObjectCallback cb); - - /// <summary> - /// Read an enumerated value. - /// </summary> - /// - /// <param name="maxValue">The maximum enumerator value in the definition.</param> - /// <returns>The enumerator.</returns> - int readEnum(int maxValue); - - /// <summary> - /// Extracts a user exception from the stream and throws it. - /// </summary> - void throwException(); - - /// <summary> - /// Extracts a user exception from the stream and throws it. - /// Extracts a user exception from the stream and throws it, using the supplied - /// factory to instantiate a UserExceptionReader. - /// </summary> - /// <param name="factory">A factory that creates UserExceptionReader instances.</param> - void throwException(UserExceptionReaderFactory factory); - - /// <summary> - /// Marks the start of an Ice object. - /// </summary> - void startObject(); - - /// <summary> - /// Marks the end of an Ice object. - /// </summary> - /// <param name="preserve">True if unknown slices should be preserved, false otherwise.</param> - /// <returns>A SlicedData object containing the preserved slices for unknown types.</returns> - SlicedData endObject(bool preserve); - - /// <summary> - /// Marks the start of a user exception. - /// </summary> - void startException(); - - /// <summary> - /// Marks the end of a user exception. - /// </summary> - /// <param name="preserve">True if unknown slices should be preserved, false otherwise.</param> - /// <returns>A SlicedData object containing the preserved slices for unknown types.</returns> - SlicedData endException(bool preserve); - - /// <summary> - /// Reads the start of an object or exception slice. - /// </summary> - /// <returns>The Slice type ID for this slice.</returns> - string startSlice(); - - /// <summary> - /// Indicates that the end of an object or exception slice has been reached. - /// </summary> - void endSlice(); - - /// <summary> - /// Skips over an object or exception slice. - /// </summary> - void skipSlice(); - - /// <summary> - /// Reads the start of an encapsulation. - /// </summary> - /// <returns>The encapsulation encoding version.</returns> - EncodingVersion startEncapsulation(); - - /// <summary> - /// Indicates that the end of an encapsulation has been reached. - /// </summary> - void endEncapsulation(); - - /// <summary> - /// Skips over an encapsulation. - /// </summary> - /// <returns>The encapsulation encoding version.</returns> - EncodingVersion skipEncapsulation(); - - /// <summary> - /// Determines the current encoding version. - /// </summary> - /// <returns>The encoding version.</returns> - EncodingVersion getEncoding(); - - /// <summary> - /// Indicates that unmarshaling is complete, except for any Slice objects. The application must - /// call this method only if the stream actually contains Slice objects. Calling readPendingObjects - /// triggers the calls to ReadObjectCallback.invoke that inform the application that unmarshaling - /// of a Slice object is complete. - /// </summary> - void readPendingObjects(); - - /// <summary> - /// Resets the read position of the stream to the beginning. - /// </summary> - void rewind(); - - /// <summary> - /// Skips ahead in the stream. - /// </summary> - /// <param name="sz">The number of bytes to skip.</param> - void skip(int sz); - - /// <summary> - /// Skips over a size value. - /// </summary> - void skipSize(); - - /// <summary> - /// Determine if an optional value is available for reading. - /// </summary> - /// <param name="tag">The tag associated with the value.</param> - /// <param name="format">The optional format for the value.</param> - /// <returns>True if the value is present, false otherwise.</returns> - bool readOptional(int tag, OptionalFormat format); - - /// <summary> - /// Determine the current position in the stream. - /// </summary> - /// <returns>The current position.</returns> - int pos(); - - /// <summary> - /// Destroys the stream and its associated resources. The application must call destroy prior - /// to releasing the last reference to a stream; failure to do so may result in resource leaks. - /// </summary> - void destroy(); - } - - /// <summary> - /// Interface for output streams used to write Slice types to a sequence - /// of bytes. - /// </summary> - public interface OutputStream - { - /// <summary> - /// Returns the communicator for this output stream. - /// </summary> - Communicator communicator(); - - /// <summary> - /// Writes a boolean to the stream. - /// </summary> - /// <param name="v">The boolean to write to the stream.</param> - void writeBool(bool v); - - /// <summary> - /// Writes a sequence of booleans to the stream. - /// </summary> - /// <param name="v">The sequence of booleans to write. - /// Passing null causes an empty sequence to be written to the stream.</param> - void writeBoolSeq(bool[] v); - - /// <summary> - /// Writes a byte to the stream. - /// </summary> - /// <param name="v">The byte to write to the stream.</param> - void writeByte(byte v); - - /// <summary> - /// Writes a sequence of bytes to the stream. - /// </summary> - /// <param name="v">The sequence of bytes to write. - /// Passing null causes an empty sequence to be written to the stream.</param> - void writeByteSeq(byte[] v); - - /// <summary> - /// Writes a serializable .NET object to the stream. - /// </summary> - /// <param name="v">The serializable object to write.</param> - void writeSerializable(object v); - - /// <summary> - /// Writes a short to the stream. - /// </summary> - /// <param name="v">The short to write to the stream.</param> - void writeShort(short v); - - /// <summary> - /// Writes a sequence of shorts to the stream. - /// </summary> - /// <param name="v">The sequence of shorts to write. - /// Passing null causes an empty sequence to be written to the stream.</param> - void writeShortSeq(short[] v); - - /// <summary> - /// Writes an integer to the stream. - /// </summary> - /// <param name="v">The integer to write to the stream.</param> - void writeInt(int v); - - /// <summary> - /// Writes a sequence of integers to the stream. - /// </summary> - /// <param name="v">The sequence of integers to write. - /// Passing null causes an empty sequence to be written to the stream.</param> - void writeIntSeq(int[] v); - - /// <summary> - /// Writes a long to the stream. - /// </summary> - /// <param name="v">The long to write to the stream.</param> - void writeLong(long v); - - /// <summary> - /// Writes a sequence of longs to the stream. - /// </summary> - /// <param name="v">The sequence of longs to write. - /// Passing null causes an empty sequence to be written to the stream.</param> - void writeLongSeq(long[] v); - - /// <summary> - /// Writes a float to the stream. - /// </summary> - /// <param name="v">The float to write to the stream.</param> - void writeFloat(float v); - - /// <summary> - /// Writes a sequence of floats to the stream. - /// </summary> - /// <param name="v">The sequence of floats to write. - /// Passing null causes an empty sequence to be written to the stream.</param> - void writeFloatSeq(float[] v); - - /// <summary> - /// Writes a double to the stream. - /// </summary> - /// <param name="v">The double to write to the stream.</param> - void writeDouble(double v); - - /// <summary> - /// Writes a sequence of doubles to the stream. - /// </summary> - /// <param name="v">The sequence of doubles to write. - /// Passing null causes an empty sequence to be written to the stream.</param> - void writeDoubleSeq(double[] v); - - /// <summary> - /// Writes a string to the stream. - /// </summary> - /// <param name="v">The string to write to the stream. - /// Passing null causes an empty string to be written to the stream.</param> - void writeString(string v); - - /// <summary> - /// Writes a sequence of strings to the stream. - /// </summary> - /// <param name="v">The sequence of strings to write. - /// Passing null causes an empty sequence to be written to the stream.</param> - void writeStringSeq(string[] v); - - /// <summary> - /// Writes a size to the stream. - /// </summary> - /// <param name="sz">The size to write.</param> - void writeSize(int sz); - - /// <summary> - /// Writes a proxy to the stream. - /// </summary> - /// <param name="v">The proxy to write.</param> - void writeProxy(ObjectPrx v); - - /// <summary> - /// Writes a Slice class to the stream. - /// </summary> - /// <param name="v">The class to write. This method writes the index of a Slice class; the state of the - /// class is written once writePendingObjects is called.</param> - void writeObject(Ice.Object v); - - /// <summary> - /// Write an enumerated value. - /// </summary> - /// <param name="v">The enumerator.</param> - /// <param name="limit">The number of enumerators in the definition.</param> - void writeEnum(int v, int limit); - - /// <summary> - /// Writes a user exception to the stream. - /// </summary> - /// <param name="ex">The user exception to write.</param> - void writeException(UserException ex); - - /// <summary> - /// Marks the start of an Ice object. - /// </summary> - /// <param name="slicedData">Preserved slices for this object, or null.</param> - void startObject(SlicedData slicedData); - - /// <summary> - /// Marks the end of an Ice object. - /// </summary> - void endObject(); - - /// <summary> - /// Marks the start of a user exception. - /// </summary> - /// <param name="slicedData">Preserved slices for this object, or null.</param> - void startException(SlicedData slicedData); - - /// <summary> - /// Marks the end of a user exception. - /// </summary> - void endException(); - - /// <summary> - /// Marks the start of a new slice for an Ice object or user exception. - /// </summary> - /// <param name="typeId">The Slice type ID corresponding to this slice.</param> - /// <param name="compactId">The Slice compact type ID corresponding to this slice.</param> - /// <param name="last">True if this is the last slice, false otherwise.</param> - void startSlice(string typeId, int compactId, bool last); - - /// <summary> - /// Marks the end of a slice for an Ice object or user exception. - /// </summary> - void endSlice(); - - /// <summary> - /// Writes the start of an encapsulation to the stream. - /// </summary> - /// <param name="encoding">The encoding version of the encapsulation.</param> - /// <param name="format">The format to use for encoding objects and user exceptions.</param> - void startEncapsulation(EncodingVersion encoding, FormatType format); - - /// <summary> - /// Writes the start of an encapsulation to the stream. - /// </summary> - void startEncapsulation(); - - /// <summary> - /// Ends the previous encapsulation. - /// </summary> - void endEncapsulation(); - - /// <summary> - /// Determines the current encoding version. - /// </summary> - /// <returns>The encoding version.</returns> - EncodingVersion getEncoding(); - - /// <summary> - /// Writes the state of Slice classes whose index was previously - /// written with writeObject to the stream. - /// </summary> - void writePendingObjects(); - - /// <summary> - /// Write the header information for an optional value. - /// </summary> - /// <param name="tag">The numeric tag associated with the value.</param> - /// <param name="format">The optional format of the value.</param> - /// <returns>True if the optional should be written, false otherwise.</returns> - bool writeOptional(int tag, OptionalFormat format); - - /// <summary> - /// Determines the current position in the stream. - /// </summary> - /// <returns>The current position.</returns> - int pos(); - - /// <summary> - /// Inserts a fixed 32-bit size value into the stream at the given position. - /// </summary> - /// <param name="sz">The 32-bit size value.</param> - /// <param name="pos">The position at which to write the value.</param> - void rewrite(int sz, int pos); - - /// <summary> - /// Returns the current position and allocates four bytes for a fixed-length (32-bit) - /// size value. - /// </summary> - /// <returns>The current position.</returns> - int startSize(); - - /// <summary> - /// Computes the amount of data written since the previous call to startSize and - /// writes that value at the saved position. - /// </summary> - /// <param name="pos">The saved position at which to write the size.</param> - void endSize(int pos); - - /// <summary> - /// Indicates that the marshaling of a request or reply is finished. - /// </summary> - /// <returns>The byte sequence containing the encoded request or reply.</returns> - byte[] finished(); - - /// <summary> - /// Resets this output stream. This method allows the stream to be reused, to avoid creating - /// unnecessary garbage. - /// </summary> - /// - /// <param name="clearBuffer">If true, the stream's internal buffer becomes eligible for - /// garbage collection; if false, the stream's internal buffer is retained, to avoid - /// creating unnecessary garbage. If retained, the internal buffer may be resized to a smaller - /// capacity. Either way, reset resets the stream's writing position to zero.</param> - void reset(bool clearBuffer); - - /// <summary> - /// Destroys the stream and its associated resources. The application must call destroy prior - /// to releasing the last reference to a stream; failure to do so may result in resource leaks. - /// </summary> - void destroy(); - } - - /// <summary> - /// Base class for extracting objects from an input stream. - /// </summary> - public abstract class ObjectReader : ObjectImpl - { - /// <summary> - /// Read the object's data members. - /// </summary> - /// <param name="inStream">The input stream to read from.</param> - public abstract void read(InputStream inStream); - - public override void write__(IceInternal.BasicStream os) - { - Debug.Assert(false); - } - - public override void read__(IceInternal.BasicStream istr) - { - InputStream stream = (InputStream)istr.closure(); - read(stream); - } - } - - /// <summary> - /// Base class for writing objects to an output stream. - /// </summary> - public abstract class ObjectWriter : ObjectImpl - { - /// <summary> - /// Writes the state of this Slice class to an output stream. - /// </summary> - /// <param name="outStream">The stream to write to.</param> - public abstract void write(OutputStream outStream); - - public override void write__(IceInternal.BasicStream os) - { - OutputStream stream = (OutputStream)os.closure(); - write(stream); - } - - public override void read__(IceInternal.BasicStream istr) - { - Debug.Assert(false); - } - } - - public abstract class UserExceptionReader : UserException - { - protected UserExceptionReader(Communicator communicator) - { - communicator_ = communicator; - } - - public abstract void read(Ice.InputStream istr); - - public override void write__(IceInternal.BasicStream ostr) - { - Debug.Assert(false); - } - - public override void read__(IceInternal.BasicStream istr) - { - InputStream stream = (InputStream)istr.closure(); - Debug.Assert(stream != null); - read(stream); - } - - public override void write__(Ice.OutputStream ostr) - { - Debug.Assert(false); - } - - public override void read__(Ice.InputStream istr) - { - read(istr); - } - - protected Communicator communicator_; - } - - public interface UserExceptionReaderFactory - { - void createAndThrow(string typeId); - } - - public abstract class UserExceptionWriter : UserException - { - public UserExceptionWriter(Communicator communicator) - { - communicator_ = communicator; - } - - public abstract void write(OutputStream os); - - public override void write__(IceInternal.BasicStream os) - { - OutputStream stream = (OutputStream)os.closure(); - if(stream == null) - { - stream = new OutputStreamI(communicator_, os); - } - write(stream); - } - - public override void read__(IceInternal.BasicStream istr) - { - Debug.Assert(false); - } - - public override void write__(Ice.OutputStream ostr) - { - write(ostr); - } - - public override void read__(Ice.InputStream istr) - { - Debug.Assert(false); - } - - protected Communicator communicator_; - } -} diff --git a/csharp/src/Ice/StreamI.cs b/csharp/src/Ice/StreamI.cs deleted file mode 100644 index b5e7650100a..00000000000 --- a/csharp/src/Ice/StreamI.cs +++ /dev/null @@ -1,570 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -namespace Ice -{ - public class InputStreamI : InputStream - { - public InputStreamI(Communicator communicator, byte[] data, bool copyData) - { - _communicator = communicator; - IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); - initialize(instance, data, instance.defaultsAndOverrides().defaultEncoding, copyData); - } - - public InputStreamI(Communicator communicator, byte[] data, EncodingVersion v, bool copyData) - { - _communicator = communicator; - initialize(IceInternal.Util.getInstance(communicator), data, v, copyData); - } - - private void initialize(IceInternal.Instance instance, byte[] data, EncodingVersion v, bool copyData) - { - if(copyData) - { - _is = new IceInternal.BasicStream(instance, v); - _is.resize(data.Length, true); - IceInternal.Buffer buf = _is.getBuffer(); - buf.b.position(0); - buf.b.put(data); - buf.b.position(0); - } - else - { - _is = new IceInternal.BasicStream(instance, v, data); - } - _is.closure(this); - } - - public Communicator communicator() - { - return _communicator; - } - - public void sliceObjects(bool slice) - { - _is.sliceObjects(slice); - } - - public bool readBool() - { - return _is.readBool(); - } - - public bool[] readBoolSeq() - { - return _is.readBoolSeq(); - } - - public byte readByte() - { - return _is.readByte(); - } - - public byte[] readByteSeq() - { - return _is.readByteSeq(); - } - - public object readSerializable() - { - return _is.readSerializable(); - } - - public short readShort() - { - return _is.readShort(); - } - - public short[] readShortSeq() - { - return _is.readShortSeq(); - } - - public int readInt() - { - return _is.readInt(); - } - - public int[] readIntSeq() - { - return _is.readIntSeq(); - } - - public long readLong() - { - return _is.readLong(); - } - - public long[] readLongSeq() - { - return _is.readLongSeq(); - } - - public float readFloat() - { - return _is.readFloat(); - } - - public float[] readFloatSeq() - { - return _is.readFloatSeq(); - } - - public double readDouble() - { - return _is.readDouble(); - } - - public double[] readDoubleSeq() - { - return _is.readDoubleSeq(); - } - - public string readString() - { - return _is.readString(); - } - - public string[] readStringSeq() - { - return _is.readStringSeq(); - } - - public int readSize() - { - return _is.readSize(); - } - - public int readAndCheckSeqSize(int minSize) - { - return _is.readAndCheckSeqSize(minSize); - } - - public ObjectPrx readProxy() - { - return _is.readProxy(); - } - - private class Patcher<T> : IceInternal.Patcher - { - public Patcher(ReadObjectCallback cb) : base("unknown") - { - _cb = cb; - } - - public override void patch(Ice.Object v) - { - _cb.invoke(v); - } - - ReadObjectCallback _cb; - } - - public void readObject(ReadObjectCallback cb) - { - _is.readObject(new Patcher<Ice.Object>(cb)); - } - - public int readEnum(int maxValue) - { - return _is.readEnum(maxValue); - } - - public void throwException() - { - _is.throwException(null); - } - - internal class UserExceptionFactoryI : IceInternal.UserExceptionFactory - { - internal UserExceptionFactoryI(UserExceptionReaderFactory factory) - { - _factory = factory; - } - - public void createAndThrow(string id) - { - _factory.createAndThrow(id); - } - - public void destroy() - { - } - - private UserExceptionReaderFactory _factory; - } - - public void throwException(UserExceptionReaderFactory factory) - { - _is.throwException(new UserExceptionFactoryI(factory)); - } - - public void startObject() - { - _is.startReadObject(); - } - - public SlicedData endObject(bool preserve) - { - return _is.endReadObject(preserve); - } - - public void startException() - { - _is.startReadException(); - } - - public SlicedData endException(bool preserve) - { - return _is.endReadException(preserve); - } - - public string startSlice() - { - return _is.startReadSlice(); - } - - public void endSlice() - { - _is.endReadSlice(); - } - - public void skipSlice() - { - _is.skipSlice(); - } - - public EncodingVersion startEncapsulation() - { - return _is.startReadEncaps(); - } - - public void endEncapsulation() - { - _is.endReadEncapsChecked(); - } - - public EncodingVersion skipEncapsulation() - { - return _is.skipEncaps(); - } - - public EncodingVersion getEncoding() - { - return _is.getReadEncoding(); - } - - public void readPendingObjects() - { - _is.readPendingObjects(); - } - - public void rewind() - { - _is.clear(); - _is.getBuffer().b.position(0); - } - - public void skip(int sz) - { - _is.skip(sz); - } - - public void skipSize() - { - _is.skipSize(); - } - - public bool readOptional(int tag, OptionalFormat format) - { - return _is.readOpt(tag, format); - } - - public int pos() - { - return _is.pos(); - } - - public void destroy() - { - if(_is != null) - { - _is = null; - } - } - - private Communicator _communicator; - private IceInternal.BasicStream _is; - } - - public class OutputStreamI : OutputStream - { - public OutputStreamI(Communicator communicator) - { - _communicator = communicator; - - IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); - _os = new IceInternal.BasicStream(instance, instance.defaultsAndOverrides().defaultEncoding); - _os.closure(this); - } - - public OutputStreamI(Communicator communicator, EncodingVersion v) - { - _communicator = communicator; - - IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); - _os = new IceInternal.BasicStream(instance, v); - _os.closure(this); - } - - public OutputStreamI(Communicator communicator, IceInternal.BasicStream os) - { - _communicator = communicator; - _os = os; - _os.closure(this); - } - - public Communicator communicator() - { - return _communicator; - } - - public void writeBool(bool v) - { - _os.writeBool(v); - } - - public void writeBoolSeq(bool[] v) - { - _os.writeBoolSeq(v); - } - - public void writeByte(byte v) - { - _os.writeByte(v); - } - - public void writeByteSeq(byte[] v) - { - _os.writeByteSeq(v); - } - - public void writeSerializable(object v) - { - _os.writeSerializable(v); - } - - public void writeShort(short v) - { - _os.writeShort(v); - } - - public void writeShortSeq(short[] v) - { - _os.writeShortSeq(v); - } - - public void writeInt(int v) - { - _os.writeInt(v); - } - - public void writeIntSeq(int[] v) - { - _os.writeIntSeq(v); - } - - public void writeLong(long v) - { - _os.writeLong(v); - } - - public void writeLongSeq(long[] v) - { - _os.writeLongSeq(v); - } - - public void writeFloat(float v) - { - _os.writeFloat(v); - } - - public void writeFloatSeq(float[] v) - { - _os.writeFloatSeq(v); - } - - public void writeDouble(double v) - { - _os.writeDouble(v); - } - - public void writeDoubleSeq(double[] v) - { - _os.writeDoubleSeq(v); - } - - public void writeString(string v) - { - _os.writeString(v); - } - - public void writeStringSeq(string[] v) - { - _os.writeStringSeq(v); - } - - public void writeSize(int sz) - { - if(sz < 0) - { - throw new MarshalException(); - } - - _os.writeSize(sz); - } - - public void writeProxy(ObjectPrx v) - { - _os.writeProxy(v); - } - - public void writeObject(Ice.Object v) - { - _os.writeObject(v); - } - - public void writeEnum(int v, int maxValue) - { - _os.writeEnum(v, maxValue); - } - - public void writeException(UserException v) - { - _os.writeUserException(v); - } - - public void startObject(SlicedData slicedData) - { - _os.startWriteObject(slicedData); - } - - public void endObject() - { - _os.endWriteObject(); - } - - public void startException(SlicedData slicedData) - { - _os.startWriteException(slicedData); - } - - public void endException() - { - _os.endWriteException(); - } - - public void startSlice(string typeId, int compactId, bool last) - { - _os.startWriteSlice(typeId, compactId, last); - } - - public void endSlice() - { - _os.endWriteSlice(); - } - - public void startEncapsulation(EncodingVersion encoding, FormatType format) - { - _os.startWriteEncaps(encoding, format); - } - - public void startEncapsulation() - { - _os.startWriteEncaps(); - } - - public void endEncapsulation() - { - _os.endWriteEncapsChecked(); - } - - public EncodingVersion getEncoding() - { - return _os.getWriteEncoding(); - } - - public void writePendingObjects() - { - _os.writePendingObjects(); - } - - public bool writeOptional(int tag, OptionalFormat format) - { - return _os.writeOpt(tag, format); - } - - public int pos() - { - return _os.pos(); - } - - public void rewrite(int sz, int pos) - { - _os.rewriteInt(sz, pos); - } - - public int startSize() - { - return _os.startSize(); - } - - public void endSize(int pos) - { - _os.endSize(pos); - } - - public byte[] finished() - { - IceInternal.Buffer buf = _os.prepareWrite(); - byte[] result = new byte[buf.b.limit()]; - buf.b.get(result); - - return result; - } - - public void reset(bool clearBuffer) - { - _os.clear(); - - IceInternal.Buffer buf = _os.getBuffer(); - if(clearBuffer) - { - buf.clear(); - } - else - { - buf.reset(); - } - buf.b.position(0); - } - - public void destroy() - { - if(_os != null) - { - _os = null; - } - } - - private Communicator _communicator; - private IceInternal.BasicStream _os; - } -} diff --git a/csharp/src/Ice/StreamSocket.cs b/csharp/src/Ice/StreamSocket.cs index 5bc168dfa79..6b0b86bd8a0 100644 --- a/csharp/src/Ice/StreamSocket.cs +++ b/csharp/src/Ice/StreamSocket.cs @@ -7,14 +7,6 @@ // // ********************************************************************** -// -// .NET and Silverlight use the new socket asynchronous APIs whereas -// the compact framework and mono still use the old Begin/End APIs. -// -#if !COMPACT && !__MonoCS__ && !UNITY -#define ICE_SOCKET_ASYNC_API -#endif - namespace IceInternal { using System; @@ -43,22 +35,20 @@ namespace IceInternal _state = StateConnected; try { - _desc = IceInternal.Network.fdToString(_fd); + _desc = Network.fdToString(_fd); } - catch(Exception ex) + catch(Exception) { Network.closeSocketNoThrow(_fd); - throw ex; + throw; } init(); } -#if !SILVERLIGHT public void setBlock(bool block) { Network.setBlock(_fd, block); } -#endif public int connect(Buffer readBuffer, Buffer writeBuffer, ref bool moreData) { @@ -69,7 +59,6 @@ namespace IceInternal } else if(_state <= StateConnectPending) { -#if ICE_SOCKET_ASYNC_API if(_writeEventArgs.SocketError != SocketError.Success) { SocketException ex = new SocketException((int)_writeEventArgs.SocketError); @@ -82,10 +71,6 @@ namespace IceInternal throw new Ice.ConnectFailedException(ex); } } -#else - Network.doFinishConnectAsync(_fd, _writeResult); - _writeResult = null; -#endif _desc = Network.fdToString(_fd, _proxy, _addr); _state = _proxy != null ? StateProxyWrite : StateConnected; } @@ -126,12 +111,12 @@ namespace IceInternal public int getSendPacketSize(int length) { - return _maxSendPacketSize > 0 ? System.Math.Min(length, _maxSendPacketSize) : length; + return _maxSendPacketSize > 0 ? Math.Min(length, _maxSendPacketSize) : length; } public int getRecvPacketSize(int length) { - return _maxRecvPacketSize > 0 ? System.Math.Min(length, _maxRecvPacketSize) : length; + return _maxRecvPacketSize > 0 ? Math.Min(length, _maxRecvPacketSize) : length; } public void setBufferSize(int rcvSize, int sndSize) @@ -186,25 +171,15 @@ namespace IceInternal public bool startRead(Buffer buf, AsyncCallback callback, object state) { -#if ICE_SOCKET_ASYNC_API Debug.Assert(_fd != null && _readEventArgs != null); -#else - Debug.Assert(_fd != null && _readResult == null); -#endif int packetSize = getRecvPacketSize(buf.b.remaining()); try { _readCallback = callback; -#if ICE_SOCKET_ASYNC_API _readEventArgs.UserToken = state; _readEventArgs.SetBuffer(buf.b.rawBytes(), buf.b.position(), packetSize); return !_fd.ReceiveAsync(_readEventArgs); -#else - _readResult = _fd.BeginReceive(buf.b.rawBytes(), buf.b.position(), packetSize, SocketFlags.None, - readCompleted, state); - return _readResult.CompletedSynchronously; -#endif } catch(SocketException ex) { @@ -220,30 +195,19 @@ namespace IceInternal { if(_fd == null) // Transceiver was closed { -#if !ICE_SOCKET_ASYNC_API - _readResult = null; -#endif return; } -#if ICE_SOCKET_ASYNC_API Debug.Assert(_fd != null && _readEventArgs != null); -#else - Debug.Assert(_fd != null && _readResult != null); -#endif try { -#if ICE_SOCKET_ASYNC_API if(_readEventArgs.SocketError != SocketError.Success) { throw new SocketException((int)_readEventArgs.SocketError); } int ret = _readEventArgs.BytesTransferred; _readEventArgs.SetBuffer(null, 0, 0); -#else - int ret = _fd.EndReceive(_readResult); - _readResult = null; -#endif + if(ret == 0) { throw new Ice.ConnectionLostException(); @@ -273,12 +237,7 @@ namespace IceInternal public bool startWrite(Buffer buf, AsyncCallback callback, object state, out bool completed) { -#if ICE_SOCKET_ASYNC_API Debug.Assert(_fd != null && _writeEventArgs != null); -#else - Debug.Assert(_fd != null && _writeResult == null); -#endif - if(_state == StateConnectPending) { completed = false; @@ -286,14 +245,9 @@ namespace IceInternal try { EndPoint addr = _proxy != null ? _proxy.getAddress() : _addr; -#if ICE_SOCKET_ASYNC_API _writeEventArgs.RemoteEndPoint = addr; _writeEventArgs.UserToken = state; return !_fd.ConnectAsync(_writeEventArgs); -#else - _writeResult = Network.doConnectAsync(_fd, addr, _sourceAddr, callback, state); - return _writeResult.CompletedSynchronously; -#endif } catch(Exception ex) { @@ -305,15 +259,9 @@ namespace IceInternal try { _writeCallback = callback; -#if ICE_SOCKET_ASYNC_API _writeEventArgs.UserToken = state; _writeEventArgs.SetBuffer(buf.b.rawBytes(), buf.b.position(), packetSize); bool completedSynchronously = !_fd.SendAsync(_writeEventArgs); -#else - _writeResult = _fd.BeginSend(buf.b.rawBytes(), buf.b.position(), packetSize, SocketFlags.None, - writeCompleted, state); - bool completedSynchronously = _writeResult.CompletedSynchronously; -#endif completed = packetSize == buf.b.remaining(); return completedSynchronously; } @@ -339,17 +287,10 @@ namespace IceInternal { buf.b.position(buf.b.limit()); // Assume all the data was sent for at-most-once semantics. } -#if !ICE_SOCKET_ASYNC_API - _writeResult = null; -#endif return; } -#if ICE_SOCKET_ASYNC_API Debug.Assert(_fd != null && _writeEventArgs != null); -#else - Debug.Assert(_fd != null && _writeResult != null); -#endif if(_state < StateConnected && _state != StateProxyWrite) { @@ -358,17 +299,12 @@ namespace IceInternal try { -#if ICE_SOCKET_ASYNC_API if(_writeEventArgs.SocketError != SocketError.Success) { throw new SocketException((int)_writeEventArgs.SocketError); } int ret = _writeEventArgs.BytesTransferred; _writeEventArgs.SetBuffer(null, 0, 0); -#else - int ret = _fd.EndSend(_writeResult); - _writeResult = null; -#endif if(ret == 0) { throw new Ice.ConnectionLostException(); @@ -412,11 +348,9 @@ namespace IceInternal public void destroy() { -#if ICE_SOCKET_ASYNC_API Debug.Assert(_readEventArgs != null && _writeEventArgs != null); _readEventArgs.Dispose(); _writeEventArgs.Dispose(); -#endif } public override string ToString() @@ -427,16 +361,6 @@ namespace IceInternal private int read(ByteBuffer buf) { Debug.Assert(_fd != null); - -#if COMPACT || SILVERLIGHT - // - // Silverlight and the Compact .NET Framework don't - // support the use of synchronous socket operations on a - // non-blocking socket. Returning 0 here forces the caller - // to schedule an asynchronous operation. - // - return 0; -#else int read = 0; while(buf.hasRemaining()) { @@ -469,35 +393,21 @@ namespace IceInternal } } return read; -#endif } private int write(ByteBuffer buf) { Debug.Assert(_fd != null); -#if COMPACT || SILVERLIGHT + int packetSize = buf.remaining(); // - // Silverlight and the Compact .NET Frameworks don't - // support the use of synchronous socket operations on a - // non-blocking socket. Returning 0 here forces the caller - // to schedule an asynchronous operation. + // On Windows, limiting the buffer size is important to prevent + // poor throughput performances when transfering large amount of + // data. See Microsoft KB article KB823764. // - return 0; -#else - - int packetSize = buf.remaining(); - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) + if(_maxSendPacketSize > 0 && packetSize > _maxSendPacketSize / 2) { - // - // On Windows, limiting the buffer size is important to prevent - // poor throughput performances when transfering large amount of - // data. See Microsoft KB article KB823764. - // - if(_maxSendPacketSize > 0 && packetSize > _maxSendPacketSize / 2) - { - packetSize = _maxSendPacketSize / 2; - } + packetSize = _maxSendPacketSize / 2; } int sent = 0; @@ -529,10 +439,7 @@ namespace IceInternal } } return sent; -#endif } - -#if ICE_SOCKET_ASYNC_API private void ioCompleted(object sender, SocketAsyncEventArgs e) { switch (e.LastOperation) @@ -548,50 +455,17 @@ namespace IceInternal throw new ArgumentException("The last operation completed on the socket was not a receive or send"); } } -#else - private void readCompleted(IAsyncResult result) - { - if(!result.CompletedSynchronously) - { - _readCallback(result.AsyncState); - } - } - - private void writeCompleted(IAsyncResult result) - { - if(!result.CompletedSynchronously) - { - _writeCallback(result.AsyncState); - } - } -#endif private void init() { -#if !SILVERLIGHT Network.setBlock(_fd, false); -#endif Network.setTcpBufSize(_fd, _instance); -#if ICE_SOCKET_ASYNC_API _readEventArgs = new SocketAsyncEventArgs(); _readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(ioCompleted); _writeEventArgs = new SocketAsyncEventArgs(); _writeEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(ioCompleted); -# if SILVERLIGHT - String policy = _instance.properties().getProperty("Ice.ClientAccessPolicyProtocol"); - if(policy.Equals("Http")) - { - _readEventArgs.SocketClientAccessPolicyProtocol = SocketClientAccessPolicyProtocol.Http; - _writeEventArgs.SocketClientAccessPolicyProtocol = SocketClientAccessPolicyProtocol.Http; - } - else if(!String.IsNullOrEmpty(policy)) - { - _instance.logger().warning("Ignoring invalid Ice.ClientAccessPolicyProtocol value `" + policy + "'"); - } -# endif -#endif // // For timeouts to work properly, we need to receive/send @@ -600,8 +474,8 @@ namespace IceInternal // connection timeout could easily be triggered when // receiging/sending large messages. // - _maxSendPacketSize = System.Math.Max(512, Network.getSendBufferSize(_fd)); - _maxRecvPacketSize = System.Math.Max(512, Network.getRecvBufferSize(_fd)); + _maxSendPacketSize = Math.Max(512, Network.getSendBufferSize(_fd)); + _maxRecvPacketSize = Math.Max(512, Network.getRecvBufferSize(_fd)); } private int toState(int operation) @@ -618,7 +492,7 @@ namespace IceInternal } private readonly ProtocolInstance _instance; - private readonly IceInternal.NetworkProxy _proxy; + private readonly NetworkProxy _proxy; private readonly EndPoint _addr; private readonly EndPoint _sourceAddr; @@ -628,13 +502,8 @@ namespace IceInternal private int _state; private string _desc; -#if ICE_SOCKET_ASYNC_API private SocketAsyncEventArgs _writeEventArgs; private SocketAsyncEventArgs _readEventArgs; -#else - private IAsyncResult _writeResult; - private IAsyncResult _readResult; -#endif AsyncCallback _writeCallback; AsyncCallback _readCallback; diff --git a/csharp/src/Ice/StreamWrapper.cs b/csharp/src/Ice/StreamWrapper.cs index 906313aab8f..21879adecb4 100644 --- a/csharp/src/Ice/StreamWrapper.cs +++ b/csharp/src/Ice/StreamWrapper.cs @@ -10,127 +10,90 @@ namespace IceInternal { - - using System; using System.Diagnostics; using System.IO; - using System.Text; // - // Class to provide a System.IO.Stream interface on top of a BasicStream. + // Classes to provide a System.IO.Stream interface on top of an Ice stream. // We use this to serialize arbitrary .NET serializable classes into // a Slice byte sequence. // - // For input streams, this class is a wrapper around the BasicStream + // For input streams, this class is a wrapper around the InputStream // class that passes all methods through. // - // For output streams, we use a different stragegy: + // For output streams, we use a different strategy: // Slice sequences are encoded on the wire as a count of elements, followed // by the sequence contents. For arbitrary .NET classes, we do not know how // big the sequence that is eventually written will be. To avoid excessive - // data copying, this class mantains a private bytes_ array of 254 bytes and, + // data copying, this class maintains a private _bytes array of 254 bytes and, // initially, writes data into that array. If more than 254 bytes end up being // written, we write a dummy sequence size of 255 (which occupies five bytes - // on the wire) into the BasicStream and, once this class is disposed, patch - // that size to match the actual size. Otherwise, if the bytes_ buffer contains + // on the wire) into the stream and, once this class is disposed, patch + // that size to match the actual size. Otherwise, if the _bytes buffer contains // fewer than 255 bytes when this class is disposed, we write the sequence size - // as a single byte, followed by the contents of the bytes_ buffer. + // as a single byte, followed by the contents of the _bytes buffer. // - enum StreamType { Read, Write }; - - public class StreamWrapper : System.IO.Stream, System.IDisposable + public class OutputStreamWrapper : Stream, System.IDisposable { - // - // Writeable stream constructor - // - public StreamWrapper(BasicStream s) - { - type_ = StreamType.Write; - s_ = s; - spos_ = s.pos(); - bytes_ = new byte[254]; - pos_ = 0; - length_ = 0; - } - - // - // Readable stream constructor - // - public StreamWrapper(int size, BasicStream s) + public OutputStreamWrapper(Ice.OutputStream s) { - type_ = StreamType.Read; - s_ = s; - spos_ = 0; - bytes_ = null; - pos_ = 0; - length_ = size; + _s = s; + _spos = s.pos(); + _bytes = new byte[254]; + _pos = 0; + _length = 0; } public override int Read(byte[] buffer, int offset, int count) { - Debug.Assert(buffer != null && offset >= 0 && count >= 0 && offset + count <= buffer.Length); - try - { - s_.getBuffer().b.get(buffer, offset, count); - } - catch(System.Exception ex) - { - throw new IOException("could not read from stream", ex); - } - return count; + Debug.Assert(false); + return 0; } public override int ReadByte() { - try - { - return s_.getBuffer().b.get(); - } - catch(System.Exception ex) - { - throw new IOException("could not read from stream", ex); - } + Debug.Assert(false); + return 0; } public override void Write(byte[] array, int offset, int count) { - Debug.Assert(type_ == StreamType.Write); Debug.Assert(array != null && offset >= 0 && count >= 0 && offset + count <= array.Length); try { - if(bytes_ != null) + if(_bytes != null) { // - // If we can fit the data into the first 254 bytes, write it to bytes_. + // If we can fit the data into the first 254 bytes, write it to _bytes. // - if(count <= bytes_.Length - pos_) + if(count <= _bytes.Length - _pos) { - System.Buffer.BlockCopy(array, offset, bytes_, pos_, count); - pos_ += count; + System.Buffer.BlockCopy(array, offset, _bytes, _pos, count); + _pos += count; return; } - s_.writeSize(255); // Dummy size, until we know how big the stream + _s.writeSize(255); // Dummy size, until we know how big the stream // really is and can patch the size. - if(pos_ > 0) + if(_pos > 0) { // - // Write the current contents of bytes_. + // Write the current contents of _bytes. // - s_.expand(pos_); - s_.getBuffer().b.put(bytes_, 0, pos_); + _s.expand(_pos); + _s.getBuffer().b.put(_bytes, 0, _pos); } - bytes_ = null; + _bytes = null; } // // Write data passed by caller. // - s_.expand(count); - s_.getBuffer().b.put(array, offset, count); - pos_ += count; + _s.expand(count); + _s.getBuffer().b.put(array, offset, count); + _pos += count; } catch(System.Exception ex) { @@ -140,40 +103,39 @@ namespace IceInternal public override void WriteByte(byte value) { - Debug.Assert(type_ == StreamType.Write); try { - if(bytes_ != null) + if(_bytes != null) { // - // If we can fit the data into the first 254 bytes, write it to bytes_. + // If we can fit the data into the first 254 bytes, write it to _bytes. // - if(pos_ < bytes_.Length) + if(_pos < _bytes.Length) { - bytes_[pos_++] = value; + _bytes[_pos++] = value; return; } - s_.writeSize(255); // Dummy size, until we know how big the stream + _s.writeSize(255); // Dummy size, until we know how big the stream // really is and can patch the size. - if(pos_ > 0) + if(_pos > 0) { // - // Write the current contents of bytes_. + // Write the current contents of _bytes. // - s_.expand(pos_); - s_.getBuffer().b.put(bytes_, 0, pos_); + _s.expand(_pos); + _s.getBuffer().b.put(_bytes, 0, _pos); } - bytes_ = null; + _bytes = null; } // // Write data passed by caller. // - s_.expand(1); - s_.getBuffer().b.put(value); - pos_ += 1; + _s.expand(1); + _s.getBuffer().b.put(value); + _pos += 1; } catch(System.Exception ex) { @@ -185,7 +147,7 @@ namespace IceInternal { get { - return true; + return false; } } @@ -193,7 +155,7 @@ namespace IceInternal { get { - return type_ == StreamType.Write; + return true; } } @@ -201,18 +163,7 @@ namespace IceInternal { get { - if(AssemblyUtil.runtime_ == AssemblyUtil.Runtime.Mono) - { - // - // The Mono deserialization implementation has a bug that causes a call to Seek() such - // that the reading position is set to -1. - // - return false; - } - else - { - return type_ == StreamType.Read; - } + return false; } } @@ -220,20 +171,20 @@ namespace IceInternal { try { - if(bytes_ != null) + if(_bytes != null) { - Debug.Assert(pos_ <= bytes_.Length); - s_.pos(spos_); - s_.writeSize(pos_); - s_.expand(pos_); - s_.getBuffer().b.put(bytes_, 0, pos_); + Debug.Assert(_pos <= _bytes.Length); + _s.pos(_spos); + _s.writeSize(_pos); + _s.expand(_pos); + _s.getBuffer().b.put(_bytes, 0, _pos); } else { - int currentPos = s_.pos(); - s_.pos(spos_); - s_.writeSize(pos_); // Patch previously-written dummy value. - s_.pos(currentPos); + int currentPos = _s.pos(); + _s.pos(_spos); + _s.writeSize(_pos); // Patch previously-written dummy value. + _s.pos(currentPos); } } catch(System.Exception ex) @@ -246,7 +197,7 @@ namespace IceInternal { get { - return length_; + return _length; } } @@ -254,7 +205,7 @@ namespace IceInternal { get { - return pos_; + return _pos; } set @@ -265,24 +216,135 @@ namespace IceInternal public override long Seek(long offset, SeekOrigin origin) { - Debug.Assert(type_ != StreamType.Write); + Debug.Assert(false); + return 0; + } + public override void SetLength(long value) + { + Debug.Assert(value >= 0); + _length = value; + } + + private Ice.OutputStream _s; + private int _spos; + private byte[] _bytes; + private int _pos; + private long _length; + } + + public class InputStreamWrapper : Stream, System.IDisposable + { + public InputStreamWrapper(int size, Ice.InputStream s) + { + _s = s; + _pos = 0; + _length = size; + } + + public override int Read(byte[] buffer, int offset, int count) + { + Debug.Assert(buffer != null && offset >= 0 && count >= 0 && offset + count <= buffer.Length); + try + { + _s.getBuffer().b.get(buffer, offset, count); + } + catch(System.Exception ex) + { + throw new IOException("could not read from stream", ex); + } + return count; + } + + public override int ReadByte() + { + try + { + return _s.getBuffer().b.get(); + } + catch(System.Exception ex) + { + throw new IOException("could not read from stream", ex); + } + } + + public override void Write(byte[] array, int offset, int count) + { + Debug.Assert(false); + } + + public override void WriteByte(byte value) + { + Debug.Assert(false); + } + + public override bool CanRead + { + get + { + return true; + } + } + + public override bool CanWrite + { + get + { + return false; + } + } + + public override bool CanSeek + { + get + { + return true; + } + } + + public override void Flush() + { + } + + public override long Length + { + get + { + return _length; + } + } + + public override long Position + { + get + { + return _pos; + } + + set + { + Seek(value, SeekOrigin.Begin); + } + } + + public override long Seek(long offset, SeekOrigin origin) + { // Deliberately no size check here--positioning beyond the limit of the stream is legal. switch(origin) { case SeekOrigin.Begin: { - pos_ = (int)offset; + _pos = (int)offset; break; } case SeekOrigin.Current: { - pos_ += (int)offset; + _pos += (int)offset; break; } case SeekOrigin.End: { - pos_ = (int)length_ + (int)offset; + _pos = (int)_length + (int)offset; break; } default: @@ -291,21 +353,17 @@ namespace IceInternal break; } } - s_.pos(pos_); - return pos_; + _s.pos(_pos); + return _pos; } public override void SetLength(long value) { - Debug.Assert(type_ == StreamType.Write && value >= 0); - length_ = value; + Debug.Assert(false); } - private StreamType type_; - private BasicStream s_; - private int spos_; - private byte[] bytes_; - private int pos_; - private long length_; + private Ice.InputStream _s; + private int _pos; + private long _length; } } diff --git a/csharp/src/Ice/StringUtil.cs b/csharp/src/Ice/StringUtil.cs index 76dbbcda543..8fc7555dd0c 100644 --- a/csharp/src/Ice/StringUtil.cs +++ b/csharp/src/Ice/StringUtil.cs @@ -25,7 +25,7 @@ namespace IceUtilInternal { return findFirstOf(str, match, 0); } - + // // Return the index of the first character in str to // appear in match, starting from start. Returns -1 if none is @@ -42,10 +42,10 @@ namespace IceUtilInternal return i; } } - + return -1; } - + // // Return the index of the first character in str which does // not appear in match, starting from 0. Returns -1 if none is @@ -55,7 +55,7 @@ namespace IceUtilInternal { return findFirstNotOf(str, match, 0); } - + // // Return the index of the first character in str which does // not appear in match, starting from start. Returns -1 if none is @@ -67,119 +67,159 @@ namespace IceUtilInternal for(int i = start; i < len; i++) { char ch = str[i]; - if(match.IndexOf((char) ch) == -1) + if(match.IndexOf(ch) == -1) { return i; } } - + return -1; } - - // - // Write the byte b as an escape sequence if it isn't a printable ASCII - // character and append the escape sequence to sb. Additional characters - // that should be escaped can be passed in special. If b is any of these - // characters, b is preceded by a backslash in sb. - // - private static void encodeChar(byte b, StringBuilder sb, string special) + + private static void + encodeChar(char c, StringBuilder sb, string special, Ice.ToStringMode toStringMode) { - switch((char)b) + switch(c) { - case '\\': + case '\\': { sb.Append("\\\\"); break; } - - case '\'': + case '\'': { sb.Append("\\'"); break; } - - case '"': + case '"': { sb.Append("\\\""); break; } - - case '\b': + case '\a': + { + if(toStringMode == Ice.ToStringMode.Compat) + { + // Octal escape for compatibility with 3.6 and earlier + sb.Append("\\007"); + } + else + { + sb.Append("\\a"); + } + break; + } + case '\b': { sb.Append("\\b"); break; } - - case '\f': + case '\f': { sb.Append("\\f"); break; } - - case '\n': + case '\n': { sb.Append("\\n"); break; } - - case '\r': + case '\r': { sb.Append("\\r"); break; } - - case '\t': + case '\t': { sb.Append("\\t"); break; } - - default: + case '\v': { - if(!(b >= 32 && b <= 126)) + if(toStringMode == Ice.ToStringMode.Compat) { - sb.Append('\\'); - string octal = System.Convert.ToString(b, 8); - // - // Add leading zeroes so that we avoid problems during - // decoding. For example, consider the encoded string - // \0013 (i.e., a character with value 1 followed by - // the character '3'). If the leading zeroes were omitted, - // the result would be incorrectly interpreted by the - // decoder as a single character with value 11. - // - for(int j = octal.Length; j < 3; j++) - { - sb.Append('0'); - } - sb.Append(octal); + // Octal escape for compatibility with 3.6 and earlier + sb.Append("\\013"); } - else if(special != null && special.IndexOf((char)b) != -1) + else + { + sb.Append("\\v"); + } + break; + } + default: + { + if(special != null && special.IndexOf(c) != -1) { sb.Append('\\'); - sb.Append((char)b); + sb.Append(c); } else { - sb.Append((char)b); + int i = (int)c; + if(i < 32 || i > 126) + { + if(toStringMode == Ice.ToStringMode.Compat) + { + // + // When ToStringMode=Compat, c is a UTF-8 byte + // + Debug.Assert(i < 256); + + sb.Append('\\'); + string octal = System.Convert.ToString(i, 8); + // + // Add leading zeroes so that we avoid problems during + // decoding. For example, consider the encoded string + // \0013 (i.e., a character with value 1 followed by + // the character '3'). If the leading zeroes were omitted, + // the result would be incorrectly interpreted by the + // decoder as a single character with value 11. + // + for(int j = octal.Length; j < 3; j++) + { + sb.Append('0'); + } + sb.Append(octal); + } + else if(i < 32 || i == 127 || toStringMode == Ice.ToStringMode.ASCII) + { + // append \\unnnn + sb.Append("\\u"); + string hex = System.Convert.ToString(i, 16); + for(int j = hex.Length; j < 4; j++) + { + sb.Append('0'); + } + sb.Append(hex); + } + else + { + // keep as is + sb.Append(c); + } + } + else + { + // printable ASCII character + sb.Append(c); + } } - } break; + } } } - + // - // Add escape sequences (such as "\n", or "\007") to make a string - // readable in ASCII. Any characters that appear in special are - // prefixed with a backslash in the returned string. + // Add escape sequences (such as "\n", or "\007") to the input string // - public static string escapeString(string s, string special) + public static string escapeString(string s, string special, Ice.ToStringMode toStringMode) { if(special != null) { for(int i = 0; i < special.Length; ++i) { - if((int)special[i] < 32 || (int)special[i] > 126) + if(special[i] < 32 || special[i] > 126) { throw new System.ArgumentException("special characters must be in ASCII range 32-126", "special"); @@ -187,22 +227,64 @@ namespace IceUtilInternal } } - UTF8Encoding utf8 = new UTF8Encoding(); - byte[] bytes = utf8.GetBytes(s); + if(toStringMode == Ice.ToStringMode.Compat) + { + // Encode UTF-8 bytes + + UTF8Encoding utf8 = new UTF8Encoding(); + byte[] bytes = utf8.GetBytes(s); - StringBuilder result = new StringBuilder(bytes.Length); - for(int i = 0; i < bytes.Length; i++) + StringBuilder result = new StringBuilder(bytes.Length); + for(int i = 0; i < bytes.Length; i++) + { + encodeChar((char)bytes[i], result, special, toStringMode); + } + + return result.ToString(); + } + else { - encodeChar(bytes[i], result, special); + StringBuilder result = new StringBuilder(s.Length); + + for(int i = 0; i < s.Length; i++) + { + char c = s[i]; + if(toStringMode == Ice.ToStringMode.Unicode || !char.IsSurrogate(c)) + { + encodeChar(c, result, special, toStringMode); + } + else + { + Debug.Assert(toStringMode == Ice.ToStringMode.ASCII && char.IsSurrogate(c)); + if(i + 1 == s.Length) + { + throw new System.ArgumentException("High surrogate without low surrogate"); + } + else + { + i++; + int codePoint = char.ConvertToUtf32(c, s[i]); + // append \Unnnnnnnn + result.Append("\\U"); + string hex = System.Convert.ToString(codePoint, 16); + for(int j = hex.Length; j < 8; j++) + { + result.Append('0'); + } + result.Append(hex); + } + } + } + + return result.ToString(); } - - return result.ToString(); } - - private static char checkChar(string s, int pos) + + private static char + checkChar(string s, int pos) { char c = s[pos]; - if(!(c >= 32 && c <= 126)) + if(c < 32 || c == 127) { string msg; if(pos > 0) @@ -219,69 +301,134 @@ namespace IceUtilInternal return c; } + // - // Decode the character or escape sequence starting at start and return it. - // end marks the one-past-the-end position of the substring to be scanned. - // nextStart is set to the index of the first character following the decoded - // character or escape sequence. + // Decode the character or escape sequence starting at start and appends it to result; + // returns the index of the first character following the decoded character + // or escape sequence. // - private static char decodeChar(string s, int start, int end, out int nextStart) + private static int + decodeChar(string s, int start, int end, string special, StringBuilder result, UTF8Encoding utf8Encoding) { Debug.Assert(start >= 0); Debug.Assert(start < end); Debug.Assert(end <= s.Length); - char c; - if(s[start] != '\\') { - c = checkChar(s, start++); + result.Append(checkChar(s, start++)); + } + else if(start + 1 == end) + { + ++start; + result.Append('\\'); // trailing backslash } else { - if(start + 1 == end) - { - throw new System.ArgumentException("trailing backslash"); - } - switch(s[++start]) + char c = s[++start]; + + switch(c) { - case '\\': - case '\'': - case '"': + case '\\': + case '\'': + case '"': + case '?': { - c = s[start++]; + ++start; + result.Append(c); break; } - case 'b': + case 'a': { ++start; - c = '\b'; + result.Append('\a'); break; } - case 'f': + case 'b': { ++start; - c = '\f'; + result.Append('\b'); break; } - case 'n': + case 'f': { ++start; - c = '\n'; + result.Append('\f'); break; } - case 'r': + case 'n': { ++start; - c = '\r'; + result.Append('\n'); break; } - case 't': + case 'r': { ++start; - c = '\t'; + result.Append('\r'); break; } + case 't': + { + ++start; + result.Append('\t'); + break; + } + case 'v': + { + ++start; + result.Append('\v'); + break; + } + case 'u': + case 'U': + { + int codePoint = 0; + bool inBMP = (c == 'u'); + int size = inBMP ? 4 : 8; + ++start; + while(size > 0 && start < end) + { + c = s[start++]; + int charVal = 0; + if(c >= '0' && c <= '9') + { + charVal = c - '0'; + } + else if(c >= 'a' && c <= 'f') + { + charVal = 10 + (c - 'a'); + } + else if(c >= 'A' && c <= 'F') + { + charVal = 10 + (c - 'A'); + } + else + { + break; // while + } + codePoint = codePoint * 16 + charVal; + --size; + } + if(size > 0) + { + throw new System.ArgumentException("Invalid universal character name: too few hex digits"); + } + if(codePoint >= 0xD800 && codePoint <= 0xDFFF) + { + throw new System.ArgumentException("A universal character name cannot designate a surrogate"); + } + if(inBMP || codePoint <= 0xFFFF) + { + result.Append((char)codePoint); + } + else + { + result.Append(char.ConvertFromUtf32(codePoint)); + } + break; + } + case '0': case '1': case '2': @@ -290,70 +437,141 @@ namespace IceUtilInternal case '5': case '6': case '7': + case 'x': { - int val = 0; - for(int j = 0; j < 3 && start < end; ++j) + // UTF-8 byte sequence encoded with octal escapes + + byte[] arr = new byte[end - start]; + int i = 0; + bool more = true; + while(more) { - int charVal = s[start++] - '0'; - if(charVal < 0 || charVal > 7) + int val = 0; + if(c == 'x') { - --start; - break; + int size = 2; + ++start; + while(size > 0 && start < end) + { + c = s[start++]; + int charVal = 0; + if(c >= '0' && c <= '9') + { + charVal = c - '0'; + } + else if(c >= 'a' && c <= 'f') + { + charVal = 10 + (c - 'a'); + } + else if(c >= 'A' && c <= 'F') + { + charVal = 10 + (c - 'A'); + } + else + { + --start; // move back + break; // while + } + val = val * 16 + charVal; + --size; + } + if(size == 2) + { + throw new System.ArgumentException("Invalid \\x escape sequence: no hex digit"); + } + } + else + { + for(int j = 0; j < 3 && start < end; ++j) + { + int charVal = s[start++] - '0'; + if(charVal < 0 || charVal > 7) + { + --start; // move back + Debug.Assert(j != 0); // must be at least one digit + break; // for + } + val = val * 8 + charVal; + } + if(val > 255) + { + string msg = "octal value \\" + System.Convert.ToString(val, 8) + " (" + val + ") is out of range"; + throw new System.ArgumentException(msg); + } + } + + arr[i++] = (byte)val; + + more = false; + + if((start + 1 < end) && s[start] == '\\') + { + c = s[start + 1]; + if(c == 'x' || (c >= '0' && c <= '9')) + { + start++; + more = true; + } } - val = val * 8 + charVal; - } - if(val > 255) - { - string msg = "octal value \\" + System.Convert.ToString(val, 8) + " (" + val + - ") is out of range"; - throw new System.ArgumentException(msg, "s"); } - c = System.Convert.ToChar(val); + + result.Append(utf8Encoding.GetString(arr, 0, i)); // May raise ArgumentException. break; } default: { - c = checkChar(s, start++); + if(string.IsNullOrEmpty(special) || special.IndexOf(c) == -1) + { + result.Append('\\'); // not in special, so we keep the backslash + } + result.Append(checkChar(s, start++)); break; } } } - nextStart = start; - return c; - } - - // - // Remove escape sequences from s and append the result to sb. - // Return true if successful, false otherwise. - // - private static void decodeString(string s, int start, int end, StringBuilder sb) - { - while(start < end) - { - sb.Append(decodeChar(s, start, end, out start)); - } + return start; } // // Remove escape sequences added by escapeString. Throws System.ArgumentException // for an invalid input string. // - public static string unescapeString(string s, int start, int end) + public static string unescapeString(string s, int start, int end, string special) { Debug.Assert(start >= 0 && start <= end && end <= s.Length); - StringBuilder sb = new StringBuilder(); - decodeString(s, start, end, sb); - string decodedString = sb.ToString(); - - byte[] arr = new byte[decodedString.Length]; - for(int i = 0; i < arr.Length; ++i) + if(special != null) { - arr[i] = (byte)decodedString[i]; + for(int i = 0; i < special.Length; ++i) + { + if(special[i] < 32 || special[i] > 126) + { + throw new System.ArgumentException("special characters must be in ASCII range 32-126", + "special"); + } + } } - UTF8Encoding utf8 = new UTF8Encoding(false, true); - return utf8.GetString(arr, 0, arr.Length); // May raise ArgumentException. + // Optimization for strings without escapes + if(start == end || s.IndexOf('\\', start, end - start) == -1) + { + int p = start; + while(p < end) + { + checkChar(s, p++); + } + return s.Substring(start, end - start); + } + else + { + StringBuilder sb = new StringBuilder(end - start); + UTF8Encoding utf8Encoding = new UTF8Encoding(false, true); + while(start < end) + { + start = decodeChar(s, start, end, special, sb, utf8Encoding); + } + return sb.ToString(); + } } // @@ -402,7 +620,7 @@ namespace IceUtilInternal continue; } } - + if(pos < str.Length) { arr[n++] = str[pos++]; @@ -425,7 +643,7 @@ namespace IceUtilInternal { return checkQuote(s, 0); } - + // // If a single or double quotation mark is found at the start position, // then the position of the matching closing quote is returned. If no @@ -502,14 +720,13 @@ namespace IceUtilInternal return true; } - private class OrdinalStringComparerImpl : System.Collections.Generic.IComparer<string> + private class OrdinalStringComparerImpl : IComparer<string> { public int Compare(string l, string r) { return string.CompareOrdinal(l, r); - } + } } - public static System.Collections.Generic.IComparer<string> OrdinalStringComparer = - new OrdinalStringComparerImpl(); + public static IComparer<string> OrdinalStringComparer = new OrdinalStringComparerImpl(); } } diff --git a/csharp/src/Ice/SysLoggerI.cs b/csharp/src/Ice/SysLoggerI.cs deleted file mode 100644 index 1b6f3285192..00000000000 --- a/csharp/src/Ice/SysLoggerI.cs +++ /dev/null @@ -1,234 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -#if !SILVERLIGHT -using System.Net.Sockets; - -namespace Ice -{ - - public sealed class SysLoggerI : Logger - { - public SysLoggerI(string prefix, string facilityString) - { - int facility; - if(facilityString.Equals("LOG_KERN")) - { - facility = LOG_KERN; - } - else if(facilityString.Equals("LOG_USER")) - { - facility = LOG_USER; - } - else if(facilityString.Equals("LOG_MAIL")) - { - facility = LOG_MAIL; - } - else if(facilityString.Equals("LOG_DAEMON")) - { - facility = LOG_DAEMON; - } - else if(facilityString.Equals("LOG_AUTH")) - { - facility = LOG_AUTH; - } - else if(facilityString.Equals("LOG_SYSLOG")) - { - facility = LOG_SYSLOG; - } - else if(facilityString.Equals("LOG_LPR")) - { - facility = LOG_LPR; - } - else if(facilityString.Equals("LOG_NEWS")) - { - facility = LOG_NEWS; - } - else if(facilityString.Equals("LOG_UUCP")) - { - facility = LOG_UUCP; - } - else if(facilityString.Equals("LOG_CRON")) - { - facility = LOG_CRON; - } - else if(facilityString.Equals("LOG_AUTHPRIV")) - { - facility = LOG_AUTHPRIV; - } - else if(facilityString.Equals("LOG_FTP")) - { - facility = LOG_FTP; - } - else if(facilityString.Equals("LOG_LOCAL0")) - { - facility = LOG_LOCAL0; - } - else if(facilityString.Equals("LOG_LOCAL1")) - { - facility = LOG_LOCAL1; - } - else if(facilityString.Equals("LOG_LOCAL2")) - { - facility = LOG_LOCAL2; - } - else if(facilityString.Equals("LOG_LOCAL3")) - { - facility = LOG_LOCAL3; - } - else if(facilityString.Equals("LOG_LOCAL4")) - { - facility = LOG_LOCAL4; - } - else if(facilityString.Equals("LOG_LOCAL5")) - { - facility = LOG_LOCAL5; - } - else if(facilityString.Equals("LOG_LOCAL6")) - { - facility = LOG_LOCAL6; - } - else if(facilityString.Equals("LOG_LOCAL7")) - { - facility = LOG_LOCAL7; - } - else - { - throw new Ice.InitializationException("Invalid value for Ice.SyslogFacility: " + facilityString); - } - initialize(prefix, facility); - } - - private SysLoggerI(string prefix, int facility) - { - initialize(prefix, facility); - } - - private void initialize(string prefix, int facility) - { - _prefix = prefix; - _facility = facility; - - // - // Open a datagram socket to communicate with the localhost - // syslog daemon. - // - try - { - _host = ((System.Net.IPEndPoint)IceInternal.Network.getAddressForServer( - System.Net.Dns.GetHostName(), _port, IceInternal.Network.EnableBoth, false)).Address; - _socket = new UdpClient(); - _socket.Connect(_host, _port); - } - catch(System.Exception ex) - { - throw new Ice.DNSException(ex); - } - } - - public void print(string message) - { - log(LOG_INFO, message); - } - - public void trace(string category, string message) - { - log(LOG_INFO, category + ": " + message); - } - - public void warning(string message) - { - log(LOG_WARNING, message); - } - - public void error(string message) - { - log(LOG_ERR, message); - } - - public string getPrefix() - { - return _prefix; - } - - public Logger cloneWithPrefix(string prefix) - { - return new SysLoggerI(prefix, _facility); - } - - private void log(int severity, string message) - { - try - { - // - // Create a syslog message as defined by the RFC 3164: - // <PRI>HEADER MSG. PRI is the priority and is calculated - // from the facility and the severity. We don't specify - // the HEADER. MSG contains the identifier followed by a - // colon character and the message. - // - - int priority = (_facility << 3) | severity; - - string msg = '<' + priority + '>' + _prefix + ": " + message; - - byte[] buf = new byte[msg.Length]; - for(int i = 0; i < msg.Length; i++) - { - buf[i] = (byte)msg[i]; - } - _socket.Send(buf, buf.Length); - } - catch(System.IO.IOException ex) - { - Ice.SocketException se = new Ice.SocketException(ex); - throw se; - } - } - - private string _prefix; - private int _facility; - private UdpClient _socket; - private System.Net.IPAddress _host; - private static int _port = 514; - - // - // Syslog facilities (as defined in syslog.h) - // - private const int LOG_KERN = 0; - private const int LOG_USER = 1; - private const int LOG_MAIL = 2; - private const int LOG_DAEMON = 3; - private const int LOG_AUTH = 4; - private const int LOG_SYSLOG = 5; - private const int LOG_LPR = 6; - private const int LOG_NEWS = 7; - private const int LOG_UUCP = 8; - private const int LOG_CRON = 9; - private const int LOG_AUTHPRIV = 10; - private const int LOG_FTP = 11; - private const int LOG_LOCAL0 = 16; - private const int LOG_LOCAL1 = 17; - private const int LOG_LOCAL2 = 18; - private const int LOG_LOCAL3 = 19; - private const int LOG_LOCAL4 = 20; - private const int LOG_LOCAL5 = 21; - private const int LOG_LOCAL6 = 22; - private const int LOG_LOCAL7 = 23; - - // - // Syslog priorities (as defined in syslog.h) - // - private const int LOG_ERR = 3; - private const int LOG_WARNING = 4; - private const int LOG_INFO = 6; - } - -} -#endif diff --git a/csharp/src/Ice/TcpAcceptor.cs b/csharp/src/Ice/TcpAcceptor.cs index 9e36871107f..69e4166e5aa 100644 --- a/csharp/src/Ice/TcpAcceptor.cs +++ b/csharp/src/Ice/TcpAcceptor.cs @@ -7,8 +7,6 @@ // // ********************************************************************** -#if !SILVERLIGHT - namespace IceInternal { using System; @@ -22,7 +20,11 @@ namespace IceInternal { public virtual void close() { - Debug.Assert(_acceptFd == null); + if(_acceptFd != null) + { + Network.closeSocketNoThrow(_acceptFd); + _acceptFd = null; + } if(_fd != null) { Network.closeSocketNoThrow(_fd); @@ -136,27 +138,9 @@ namespace IceInternal _addr = (IPEndPoint)Network.getAddressForServer(host, port, protocol, _instance.preferIPv6()); _fd = Network.createServerSocket(false, _addr.AddressFamily, protocol); Network.setBlock(_fd, false); -# if !COMPACT Network.setTcpBufSize(_fd, _instance); -# endif - if(AssemblyUtil.platform_ != AssemblyUtil.Platform.Windows) - { - // - // Enable SO_REUSEADDR on Unix platforms to allow re-using the - // socket even if it's in the TIME_WAIT state. On Windows, - // this doesn't appear to be necessary and enabling - // SO_REUSEADDR would actually not be a good thing since it - // allows a second process to bind to an address even it's - // already bound by another process. - // - // TODO: using SO_EXCLUSIVEADDRUSE on Windows would probably - // be better but it's only supported by recent Windows - // versions (XP SP2, Windows Server 2003). - // - Network.setReuseAddress(_fd, true); - } } - catch(System.Exception) + catch(Exception) { _fd = null; throw; @@ -167,10 +151,9 @@ namespace IceInternal private ProtocolInstance _instance; private Socket _fd; private Socket _acceptFd; - private System.Exception _acceptError; + private Exception _acceptError; private int _backlog; private IPEndPoint _addr; private IAsyncResult _result; } } -#endif diff --git a/csharp/src/Ice/TcpConnector.cs b/csharp/src/Ice/TcpConnector.cs index 2cc7bc9de1d..b0ee6bb7df8 100644 --- a/csharp/src/Ice/TcpConnector.cs +++ b/csharp/src/Ice/TcpConnector.cs @@ -9,10 +9,7 @@ namespace IceInternal { - using System; - using System.Diagnostics; using System.Net; - using System.Net.Sockets; sealed class TcpConnector : Connector { @@ -40,13 +37,13 @@ namespace IceInternal _connectionId = connectionId; _hashCode = 5381; - IceInternal.HashUtil.hashAdd(ref _hashCode, _addr); + HashUtil.hashAdd(ref _hashCode, _addr); if(_sourceAddr != null) { - IceInternal.HashUtil.hashAdd(ref _hashCode, _sourceAddr); + HashUtil.hashAdd(ref _hashCode, _sourceAddr); } - IceInternal.HashUtil.hashAdd(ref _hashCode, _timeout); - IceInternal.HashUtil.hashAdd(ref _hashCode, _connectionId); + HashUtil.hashAdd(ref _hashCode, _timeout); + HashUtil.hashAdd(ref _hashCode, _connectionId); } public override bool Equals(object obj) diff --git a/csharp/src/Ice/TcpEndpointI.cs b/csharp/src/Ice/TcpEndpointI.cs index 0c281fa0083..e45d2bce4d3 100644 --- a/csharp/src/Ice/TcpEndpointI.cs +++ b/csharp/src/Ice/TcpEndpointI.cs @@ -9,13 +9,11 @@ namespace IceInternal { - using System.Diagnostics; using System.Collections.Generic; using System.Net; - using System; using System.Globalization; - sealed class TcpEndpointI : IPEndpointI, WSEndpointDelegate + sealed class TcpEndpointI : IPEndpointI { public TcpEndpointI(ProtocolInstance instance, string ho, int po, EndPoint sourceAddr, int ti, string conId, bool co) : @@ -32,7 +30,7 @@ namespace IceInternal _compress = false; } - public TcpEndpointI(ProtocolInstance instance, BasicStream s) : + public TcpEndpointI(ProtocolInstance instance, Ice.InputStream s) : base(instance, s) { _timeout = s.readInt(); @@ -64,43 +62,17 @@ namespace IceInternal private IPEndpointI _endpoint; } - public override Ice.EndpointInfo getInfo() - { - InfoI info = new InfoI(this); - fillEndpointInfo(info); - return info; - } - - private sealed class WSInfoI : Ice.WSEndpointInfo + public override void streamWriteImpl(Ice.OutputStream s) { - public WSInfoI(IPEndpointI e) - { - _endpoint = e; - } - - public override short type() - { - return _endpoint.type(); - } - - public override bool datagram() - { - return _endpoint.datagram(); - } - - public override bool secure() - { - return _endpoint.secure(); - } - - private IPEndpointI _endpoint; + base.streamWriteImpl(s); + s.writeInt(_timeout); + s.writeBool(_compress); } - public Ice.EndpointInfo getWSInfo(string resource) + public override Ice.EndpointInfo getInfo() { - WSInfoI info = new WSInfoI(this); + InfoI info = new InfoI(this); fillEndpointInfo(info); - info.resource = resource; return info; } @@ -150,20 +122,14 @@ namespace IceInternal public override Acceptor acceptor(string adapterName) { -#if SILVERLIGHT - throw new Ice.FeatureNotSupportedException("server endpoint not supported for `" + ToString() + "'"); -#else return new TcpAcceptor(this, instance_, host_, port_); -#endif } -#if !SILVERLIGHT public TcpEndpointI endpoint(TcpAcceptor acceptor) { return new TcpEndpointI(instance_, host_, acceptor.effectivePort(), sourceAddr_, _timeout, connectionId_, _compress); } -#endif public override string options() { @@ -227,18 +193,11 @@ namespace IceInternal return base.CompareTo(p); } - public override void streamWriteImpl(BasicStream s) - { - base.streamWriteImpl(s); - s.writeInt(_timeout); - s.writeBool(_compress); - } - public override void hashInit(ref int h) { base.hashInit(ref h); - IceInternal.HashUtil.hashAdd(ref h, _timeout); - IceInternal.HashUtil.hashAdd(ref h, _compress); + HashUtil.hashAdd(ref h, _timeout); + HashUtil.hashAdd(ref h, _compress); } public override void fillEndpointInfo(Ice.IPEndpointInfo info) @@ -273,7 +232,7 @@ namespace IceInternal { try { - _timeout = System.Int32.Parse(argument, CultureInfo.InvariantCulture); + _timeout = int.Parse(argument, CultureInfo.InvariantCulture); if(_timeout < 1) { Ice.EndpointParseException e = new Ice.EndpointParseException(); @@ -350,7 +309,7 @@ namespace IceInternal return endpt; } - public EndpointI read(BasicStream s) + public EndpointI read(Ice.InputStream s) { return new TcpEndpointI(_instance, s); } @@ -360,7 +319,7 @@ namespace IceInternal _instance = null; } - public EndpointFactory clone(ProtocolInstance instance) + public EndpointFactory clone(ProtocolInstance instance, EndpointFactory del) { return new TcpEndpointFactory(instance); } diff --git a/csharp/src/Ice/TcpTransceiver.cs b/csharp/src/Ice/TcpTransceiver.cs index 5a453408fb0..aec5e714c66 100644 --- a/csharp/src/Ice/TcpTransceiver.cs +++ b/csharp/src/Ice/TcpTransceiver.cs @@ -9,14 +9,12 @@ namespace IceInternal { - using System; - using System.ComponentModel; using System.Diagnostics; using System.Collections.Generic; using System.Net; using System.Net.Sockets; - sealed class TcpTransceiver : Transceiver, WSTransceiverDelegate + sealed class TcpTransceiver : Transceiver { public Socket fd() { @@ -89,15 +87,17 @@ namespace IceInternal public Ice.ConnectionInfo getInfo() { Ice.TCPConnectionInfo info = new Ice.TCPConnectionInfo(); - fillConnectionInfo(info); - return info; - } - - public Ice.ConnectionInfo getWSInfo(Dictionary<string, string> headers) - { - Ice.WSConnectionInfo info = new Ice.WSConnectionInfo(); - fillConnectionInfo(info); - info.headers = headers; + if(_stream.fd() != null) + { + EndPoint localEndpoint = Network.getLocalAddress(_stream.fd()); + info.localAddress = Network.endpointAddressToString(localEndpoint); + info.localPort = Network.endpointPort(localEndpoint); + EndPoint remoteEndpoint = Network.getRemoteAddress(_stream.fd()); + info.remoteAddress = Network.endpointAddressToString(remoteEndpoint); + info.remotePort = Network.endpointPort(remoteEndpoint); + info.rcvSize = Network.getRecvBufferSize(_stream.fd()); + info.sndSize = Network.getSendBufferSize(_stream.fd()); + } return info; } @@ -129,21 +129,6 @@ namespace IceInternal _stream = stream; } - private void fillConnectionInfo(Ice.TCPConnectionInfo info) - { - if(_stream.fd() != null) - { - EndPoint localEndpoint = Network.getLocalAddress(_stream.fd()); - info.localAddress = Network.endpointAddressToString(localEndpoint); - info.localPort = Network.endpointPort(localEndpoint); - EndPoint remoteEndpoint = Network.getRemoteAddress(_stream.fd()); - info.remoteAddress = Network.endpointAddressToString(remoteEndpoint); - info.remotePort = Network.endpointPort(remoteEndpoint); - info.rcvSize = Network.getRecvBufferSize(_stream.fd()); - info.sndSize = Network.getSendBufferSize(_stream.fd()); - } - } - private readonly ProtocolInstance _instance; private readonly StreamSocket _stream; } diff --git a/csharp/src/Ice/ThreadHookPlugin.cs b/csharp/src/Ice/ThreadHookPlugin.cs index 882c76b1775..d1d5a02b450 100644 --- a/csharp/src/Ice/ThreadHookPlugin.cs +++ b/csharp/src/Ice/ThreadHookPlugin.cs @@ -15,7 +15,7 @@ namespace Ice /// thread notification hook and return the instance from their /// PluginFactory implementation. /// </summary> - public class ThreadHookPlugin : Ice.Plugin + public class ThreadHookPlugin : Plugin { /// <summary> /// Installs a custom logger for a communicator. diff --git a/csharp/src/Ice/ThreadPool.cs b/csharp/src/Ice/ThreadPool.cs index e52eea51d10..94e0ebba602 100644 --- a/csharp/src/Ice/ThreadPool.cs +++ b/csharp/src/Ice/ThreadPool.cs @@ -9,8 +9,6 @@ namespace IceInternal { - - using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; @@ -18,6 +16,48 @@ namespace IceInternal public delegate void ThreadPoolWorkItem(); public delegate void AsyncCallback(object state); + // + // Thread pool threads set a custom synchronization context to ensure that + // continuations from awaited methods continue executing on the thread pool + // and not on the thread that notifies the awaited task. + // + sealed class ThreadPoolSynchronizationContext : SynchronizationContext + { + public ThreadPoolSynchronizationContext(ThreadPool threadPool) + { + _threadPool = threadPool; + } + + public override void Post(SendOrPostCallback d, object state) + { + // + // Dispatch the continuation on the thread pool if this isn't called + // already from a thread pool thread. We don't use the dispatcher + // for the continuations, the dispatcher is only used when the + // call is initialy invoked (e.g.: a servant dispatch after being + // received is dispatched using the dispatcher which might dispatch + // the call on the UI thread which will then use its own synchronization + // context to execute continuations). + // + var ctx = Current as ThreadPoolSynchronizationContext; + if(ctx != this) + { + _threadPool.dispatch(() => { d(state); }, null, false); + } + else + { + d(state); + } + } + + public override void Send(SendOrPostCallback d, object state) + { + throw new System.NotSupportedException("the thread pool doesn't support synchronous calls"); + } + + private ThreadPool _threadPool; + } + internal struct ThreadPoolMessage { public ThreadPoolMessage(object mutex) @@ -197,15 +237,9 @@ namespace IceInternal } _stackSize = stackSize; -#if !SILVERLIGHT - _hasPriority = properties.getProperty(_prefix + ".ThreadPriority").Length > 0; - _priority = IceInternal.Util.stringToThreadPriority(properties.getProperty(_prefix + ".ThreadPriority")); - if(!_hasPriority) - { - _hasPriority = properties.getProperty("Ice.ThreadPriority").Length > 0; - _priority = IceInternal.Util.stringToThreadPriority(properties.getProperty("Ice.ThreadPriority")); - } -#endif + _priority = properties.getProperty(_prefix + ".ThreadPriority").Length > 0 ? + Util.stringToThreadPriority(properties.getProperty(_prefix + ".ThreadPriority")) : + Util.stringToThreadPriority(properties.getProperty("Ice.ThreadPriority")); if(_instance.traceLevels().threadPool >= 1) { @@ -222,18 +256,7 @@ namespace IceInternal for(int i = 0; i < _size; ++i) { WorkerThread thread = new WorkerThread(this, _threadPrefix + "-" + _threadIndex++); -#if !SILVERLIGHT - if(_hasPriority) - { - thread.start(_priority); - } - else - { - thread.start(ThreadPriority.Normal); - } -#else - thread.start(); -#endif + thread.start(_priority); _threads.Add(thread); } } @@ -257,7 +280,7 @@ namespace IceInternal return; } _destroyed = true; - System.Threading.Monitor.PulseAll(this); + Monitor.PulseAll(this); } } @@ -274,7 +297,12 @@ namespace IceInternal public void initialize(EventHandler handler) { - // Nothing to do. + handler._ready = 0; + handler._pending = 0; + handler._started = 0; + handler._finish = false; + handler._hasMoreData = false; + handler._registered = 0; } public void register(EventHandler handler, int op) @@ -332,12 +360,13 @@ namespace IceInternal { Debug.Assert(!_destroyed); + handler._registered = SocketOperation.None; + // // If there are no pending asynchronous operations, we can call finish on the handler now. // if(handler._pending == 0) { - handler._registered = SocketOperation.None; executeNonBlocking(() => { ThreadPoolCurrent current = new ThreadPoolCurrent(this, handler, SocketOperation.None); @@ -351,11 +380,7 @@ namespace IceInternal } } -#if COMPACT - public void dispatchFromThisThread(Ice.VoidAction call, Ice.Connection con) -#else public void dispatchFromThisThread(System.Action call, Ice.Connection con) -#endif { if(_dispatcher != null) { @@ -370,7 +395,7 @@ namespace IceInternal { _instance.initializationData().logger.warning("dispatch exception:\n" + ex); } - } + } } else { @@ -378,11 +403,7 @@ namespace IceInternal } } -#if COMPACT - public void dispatch(Ice.VoidAction call, Ice.Connection con) -#else - public void dispatch(System.Action call, Ice.Connection con) -#endif + public void dispatch(System.Action call, Ice.Connection con, bool useDispatcher = true) { lock(this) { @@ -391,11 +412,15 @@ namespace IceInternal throw new Ice.CommunicatorDestroyedException(); } - _workItems.Enqueue(() => - { - dispatchFromThisThread(call, con); - }); - System.Threading.Monitor.Pulse(this); + if(useDispatcher) + { + _workItems.Enqueue(() => { dispatchFromThisThread(call, con); }); + } + else + { + _workItems.Enqueue(() => { call(); }); + } + Monitor.Pulse(this); // // If this is a dynamic thread pool which can still grow and if all threads are @@ -415,18 +440,7 @@ namespace IceInternal try { WorkerThread t = new WorkerThread(this, _threadPrefix + "-" + _threadIndex++); -#if !SILVERLIGHT - if(_hasPriority) - { - t.start(_priority); - } - else - { - t.start(ThreadPriority.Normal); - } -#else - t.start(); -#endif + t.start(_priority); _threads.Add(t); } catch(System.Exception ex) @@ -500,7 +514,7 @@ namespace IceInternal if(_threadIdleTime > 0) { - if(!System.Threading.Monitor.Wait(this, _threadIdleTime * 1000) && _workItems.Count == 0) // If timeout + if(!Monitor.Wait(this, _threadIdleTime * 1000) && _workItems.Count == 0) // If timeout { if(_destroyed) { @@ -532,7 +546,7 @@ namespace IceInternal else { Debug.Assert(_serverIdleTime > 0 && _inUse == 0 && _threads.Count == 1); - if(!System.Threading.Monitor.Wait(this, _serverIdleTime * 1000) && + if(!Monitor.Wait(this, _serverIdleTime * 1000) && _workItems.Count == 0) { if(!_destroyed) @@ -554,7 +568,7 @@ namespace IceInternal } else { - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); } } @@ -778,7 +792,6 @@ namespace IceInternal _thread.Join(); } -#if !SILVERLIGHT public void start(ThreadPriority priority) { if(_threadPool._stackSize == 0) @@ -794,18 +807,15 @@ namespace IceInternal _thread.Priority = priority; _thread.Start(); } -#else - public void start() - { - _thread = new Thread(new ThreadStart(Run)); - _thread.IsBackground = true; - _thread.Name = _name; - _thread.Start(); - } -#endif public void Run() { + // + // Set the default synchronization context to allow async/await to run + // continuations on the thread pool. + // + SynchronizationContext.SetSynchronizationContext(new ThreadPoolSynchronizationContext(_threadPool)); + if(_threadPool._instance.initializationData().threadHook != null) { try @@ -858,10 +868,7 @@ namespace IceInternal private readonly int _sizeMax; // Maximum number of threads. private readonly int _sizeWarn; // If _inUse reaches _sizeWarn, a "low on threads" warning will be printed. private readonly bool _serialize; // True if requests need to be serialized over the connection. -#if !SILVERLIGHT private readonly ThreadPriority _priority; - private readonly bool _hasPriority = false; -#endif private readonly int _serverIdleTime; private readonly int _threadIdleTime; private readonly int _stackSize; diff --git a/csharp/src/Ice/Time.cs b/csharp/src/Ice/Time.cs index e487f1a31f1..e1802dfa912 100644 --- a/csharp/src/Ice/Time.cs +++ b/csharp/src/Ice/Time.cs @@ -9,7 +9,6 @@ namespace IceInternal { -#if !SILVERLIGHT using System.Diagnostics; public sealed class Time @@ -26,78 +25,4 @@ namespace IceInternal private static Stopwatch _stopwatch = new Stopwatch(); } - -#else - - public class Stopwatch - { - public void Start() - { - if(!_running) - { - _startTick = System.DateTime.Now.Ticks; - _running = true; - } - } - - public void Stop() - { - if(_running) - { - _elapsedTicks += System.DateTime.Now.Ticks - _startTick; - _running = false; - } - - } - - public void Reset() - { - _startTick = 0; - _elapsedTicks = 0; - _running = false; - } - - public long ElapsedTicks - { - get - { - if(!_running) - { - return _elapsedTicks; - } - else - { - return _elapsedTicks + (System.DateTime.Now.Ticks - _startTick); - } - } - } - - public long Frequency - { - get - { - return System.TimeSpan.TicksPerMillisecond * 1000; - } - } - - private long _startTick = 0; - private long _elapsedTicks = 0; - private bool _running = false; - } - - public sealed class Time - { - static Time() - { - _begin = System.DateTime.Now.Ticks; - } - - public static long currentMonotonicTimeMillis() - { - return (System.DateTime.Now.Ticks - _begin) / 10000; - } - - private static long _begin; - } -#endif } diff --git a/csharp/src/Ice/Timer.cs b/csharp/src/Ice/Timer.cs index 8353f206bc5..cfa61c912b6 100644 --- a/csharp/src/Ice/Timer.cs +++ b/csharp/src/Ice/Timer.cs @@ -15,10 +15,8 @@ namespace IceInternal { - using System; using System.Diagnostics; using System.Threading; - using System.Collections; using System.Collections.Generic; public interface TimerTask @@ -38,7 +36,7 @@ namespace IceInternal } _instance = null; - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); _tokens.Clear(); _tasks.Clear(); @@ -61,16 +59,7 @@ namespace IceInternal try { _tasks.Add(task, token); -#if SILVERLIGHT - int index = _tokens.BinarySearch(token); - Debug.Assert(index < 0); - if(index < 0) - { - _tokens.Insert(~index, token); - } -#else _tokens.Add(token, null); -#endif } catch(System.ArgumentException) { @@ -79,7 +68,7 @@ namespace IceInternal if(token.scheduledTime < _wakeUpTime) { - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } } } @@ -98,16 +87,7 @@ namespace IceInternal try { _tasks.Add(task, token); -#if SILVERLIGHT - int index = _tokens.BinarySearch(token); - Debug.Assert(index < 0); - if(index < 0) - { - _tokens.Insert(~index, token); - } -#else _tokens.Add(token, null); -#endif } catch(System.ArgumentException) { @@ -116,7 +96,7 @@ namespace IceInternal if(token.scheduledTime < _wakeUpTime) { - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } } } @@ -144,27 +124,12 @@ namespace IceInternal // // Only for use by Instance. // -#if !SILVERLIGHT - internal Timer(IceInternal.Instance instance, ThreadPriority priority) + internal Timer(Instance instance, ThreadPriority priority = ThreadPriority.Normal) { init(instance, priority, true); } -#endif - - internal Timer(IceInternal.Instance instance) - { -#if !SILVERLIGHT - init(instance, ThreadPriority.Normal, false); -#else - init(instance); -#endif - } -#if !SILVERLIGHT - internal void init(IceInternal.Instance instance, ThreadPriority priority, bool hasPriority) -#else - internal void init(IceInternal.Instance instance) -#endif + internal void init(Instance instance, ThreadPriority priority, bool hasPriority) { _instance = instance; @@ -177,12 +142,10 @@ namespace IceInternal _thread = new Thread(new ThreadStart(Run)); _thread.IsBackground = true; _thread.Name = threadName + "Ice.Timer"; -#if !SILVERLIGHT if(hasPriority) { _thread.Priority = priority; } -#endif _thread.Start(); } @@ -220,16 +183,7 @@ namespace IceInternal if(_tasks.ContainsKey(token.task)) { token.scheduledTime = Time.currentMonotonicTimeMillis() + token.delay; -#if SILVERLIGHT - int index = _tokens.BinarySearch(token); - Debug.Assert(index < 0); - if(index < 0) - { - _tokens.Insert(~index, token); - } -#else _tokens.Add(token, null); -#endif } } } @@ -242,8 +196,8 @@ namespace IceInternal if(_tokens.Count == 0) { - _wakeUpTime = System.Int64.MaxValue; - System.Threading.Monitor.Wait(this); + _wakeUpTime = long.MaxValue; + Monitor.Wait(this); } if(_instance == null) @@ -256,11 +210,7 @@ namespace IceInternal long now = Time.currentMonotonicTimeMillis(); Token first = null; -#if SILVERLIGHT - foreach(Token t in _tokens) -#else foreach(Token t in _tokens.Keys) -#endif { first = t; break; @@ -279,7 +229,7 @@ namespace IceInternal } _wakeUpTime = first.scheduledTime; - System.Threading.Monitor.Wait(this, (int)(first.scheduledTime - now)); + Monitor.Wait(this, (int)(first.scheduledTime - now)); } if(_instance == null) @@ -367,7 +317,7 @@ namespace IceInternal public override bool Equals(object o) { - if(object.ReferenceEquals(this, o)) + if(ReferenceEquals(this, o)) { return true; } @@ -378,8 +328,8 @@ namespace IceInternal public override int GetHashCode() { int h = 5381; - IceInternal.HashUtil.hashAdd(ref h, id); - IceInternal.HashUtil.hashAdd(ref h, scheduledTime); + HashUtil.hashAdd(ref h, id); + HashUtil.hashAdd(ref h, scheduledTime); return h; } @@ -389,16 +339,10 @@ namespace IceInternal public TimerTask task; } -#if COMPACT - private IDictionary<Token, object> _tokens = new SortedList<Token, object>(); -#elif SILVERLIGHT - private List<Token> _tokens = new List<Token>(); -#else private IDictionary<Token, object> _tokens = new SortedDictionary<Token, object>(); -#endif private IDictionary<TimerTask, Token> _tasks = new Dictionary<TimerTask, Token>(); private Instance _instance; - private long _wakeUpTime = System.Int64.MaxValue; + private long _wakeUpTime = long.MaxValue; private int _tokenId = 0; private Thread _thread; diff --git a/csharp/src/Ice/TraceLevels.cs b/csharp/src/Ice/TraceLevels.cs index c9f302965f2..b9f488ec4e0 100644 --- a/csharp/src/Ice/TraceLevels.cs +++ b/csharp/src/Ice/TraceLevels.cs @@ -9,7 +9,6 @@ namespace IceInternal { - public sealed class TraceLevels { internal TraceLevels(Ice.Properties properties) diff --git a/csharp/src/Ice/TraceUtil.cs b/csharp/src/Ice/TraceUtil.cs index a925ba85f5c..e772b44717b 100644 --- a/csharp/src/Ice/TraceUtil.cs +++ b/csharp/src/Ice/TraceUtil.cs @@ -9,23 +9,23 @@ namespace IceInternal { - using System.Collections.Generic; using System.Diagnostics; using System.Globalization; sealed class TraceUtil { - internal static void traceSend(BasicStream str, Ice.Logger logger, TraceLevels tl) + internal static void traceSend(Ice.OutputStream str, Ice.Logger logger, TraceLevels tl) { if(tl.protocol >= 1) { int p = str.pos(); - str.pos(0); + Ice.InputStream iss = new Ice.InputStream(str.instance(), str.getEncoding(), str.getBuffer(), false); + iss.pos(0); using(System.IO.StringWriter s = new System.IO.StringWriter(CultureInfo.CurrentCulture)) { - byte type = printMessage(s, str); + byte type = printMessage(s, iss); logger.trace(tl.protocolCat, "sending " + getMessageTypeAsString(type) + " " + s.ToString()); } @@ -33,7 +33,7 @@ namespace IceInternal } } - internal static void traceRecv(BasicStream str, Ice.Logger logger, TraceLevels tl) + internal static void traceRecv(Ice.InputStream str, Ice.Logger logger, TraceLevels tl) { if(tl.protocol >= 1) { @@ -50,7 +50,26 @@ namespace IceInternal } } - internal static void trace(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) + internal static void trace(string heading, Ice.OutputStream str, Ice.Logger logger, TraceLevels tl) + { + if(tl.protocol >= 1) + { + int p = str.pos(); + Ice.InputStream iss = new Ice.InputStream(str.instance(), str.getEncoding(), str.getBuffer(), false); + iss.pos(0); + + using(System.IO.StringWriter s = new System.IO.StringWriter(CultureInfo.CurrentCulture)) + { + s.Write(heading); + printMessage(s, iss); + + logger.trace(tl.protocolCat, s.ToString()); + } + str.pos(p); + } + } + + internal static void trace(string heading, Ice.InputStream str, Ice.Logger logger, TraceLevels tl) { if(tl.protocol >= 1) { @@ -72,7 +91,7 @@ namespace IceInternal internal static void traceSlicing(string kind, string typeId, string slicingCat, Ice.Logger logger) { - lock(typeof(IceInternal.TraceUtil)) + lock(typeof(TraceUtil)) { if(slicingIds.Add(typeId)) { @@ -85,7 +104,7 @@ namespace IceInternal } } - public static void dumpStream(BasicStream stream) + public static void dumpStream(Ice.InputStream stream) { int pos = stream.pos(); stream.pos(0); @@ -107,7 +126,7 @@ namespace IceInternal { if(j < data.Length) { - int n = (int)data[j]; + int n = data[j]; if(n < 0) { n += 256; @@ -138,7 +157,7 @@ namespace IceInternal for(int j = i; j < data.Length && j - i < inc; j++) { // TODO: this needs fixing - if(data[j] >= (byte)32 && data[j] < (byte)127) + if(data[j] >= 32 && data[j] < 127) { System.Console.Out.Write((char) data[j]); } @@ -152,19 +171,25 @@ namespace IceInternal } } - private static void printIdentityFacetOperation(System.IO.StringWriter s, BasicStream str) + private static void printIdentityFacetOperation(System.IO.StringWriter s, Ice.InputStream str) { try { + Ice.ToStringMode toStringMode = Ice.ToStringMode.Unicode; + if(str.instance() != null) + { + toStringMode = str.instance().toStringMode(); + } + Ice.Identity identity = new Ice.Identity(); - identity.read__(str); - s.Write("\nidentity = " + str.instance().identityToString(identity)); + identity.ice_readMembers(str); + s.Write("\nidentity = " + Ice.Util.identityToString(identity, toStringMode)); string[] facet = str.readStringSeq(); s.Write("\nfacet = "); if(facet.Length > 0) { - s.Write(IceUtilInternal.StringUtil.escapeString(facet[0], "")); + s.Write(IceUtilInternal.StringUtil.escapeString(facet[0], "", toStringMode)); } string operation = str.readString(); @@ -176,7 +201,7 @@ namespace IceInternal } } - private static void printRequest(System.IO.StringWriter s, BasicStream str) + private static void printRequest(System.IO.StringWriter s, Ice.InputStream str) { int requestId = str.readInt(); s.Write("\nrequest id = " + requestId); @@ -188,7 +213,7 @@ namespace IceInternal printRequestHeader(s, str); } - private static void printBatchRequest(System.IO.StringWriter s, BasicStream str) + private static void printBatchRequest(System.IO.StringWriter s, Ice.InputStream str) { int batchRequestNum = str.readInt(); s.Write("\nnumber of requests = " + batchRequestNum); @@ -200,7 +225,7 @@ namespace IceInternal } } - private static void printReply(System.IO.StringWriter s, BasicStream str) + private static void printReply(System.IO.StringWriter s, Ice.InputStream str) { int requestId = str.readInt(); s.Write("\nrequest id = " + requestId); @@ -302,7 +327,7 @@ namespace IceInternal if(replyStatus == ReplyStatus.replyOK || replyStatus == ReplyStatus.replyUserException) { - Ice.EncodingVersion v = str.skipEncaps(); + Ice.EncodingVersion v = str.skipEncapsulation(); if(!v.Equals(Ice.Util.Encoding_1_0)) { s.Write("\nencoding = "); @@ -311,7 +336,7 @@ namespace IceInternal } } - private static void printRequestHeader(System.IO.StringWriter s, BasicStream str) + private static void printRequestHeader(System.IO.StringWriter s, Ice.InputStream str) { printIdentityFacetOperation(s, str); @@ -359,7 +384,7 @@ namespace IceInternal } } - Ice.EncodingVersion v = str.skipEncaps(); + Ice.EncodingVersion v = str.skipEncapsulation(); if(!v.Equals(Ice.Util.Encoding_1_0)) { s.Write("\nencoding = "); @@ -372,7 +397,7 @@ namespace IceInternal } } - private static byte printHeader(System.IO.StringWriter s, BasicStream str) + private static byte printHeader(System.IO.StringWriter s, Ice.InputStream str) { try { @@ -396,19 +421,19 @@ namespace IceInternal s.Write("\ncompression status = " + (int)compress + ' '); switch(compress) { - case (byte)0: + case 0: { s.Write("(not compressed; do not compress response, if any)"); break; } - case (byte)1: + case 1: { s.Write("(not compressed; compress response, if any)"); break; } - case (byte)2: + case 2: { s.Write("(compressed; compress response, if any)"); break; @@ -432,7 +457,7 @@ namespace IceInternal } } - private static byte printMessage(System.IO.StringWriter s, BasicStream str) + private static byte printMessage(System.IO.StringWriter s, Ice.InputStream str) { byte type = printHeader(s, str); @@ -473,7 +498,7 @@ namespace IceInternal return type; } - internal static void traceHeader(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) + internal static void traceHeader(string heading, Ice.InputStream str, Ice.Logger logger, TraceLevels tl) { if(tl.protocol >= 1) { diff --git a/csharp/src/Ice/Transceiver.cs b/csharp/src/Ice/Transceiver.cs index 78189cfc041..5b330a9138b 100644 --- a/csharp/src/Ice/Transceiver.cs +++ b/csharp/src/Ice/Transceiver.cs @@ -9,7 +9,6 @@ namespace IceInternal { - using System; using System.Net.Sockets; public interface Transceiver diff --git a/csharp/src/Ice/UdpConnector.cs b/csharp/src/Ice/UdpConnector.cs index a4f171e47dd..e2b8cd0b9b8 100644 --- a/csharp/src/Ice/UdpConnector.cs +++ b/csharp/src/Ice/UdpConnector.cs @@ -9,10 +9,7 @@ namespace IceInternal { - using System; - using System.Diagnostics; using System.Net; - using System.Net.Sockets; sealed class UdpConnector : Connector { @@ -40,14 +37,14 @@ namespace IceInternal _connectionId = connectionId; _hashCode = 5381; - IceInternal.HashUtil.hashAdd(ref _hashCode, _addr); + HashUtil.hashAdd(ref _hashCode, _addr); if(sourceAddr != null) { - IceInternal.HashUtil.hashAdd(ref _hashCode, _sourceAddr); + HashUtil.hashAdd(ref _hashCode, _sourceAddr); } - IceInternal.HashUtil.hashAdd(ref _hashCode, _mcastInterface); - IceInternal.HashUtil.hashAdd(ref _hashCode, _mcastTtl); - IceInternal.HashUtil.hashAdd(ref _hashCode, _connectionId); + HashUtil.hashAdd(ref _hashCode, _mcastInterface); + HashUtil.hashAdd(ref _hashCode, _mcastTtl); + HashUtil.hashAdd(ref _hashCode, _connectionId); } public override bool Equals(object obj) diff --git a/csharp/src/Ice/UdpEndpointI.cs b/csharp/src/Ice/UdpEndpointI.cs index a792bf71b83..b25107e327d 100644 --- a/csharp/src/Ice/UdpEndpointI.cs +++ b/csharp/src/Ice/UdpEndpointI.cs @@ -9,7 +9,6 @@ namespace IceInternal { - using System.Diagnostics; using System.Collections; using System.Collections.Generic; @@ -36,10 +35,10 @@ namespace IceInternal _compress = false; } - public UdpEndpointI(ProtocolInstance instance, BasicStream s) : + public UdpEndpointI(ProtocolInstance instance, Ice.InputStream s) : base(instance, s) { - if(s.getReadEncoding().Equals(Ice.Util.Encoding_1_0)) + if(s.getEncoding().Equals(Ice.Util.Encoding_1_0)) { s.readByte(); s.readByte(); @@ -159,6 +158,24 @@ namespace IceInternal return null; } + public override void initWithOptions(List<string> args, bool oaEndpoint) + { + base.initWithOptions(args, oaEndpoint); + + if(_mcastInterface.Equals("*")) + { + if(oaEndpoint) + { + _mcastInterface = ""; + } + else + { + throw new Ice.EndpointParseException("`--interface *' not valid for proxy endpoint `" + + ToString() + "'"); + } + } + } + public UdpEndpointI endpoint(UdpTransceiver transceiver) { return new UdpEndpointI(instance_, host_, transceiver.effectivePort(), sourceAddr_, _mcastInterface, @@ -254,13 +271,13 @@ namespace IceInternal // // Marshal the endpoint // - public override void streamWriteImpl(BasicStream s) + public override void streamWriteImpl(Ice.OutputStream s) { base.streamWriteImpl(s); - if(s.getWriteEncoding().Equals(Ice.Util.Encoding_1_0)) + if(s.getEncoding().Equals(Ice.Util.Encoding_1_0)) { - Ice.Util.Protocol_1_0.write__(s); - Ice.Util.Encoding_1_0.write__(s); + Ice.Util.Protocol_1_0.ice_writeMembers(s); + Ice.Util.Encoding_1_0.ice_writeMembers(s); } // Not transmitted. //s.writeBool(_connect); @@ -270,10 +287,10 @@ namespace IceInternal public override void hashInit(ref int h) { base.hashInit(ref h); - IceInternal.HashUtil.hashAdd(ref h, _mcastInterface); - IceInternal.HashUtil.hashAdd(ref h, _mcastTtl); - IceInternal.HashUtil.hashAdd(ref h, _connect); - IceInternal.HashUtil.hashAdd(ref h, _compress); + HashUtil.hashAdd(ref h, _mcastInterface); + HashUtil.hashAdd(ref h, _mcastTtl); + HashUtil.hashAdd(ref h, _connect); + HashUtil.hashAdd(ref h, _compress); } public override void fillEndpointInfo(Ice.IPEndpointInfo info) @@ -353,9 +370,9 @@ namespace IceInternal try { - _mcastTtl = System.Int32.Parse(argument, CultureInfo.InvariantCulture); + _mcastTtl = int.Parse(argument, CultureInfo.InvariantCulture); } - catch(System.FormatException ex) + catch(FormatException ex) { Ice.EndpointParseException e = new Ice.EndpointParseException(ex); e.str = "invalid TTL value `" + argument + "' in endpoint " + endpoint; @@ -428,7 +445,7 @@ namespace IceInternal return endpt; } - public EndpointI read(BasicStream s) + public EndpointI read(Ice.InputStream s) { return new UdpEndpointI(_instance, s); } @@ -438,7 +455,7 @@ namespace IceInternal _instance = null; } - public EndpointFactory clone(ProtocolInstance instance) + public EndpointFactory clone(ProtocolInstance instance, EndpointFactory del) { return new UdpEndpointFactory(instance); } diff --git a/csharp/src/Ice/UdpTransceiver.cs b/csharp/src/Ice/UdpTransceiver.cs index b65a5cdea4a..0b469bba3ac 100644 --- a/csharp/src/Ice/UdpTransceiver.cs +++ b/csharp/src/Ice/UdpTransceiver.cs @@ -7,14 +7,6 @@ // // ********************************************************************** -// -// .NET and Silverlight use the new socket asynchronous APIs whereas -// the compact framework and mono still use the old Begin/End APIs. -// -#if !COMPACT && !__MonoCS__ && !UNITY -#define ICE_SOCKET_ASYNC_API -#endif - namespace IceInternal { using System; @@ -37,7 +29,6 @@ namespace IceInternal if(_state == StateNeedConnect) { _state = StateConnectPending; -#if ICE_SOCKET_ASYNC_API && !SILVERLIGHT try { if(_sourceAddr != null) @@ -58,31 +49,23 @@ namespace IceInternal { throw new Ice.ConnectFailedException(ex); } -#else - return SocketOperation.Connect; -#endif } if(_state <= StateConnectPending) { -#if !SILVERLIGHT - if(!AssemblyUtil.osx_) + // + // On Windows, we delay the join for the mcast group after the connection + // establishment succeeds. This is necessary for older Windows versions + // where joining the group fails if the socket isn't bound. See ICE-5113. + // + if(Network.isMulticast((IPEndPoint)_addr)) { - // - // On Windows, we delay the join for the mcast group after the connection - // establishment succeeds. This is necessary for older Windows versions - // where joining the group fails if the socket isn't bound. See ICE-5113. - // - if(Network.isMulticast((IPEndPoint)_addr)) + Network.setMcastGroup(_fd, ((IPEndPoint)_addr).Address, _mcastInterface); + if(_mcastTtl != -1) { - Network.setMcastGroup(_fd, ((IPEndPoint)_addr).Address, _mcastInterface); - if(_mcastTtl != -1) - { - Network.setMcastTtl(_fd, _mcastTtl, _addr.AddressFamily); - } + Network.setMcastTtl(_fd, _mcastTtl, _addr.AddressFamily); } } -#endif _state = StateConnected; } @@ -115,29 +98,27 @@ namespace IceInternal public EndpointI bind() { -#if !SILVERLIGHT if(Network.isMulticast((IPEndPoint)_addr)) { Network.setReuseAddress(_fd, true); _mcastAddr = (IPEndPoint)_addr; - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) + + // + // Windows does not allow binding to the mcast address itself + // so we bind to INADDR_ANY (0.0.0.0) instead. As a result, + // bi-directional connection won't work because the source + // address won't the multicast address and the client will + // therefore reject the datagram. + // + if(_addr.AddressFamily == AddressFamily.InterNetwork) { - // - // Windows does not allow binding to the mcast address itself - // so we bind to INADDR_ANY (0.0.0.0) instead. As a result, - // bi-directional connection won't work because the source - // address won't the multicast address and the client will - // therefore reject the datagram. - // - if(_addr.AddressFamily == AddressFamily.InterNetwork) - { - _addr = new IPEndPoint(IPAddress.Any, _port); - } - else - { - _addr = new IPEndPoint(IPAddress.IPv6Any, _port); - } + _addr = new IPEndPoint(IPAddress.Any, _port); + } + else + { + _addr = new IPEndPoint(IPAddress.IPv6Any, _port); } + _addr = Network.doBind(_fd, _addr); if(_port == 0) { @@ -147,25 +128,8 @@ namespace IceInternal } else { - if(AssemblyUtil.platform_ != AssemblyUtil.Platform.Windows) - { - // - // Enable SO_REUSEADDR on Unix platforms to allow re-using - // the socket even if it's in the TIME_WAIT state. On - // Windows, this doesn't appear to be necessary and - // enabling SO_REUSEADDR would actually not be a good - // thing since it allows a second process to bind to an - // address even it's already bound by another process. - // - // TODO: using SO_EXCLUSIVEADDRUSE on Windows would - // probably be better but it's only supported by recent - // Windows versions (XP SP2, Windows Server 2003). - // - Network.setReuseAddress(_fd, true); - } _addr = Network.doBind(_fd, _addr); } -#endif _bound = true; _endpoint = _endpoint.endpoint(this); return _endpoint; @@ -173,10 +137,8 @@ namespace IceInternal public void destroy() { -#if ICE_SOCKET_ASYNC_API _readEventArgs.Dispose(); _writeEventArgs.Dispose(); -#endif } public int write(Buffer buf) @@ -185,25 +147,12 @@ namespace IceInternal { return SocketOperation.None; } -#if COMPACT || SILVERLIGHT -# if !ICE_SOCKET_ASYNC_API - if(_writeResult != null) - { - return SocketOperation.None; - } -# endif - // - // Silverlight and the Compact .NET Framework don't support the use of synchronous socket - // operations on a non-blocking socket. Returning SocketOperation.Write here forces the - // caller to schedule an asynchronous operation. - // - return SocketOperation.Write; -#else + Debug.Assert(buf.b.position() == 0); Debug.Assert(_fd != null && _state >= StateConnected); // The caller is supposed to check the send size before by calling checkSendSize - Debug.Assert(System.Math.Min(_maxPacketSize, _sndSize - _udpOverhead) >= buf.size()); + Debug.Assert(Math.Min(_maxPacketSize, _sndSize - _udpOverhead) >= buf.size()); int ret = 0; while(true) @@ -245,7 +194,7 @@ namespace IceInternal throw new Ice.SocketException(ex); } } - catch(System.Exception e) + catch(Exception e) { throw new Ice.SyscallException(e); } @@ -255,7 +204,6 @@ namespace IceInternal Debug.Assert(ret == buf.b.limit()); buf.b.position(buf.b.limit()); return SocketOperation.None; -#endif } public int read(Buffer buf, ref bool hasMoreData) @@ -264,18 +212,11 @@ namespace IceInternal { return SocketOperation.None; } -#if COMPACT || SILVERLIGHT - // - // Silverlight and the Compact .NET Framework don't support the use of synchronous socket - // operations on a non-blocking socket. Returning SocketOperation.Read here forces the - // caller to schedule an asynchronous operation. - // - return SocketOperation.Read; -#else + Debug.Assert(buf.b.position() == 0); Debug.Assert(_fd != null); - int packetSize = System.Math.Min(_maxPacketSize, _rcvSize - _udpOverhead); + int packetSize = Math.Min(_maxPacketSize, _rcvSize - _udpOverhead); buf.resize(packetSize, true); buf.b.position(0); @@ -339,7 +280,7 @@ namespace IceInternal throw new Ice.SocketException(e); } } - catch(System.Exception e) + catch(Exception e) { throw new Ice.SyscallException(e); } @@ -372,14 +313,13 @@ namespace IceInternal buf.b.position(ret); return SocketOperation.None; -#endif } public bool startRead(Buffer buf, AsyncCallback callback, object state) { Debug.Assert(buf.b.position() == 0); - int packetSize = System.Math.Min(_maxPacketSize, _rcvSize - _udpOverhead); + int packetSize = Math.Min(_maxPacketSize, _rcvSize - _udpOverhead); buf.resize(packetSize, true); buf.b.position(0); @@ -388,42 +328,17 @@ namespace IceInternal if(_state == StateConnected) { _readCallback = callback; -#if ICE_SOCKET_ASYNC_API _readEventArgs.UserToken = state; _readEventArgs.SetBuffer(buf.b.rawBytes(), buf.b.position(), packetSize); return !_fd.ReceiveAsync(_readEventArgs); -#else - _readResult = _fd.BeginReceive(buf.b.rawBytes(), 0, buf.b.limit(), SocketFlags.None, - readCompleted, state); - return _readResult.CompletedSynchronously; -#endif } else { Debug.Assert(_incoming); _readCallback = callback; -#if ICE_SOCKET_ASYNC_API _readEventArgs.UserToken = state; _readEventArgs.SetBuffer(buf.b.rawBytes(), 0, buf.b.limit()); return !_fd.ReceiveFromAsync(_readEventArgs); -#else - EndPoint peerAddr = _peerAddr; - if(peerAddr == null) - { - if(_addr.AddressFamily == AddressFamily.InterNetwork) - { - peerAddr = new IPEndPoint(IPAddress.Any, 0); - } - else - { - Debug.Assert(_addr.AddressFamily == AddressFamily.InterNetworkV6); - peerAddr = new IPEndPoint(IPAddress.IPv6Any, 0); - } - } - _readResult = _fd.BeginReceiveFrom(buf.b.rawBytes(), 0, buf.b.limit(), SocketFlags.None, - ref peerAddr, readCompleted, state); - return _readResult.CompletedSynchronously; -#endif } } catch(SocketException ex) @@ -457,7 +372,6 @@ namespace IceInternal int ret; try { -#if ICE_SOCKET_ASYNC_API if(_readEventArgs.SocketError != SocketError.Success) { throw new SocketException((int)_readEventArgs.SocketError); @@ -467,29 +381,6 @@ namespace IceInternal { _peerAddr = _readEventArgs.RemoteEndPoint; } -#else - Debug.Assert(_readResult != null); - if(_state == StateConnected) - { - ret = _fd.EndReceive(_readResult); - } - else - { - EndPoint peerAddr = _peerAddr; - if(_addr.AddressFamily == AddressFamily.InterNetwork) - { - peerAddr = new IPEndPoint(IPAddress.Any, 0); - } - else - { - Debug.Assert(_addr.AddressFamily == AddressFamily.InterNetworkV6); - peerAddr = new IPEndPoint(IPAddress.IPv6Any, 0); - } - ret = _fd.EndReceiveFrom(_readResult, ref peerAddr); - _peerAddr = (IPEndPoint)peerAddr; - } - _readResult = null; -#endif } catch(SocketException ex) { @@ -533,11 +424,7 @@ namespace IceInternal // If we must connect, then we connect to the first peer that // sends us a packet. // -#if ICE_SOCKET_ASYNC_API bool connected = !_fd.ConnectAsync(_readEventArgs); -#else - bool connected = Network.doConnect(_fd, _peerAddr, null); -#endif Debug.Assert(connected); _state = StateConnected; // We're connected now @@ -558,25 +445,18 @@ namespace IceInternal { Debug.Assert(_addr != null); completed = false; -#if ICE_SOCKET_ASYNC_API -# if !SILVERLIGHT if(_sourceAddr != null) { _fd.Bind(_sourceAddr); } -# endif _writeEventArgs.UserToken = state; return !_fd.ConnectAsync(_writeEventArgs); -#else - _writeResult = Network.doConnectAsync(_fd, _addr, _sourceAddr, callback, state); - return _writeResult.CompletedSynchronously; -#endif } Debug.Assert(_fd != null); // The caller is supposed to check the send size before by calling checkSendSize - Debug.Assert(System.Math.Min(_maxPacketSize, _sndSize - _udpOverhead) >= buf.size()); + Debug.Assert(Math.Min(_maxPacketSize, _sndSize - _udpOverhead) >= buf.size()); Debug.Assert(buf.b.position() == 0); @@ -587,15 +467,9 @@ namespace IceInternal if(_state == StateConnected) { -#if ICE_SOCKET_ASYNC_API _writeEventArgs.UserToken = state; _writeEventArgs.SetBuffer(buf.b.rawBytes(), 0, buf.b.limit()); completedSynchronously = !_fd.SendAsync(_writeEventArgs); -#else - _writeResult = _fd.BeginSend(buf.b.rawBytes(), 0, buf.b.limit(), SocketFlags.None, - writeCompleted, state); - completedSynchronously = _writeResult.CompletedSynchronously; -#endif } else { @@ -603,16 +477,10 @@ namespace IceInternal { throw new Ice.SocketException(); } -#if ICE_SOCKET_ASYNC_API _writeEventArgs.RemoteEndPoint = _peerAddr; _writeEventArgs.UserToken = state; _writeEventArgs.SetBuffer(buf.b.rawBytes(), 0, buf.b.limit()); completedSynchronously = !_fd.SendToAsync(_writeEventArgs); -#else - _writeResult = _fd.BeginSendTo(buf.b.rawBytes(), 0, buf.b.limit(), SocketFlags.None, _peerAddr, - writeCompleted, state); - completedSynchronously = _writeResult.CompletedSynchronously; -#endif } } catch(SocketException ex) @@ -636,17 +504,12 @@ namespace IceInternal if(_fd == null) { buf.b.position(buf.size()); // Assume all the data was sent for at-most-once semantics. -#if ICE_SOCKET_ASYNC_API _writeEventArgs = null; -#else - _writeResult = null; -#endif return; } if(!_incoming && _state < StateConnected) { -#if ICE_SOCKET_ASYNC_API if(_writeEventArgs.SocketError != SocketError.Success) { SocketException ex = new SocketException((int)_writeEventArgs.SocketError); @@ -659,34 +522,17 @@ namespace IceInternal throw new Ice.ConnectFailedException(ex); } } -#else - Debug.Assert(_writeResult != null); - Network.doFinishConnectAsync(_fd, _writeResult); - _writeResult = null; -#endif return; } int ret; try { -#if ICE_SOCKET_ASYNC_API if(_writeEventArgs.SocketError != SocketError.Success) { throw new SocketException((int)_writeEventArgs.SocketError); } ret = _writeEventArgs.BytesTransferred; -#else - if (_state == StateConnected) - { - ret = _fd.EndSend(_writeResult); - } - else - { - ret = _fd.EndSendTo(_writeResult); - } - _writeResult = null; -#endif } catch(SocketException ex) { @@ -745,13 +591,11 @@ namespace IceInternal info.rcvSize = Network.getRecvBufferSize(_fd); info.sndSize = Network.getSendBufferSize(_fd); -#if !SILVERLIGHT if(_mcastAddr != null) { info.mcastAddress = Network.endpointAddressToString(_mcastAddr); info.mcastPort = Network.endpointPort(_mcastAddr); } -#endif return info; } @@ -761,7 +605,7 @@ namespace IceInternal // The maximum packetSize is either the maximum allowable UDP packet size, or // the UDP send buffer size (which ever is smaller). // - int packetSize = System.Math.Min(_maxPacketSize, _sndSize - _udpOverhead); + int packetSize = Math.Min(_maxPacketSize, _sndSize - _udpOverhead); if(packetSize < buf.size()) { throw new Ice.DatagramLimitException(); @@ -798,24 +642,30 @@ namespace IceInternal s = Network.fdToString(_fd); } -#if !SILVERLIGHT if(_mcastAddr != null) { s += "\nmulticast address = " + Network.addrToString(_mcastAddr); } -#endif return s; } public string toDetailedString() { StringBuilder s = new StringBuilder(ToString()); - List<string> intfs = Network.getHostsForEndpointExpand( - Network.endpointAddressToString(_addr), _instance.protocolSupport(), true); + List<string> intfs; + if(_mcastAddr == null) + { + intfs = Network.getHostsForEndpointExpand(Network.endpointAddressToString(_addr), + _instance.protocolSupport(), true); + } + else + { + intfs = Network.getInterfacesForMulticast(_mcastInterface, _mcastAddr.Address); + } if(intfs.Count != 0) { s.Append("\nlocal interfaces = "); - s.Append(String.Join(", ", intfs.ToArray())); + s.Append(string.Join(", ", intfs.ToArray())); } return s.ToString(); } @@ -835,7 +685,6 @@ namespace IceInternal _addr = addr; _sourceAddr = sourceAddr; -#if ICE_SOCKET_ASYNC_API _readEventArgs = new SocketAsyncEventArgs(); _readEventArgs.RemoteEndPoint = _addr; _readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(ioCompleted); @@ -843,19 +692,6 @@ namespace IceInternal _writeEventArgs = new SocketAsyncEventArgs(); _writeEventArgs.RemoteEndPoint = _addr; _writeEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(ioCompleted); -#if SILVERLIGHT - String policy = instance.properties().getProperty("Ice.ClientAccessPolicyProtocol"); - if(policy.Equals("Http")) - { - _readEventArgs.SocketClientAccessPolicyProtocol = SocketClientAccessPolicyProtocol.Http; - _writeEventArgs.SocketClientAccessPolicyProtocol = SocketClientAccessPolicyProtocol.Http; - } - else if(!String.IsNullOrEmpty(policy)) - { - _instance.logger().warning("Ignoring invalid Ice.ClientAccessPolicyProtocol value `" + policy + "'"); - } -#endif -#endif _mcastInterface = mcastInterface; _mcastTtl = mcastTtl; @@ -866,7 +702,6 @@ namespace IceInternal { _fd = Network.createSocket(true, _addr.AddressFamily); setBufSize(-1, -1); -#if !SILVERLIGHT Network.setBlock(_fd, false); if(Network.isMulticast((IPEndPoint)_addr)) { @@ -874,21 +709,7 @@ namespace IceInternal { Network.setMcastInterface(_fd, _mcastInterface, _addr.AddressFamily); } - if(AssemblyUtil.osx_) - { - // - // On Windows, we delay the join for the mcast group after the connection - // establishment succeeds. This is necessary for older Windows versions - // where joining the group fails if the socket isn't bound. See ICE-5113. - // - Network.setMcastGroup(_fd, ((IPEndPoint)_addr).Address, _mcastInterface); - if(_mcastTtl != -1) - { - Network.setMcastTtl(_fd, _mcastTtl, _addr.AddressFamily); - } - } } -#endif } catch(Ice.LocalException) { @@ -914,7 +735,6 @@ namespace IceInternal { _addr = Network.getAddressForServer(host, port, instance.protocolSupport(), instance.preferIPv6()); -#if ICE_SOCKET_ASYNC_API _readEventArgs = new SocketAsyncEventArgs(); _readEventArgs.RemoteEndPoint = _addr; _readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(ioCompleted); @@ -922,17 +742,13 @@ namespace IceInternal _writeEventArgs = new SocketAsyncEventArgs(); _writeEventArgs.RemoteEndPoint = _addr; _writeEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(ioCompleted); -#endif _fd = Network.createServerSocket(true, _addr.AddressFamily, instance.protocolSupport()); setBufSize(-1, -1); -#if !SILVERLIGHT Network.setBlock(_fd, false); -#endif } catch(Ice.LocalException) { -#if ICE_SOCKET_ASYNC_API if(_readEventArgs != null) { _readEventArgs.Dispose(); @@ -941,7 +757,6 @@ namespace IceInternal { _writeEventArgs.Dispose(); } -#endif _fd = null; throw; } @@ -987,7 +802,7 @@ namespace IceInternal // // Check for sanity. // - if(sizeRequested < (_udpOverhead + IceInternal.Protocol.headerSize)) + if(sizeRequested < (_udpOverhead + Protocol.headerSize)) { _instance.logger().warning("Invalid " + prop + " value of " + sizeRequested + " adjusted to " + dfltSize); @@ -1042,15 +857,12 @@ namespace IceInternal } } -#if ICE_SOCKET_ASYNC_API internal void ioCompleted(object sender, SocketAsyncEventArgs e) { switch (e.LastOperation) { case SocketAsyncOperation.Receive: -#if !SILVERLIGHT case SocketAsyncOperation.ReceiveFrom: -#endif _readCallback(e.UserToken); break; case SocketAsyncOperation.Send: @@ -1061,23 +873,6 @@ namespace IceInternal throw new ArgumentException("The last operation completed on the socket was not a receive or send"); } } -#else - internal void readCompleted(IAsyncResult result) - { - if(!result.CompletedSynchronously) - { - _readCallback(result.AsyncState); - } - } - - internal void writeCompleted(IAsyncResult result) - { - if(!result.CompletedSynchronously) - { - _writeCallback(result.AsyncState); - } - } -#endif private UdpEndpointI _endpoint; private ProtocolInstance _instance; @@ -1088,9 +883,7 @@ namespace IceInternal private Socket _fd; private EndPoint _addr; private EndPoint _sourceAddr; -#if !SILVERLIGHT private IPEndPoint _mcastAddr = null; -#endif private EndPoint _peerAddr = null; private string _mcastInterface = null; private int _mcastTtl = -1; @@ -1098,13 +891,8 @@ namespace IceInternal private int _port = 0; private bool _bound = false; -#if ICE_SOCKET_ASYNC_API private SocketAsyncEventArgs _writeEventArgs; private SocketAsyncEventArgs _readEventArgs; -#else - private IAsyncResult _writeResult; - private IAsyncResult _readResult; -#endif AsyncCallback _writeCallback; AsyncCallback _readCallback; diff --git a/csharp/src/Ice/UnknownSlicedObject.cs b/csharp/src/Ice/UnknownSlicedValue.cs index 3ef82aab51b..0d0d38c0264 100644 --- a/csharp/src/Ice/UnknownSlicedObject.cs +++ b/csharp/src/Ice/UnknownSlicedValue.cs @@ -1,6 +1,6 @@ // ********************************************************************** // -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. @@ -10,15 +10,15 @@ namespace Ice { /// <summary> - /// Unknown sliced object holds an instance of unknown type. + /// Unknown sliced value holds an instance of an unknown Slice class type. /// </summary> - public sealed class UnknownSlicedObject : ObjectImpl + public sealed class UnknownSlicedValue : Value { /// <summary> - /// Instantiates the class for an Ice object having the given Slice type. + /// Represents an instance of a Slice class type having the given Slice type. /// </summary> /// <param name="unknownTypeId">The Slice type ID of the unknown object.</param> - public UnknownSlicedObject(string unknownTypeId) + public UnknownSlicedValue(string unknownTypeId) { _unknownTypeId = unknownTypeId; } @@ -32,16 +32,16 @@ namespace Ice return _unknownTypeId; } - public override void write__(IceInternal.BasicStream os__) + public override void iceWrite(OutputStream ostr) { - os__.startWriteObject(_slicedData); - os__.endWriteObject(); + ostr.startValue(_slicedData); + ostr.endValue(); } - public override void read__(IceInternal.BasicStream is__) + public override void iceRead(InputStream istr) { - is__.startReadObject(); - _slicedData = is__.endReadObject(true); + istr.startValue(); + _slicedData = istr.endValue(true); } private string _unknownTypeId; diff --git a/csharp/src/Ice/UserExceptionFactory.cs b/csharp/src/Ice/UserExceptionFactory.cs deleted file mode 100644 index ec4af175671..00000000000 --- a/csharp/src/Ice/UserExceptionFactory.cs +++ /dev/null @@ -1,19 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -namespace IceInternal -{ - - public interface UserExceptionFactory - { - void createAndThrow(string typeId); - void destroy(); - } - -} diff --git a/csharp/src/Ice/Util.cs b/csharp/src/Ice/Util.cs index 4dc0df5cc13..74bbaec5d82 100644 --- a/csharp/src/Ice/Util.cs +++ b/csharp/src/Ice/Util.cs @@ -10,7 +10,6 @@ using System; using System.Threading; using System.Collections; -using System.Text; using System.Globalization; namespace Ice @@ -37,22 +36,11 @@ namespace Ice void stop(); } -#if COMPACT - /// <summary> - /// A delegate for an action taking no parameters. - /// </summary> - public delegate void VoidAction(); -#endif - /// <summary> /// A delegate for the dispatcher. The dispatcher is called by the Ice /// runtime to dispatch servant calls and AMI callbacks. /// </summary> -#if COMPACT - public delegate void Dispatcher(VoidAction call, Connection con); -#else public delegate void Dispatcher(System.Action call, Connection con); -#endif /// <summary> /// Applications that make use of compact type IDs to conserve space @@ -71,7 +59,7 @@ namespace Ice /// <summary> /// Creates and returns a copy of this object. /// </summary> - public System.Object Clone() + public object Clone() { // // A member-wise copy is safe because the members are immutable. @@ -92,7 +80,7 @@ namespace Ice /// <summary> /// The communicator observer used by the Ice run-time. /// </summary> - public Ice.Instrumentation.CommunicatorObserver observer; + public Instrumentation.CommunicatorObserver observer; /// <summary> /// The thread hook for the communicator. @@ -113,6 +101,11 @@ namespace Ice /// The batch request interceptor. /// </summary> public BatchRequestInterceptor batchRequestInterceptor; + + /// <summary> + /// The value factory manager. + /// </summary> + public ValueFactoryManager valueFactoryManager; } /// <summary> @@ -281,9 +274,9 @@ namespace Ice ident.category = ""; try { - ident.name = IceUtilInternal.StringUtil.unescapeString(s, 0, s.Length); + ident.name = IceUtilInternal.StringUtil.unescapeString(s, 0, s.Length, "/"); } - catch(System.ArgumentException e) + catch(ArgumentException e) { IdentityParseException ex = new IdentityParseException(); ex.str = "invalid identity name `" + s + "': " + e.Message; @@ -294,9 +287,9 @@ namespace Ice { try { - ident.category = IceUtilInternal.StringUtil.unescapeString(s, 0, slash); + ident.category = IceUtilInternal.StringUtil.unescapeString(s, 0, slash, "/"); } - catch(System.ArgumentException e) + catch(ArgumentException e) { IdentityParseException ex = new IdentityParseException(); ex.str = "invalid category in identity `" + s + "': " + e.Message; @@ -306,9 +299,9 @@ namespace Ice { try { - ident.name = IceUtilInternal.StringUtil.unescapeString(s, slash + 1, s.Length); + ident.name = IceUtilInternal.StringUtil.unescapeString(s, slash + 1, s.Length, "/"); } - catch(System.ArgumentException e) + catch(ArgumentException e) { IdentityParseException ex = new IdentityParseException(); ex.str = "invalid name in identity `" + s + "': " + e.Message; @@ -328,17 +321,18 @@ namespace Ice /// Converts an object identity to a string. /// </summary> /// <param name="ident">The object identity to convert.</param> + /// <param name="toStringMode">Specifies if and how non-printable ASCII characters are escaped in the result.</param> /// <returns>The string representation of the object identity.</returns> - public static string identityToString(Identity ident) + public static string identityToString(Identity ident, ToStringMode toStringMode = ToStringMode.Unicode) { if(ident.category == null || ident.category.Length == 0) { - return IceUtilInternal.StringUtil.escapeString(ident.name, "/"); + return IceUtilInternal.StringUtil.escapeString(ident.name, "/", toStringMode); } else { - return IceUtilInternal.StringUtil.escapeString(ident.category, "/") + '/' + - IceUtilInternal.StringUtil.escapeString(ident.name, "/"); + return IceUtilInternal.StringUtil.escapeString(ident.category, "/", toStringMode) + '/' + + IceUtilInternal.StringUtil.escapeString(ident.name, "/", toStringMode); } } @@ -447,79 +441,6 @@ namespace Ice } /// <summary> - /// Creates an input stream for dynamic invocation and dispatch. The stream uses - /// the communicator's default encoding version. The given data is copied. - /// </summary> - /// <param name="communicator">The communicator for the stream.</param> - /// <param name="bytes">An encoded request or reply.</param> - /// <returns>The input stream.</returns> - public static InputStream createInputStream(Communicator communicator, byte[] bytes) - { - return new InputStreamI(communicator, bytes, true); - } - - /// <summary> - /// Creates an input stream for dynamic invocation and dispatch. The stream uses - /// the given encoding version. - /// </summary> - /// <param name="communicator">The communicator for the stream.</param> - /// <param name="bytes">An encoded request or reply.</param> - /// <param name="v">The desired encoding version.</param> - /// <returns>The input stream.</returns> - public static InputStream createInputStream(Communicator communicator, byte[] bytes, EncodingVersion v) - { - return new InputStreamI(communicator, bytes, v, true); - } - - /// <summary> - /// Wraps encoded data with an input stream for dynamic invocation and dispatch. - /// The stream uses the communicator's default encoding version. - /// </summary> - /// <param name="communicator">The communicator for the stream.</param> - /// <param name="bytes">An encoded request or reply.</param> - /// <returns>The input stream.</returns> - public static InputStream wrapInputStream(Communicator communicator, byte[] bytes) - { - return new InputStreamI(communicator, bytes, false); - } - - /// <summary> - /// Wraps encoded data with an input stream for dynamic invocation and dispatch. - /// The stream uses the given encoding version. - /// </summary> - /// <param name="communicator">The communicator for the stream.</param> - /// <param name="bytes">An encoded request or reply.</param> - /// <param name="v">The desired encoding version.</param> - /// <returns>The input stream.</returns> - public static InputStream wrapInputStream(Communicator communicator, byte[] bytes, EncodingVersion v) - { - return new InputStreamI(communicator, bytes, v, false); - } - - /// <summary> - /// Creates an output stream for dynamic invocation and dispatch. The stream uses - /// the communicator's default encoding version. - /// </summary> - /// <param name="communicator">The communicator for the stream.</param> - /// <returns>The output stream.</returns> - public static OutputStream createOutputStream(Communicator communicator) - { - return new OutputStreamI(communicator); - } - - /// <summary> - /// Creates an output stream for dynamic invocation and dispatch. The stream uses - /// the given encoding version. - /// </summary> - /// <param name="communicator">The communicator for the stream.</param> - /// <param name="v">The desired encoding version.</param> - /// <returns>The output stream.</returns> - public static OutputStream createOutputStream(Communicator communicator, EncodingVersion v) - { - return new OutputStreamI(communicator, v); - } - - /// <summary> /// Returns the process-wide logger. /// </summary> /// <returns>The process-wide logger.</returns> @@ -529,7 +450,7 @@ namespace Ice { if(_processLogger == null) { - _processLogger = new ConsoleLoggerI(System.AppDomain.CurrentDomain.FriendlyName); + _processLogger = new ConsoleLoggerI(AppDomain.CurrentDomain.FriendlyName); } return _processLogger; } @@ -555,7 +476,7 @@ namespace Ice /// <returns>The Ice version.</returns> public static string stringVersion() { - return "3.6.3"; // "A.B.C", with A=major, B=minor, C=patch + return "3.7a4"; // "A.B.C", with A=major, B=minor, C=patch } /// <summary> @@ -566,7 +487,7 @@ namespace Ice /// <returns>The Ice version.</returns> public static int intVersion() { - return 30603; // AABBCC, with AA=major, BB=minor, CC=patch + return 30754; // AABBCC, with AA=major, BB=minor, CC=patch } /// <summary> @@ -574,11 +495,11 @@ namespace Ice /// </summary> /// <param name="version">The string to convert.</param> /// <returns>The converted protocol version.</returns> - public static Ice.ProtocolVersion stringToProtocolVersion(string version) + public static ProtocolVersion stringToProtocolVersion(string version) { byte major, minor; stringToMajorMinor(version, out major, out minor); - return new Ice.ProtocolVersion(major, minor); + return new ProtocolVersion(major, minor); } /// <summary> @@ -586,11 +507,11 @@ namespace Ice /// </summary> /// <param name="version">The string to convert.</param> /// <returns>The converted object identity.</returns> - public static Ice.EncodingVersion stringToEncodingVersion(string version) + public static EncodingVersion stringToEncodingVersion(string version) { byte major, minor; stringToMajorMinor(version, out major, out minor); - return new Ice.EncodingVersion(major, minor); + return new EncodingVersion(major, minor); } /// <summary> @@ -615,10 +536,10 @@ namespace Ice static private void stringToMajorMinor(string str, out byte major, out byte minor) { - int pos = str.IndexOf((System.Char) '.'); + int pos = str.IndexOf('.'); if(pos == -1) { - throw new Ice.VersionParseException("malformed version value `" + str + "'"); + throw new VersionParseException("malformed version value `" + str + "'"); } string majStr = str.Substring(0, (pos) - (0)); @@ -627,30 +548,26 @@ namespace Ice int minVersion; try { - majVersion = System.Int32.Parse(majStr, CultureInfo.InvariantCulture); - minVersion = System.Int32.Parse(minStr, CultureInfo.InvariantCulture); + majVersion = int.Parse(majStr, CultureInfo.InvariantCulture); + minVersion = int.Parse(minStr, CultureInfo.InvariantCulture); } - catch(System.FormatException) + catch(FormatException) { - throw new Ice.VersionParseException("invalid version value `" + str + "'"); + throw new VersionParseException("invalid version value `" + str + "'"); } if(majVersion < 1 || majVersion > 255 || minVersion < 0 || minVersion > 255) { - throw new Ice.VersionParseException("range error in version `" + str + "'"); + throw new VersionParseException("range error in version `" + str + "'"); } major = (byte)majVersion; minor = (byte)minVersion; } - static private String majorMinorToString(byte major, byte minor) + static private string majorMinorToString(byte major, byte minor) { - StringBuilder str = new StringBuilder(); - str.Append(major < 0 ? (int)major + 255 : (int)major); - str.Append("."); - str.Append(minor < 0 ? (int)minor + 255 : (int)minor); - return str.ToString(); + return string.Format("{0}.{1}", major, minor); } public static readonly ProtocolVersion currentProtocol = @@ -768,10 +685,9 @@ namespace IceInternal return new ProtocolPluginFacadeI(communicator); } -#if !SILVERLIGHT - public static System.Threading.ThreadPriority stringToThreadPriority(string s) + public static ThreadPriority stringToThreadPriority(string s) { - if(String.IsNullOrEmpty(s)) + if(string.IsNullOrEmpty(s)) { return ThreadPriority.Normal; } @@ -801,16 +717,5 @@ namespace IceInternal } return ThreadPriority.Normal; } -#endif - } -} - -#if SILVERLIGHT -namespace System -{ - public interface ICloneable - { - Object Clone(); } } -#endif diff --git a/csharp/src/Ice/Value.cs b/csharp/src/Ice/Value.cs new file mode 100644 index 00000000000..6eb5ad1acef --- /dev/null +++ b/csharp/src/Ice/Value.cs @@ -0,0 +1,119 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +using System; +using System.ComponentModel; + +namespace Ice +{ + [Serializable] + public abstract class Value : ICloneable + { + private const string _id = "::Ice::Object"; + + /// <summary> + /// Returns the Slice type ID of the interface supported by this object. + /// </summary> + /// <returns>The return value is always ::Ice::Object.</returns> + public static string ice_staticId() + { + return _id; + } + + /// <summary> + /// Returns the Slice type ID of the most-derived interface supported by this object. + /// </summary> + /// <returns>The return value is always ::Ice::Object.</returns> + public virtual string ice_id() + { + return _id; + } + + /// <summary> + /// The Ice run time invokes this method prior to marshaling an object's data members. This allows a subclass + /// to override this method in order to validate its data members. + /// </summary> + public virtual void ice_preMarshal() + { + } + + /// <summary> + /// This Ice run time invokes this method vafter unmarshaling an object's data members. This allows a + /// subclass to override this method in order to perform additional initialization. + /// </summary> + public virtual void ice_postUnmarshal() + { + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual void iceWrite(OutputStream ostr) + { + ostr.startValue(null); + iceWriteImpl(ostr); + ostr.endValue(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual void iceRead(InputStream istr) + { + istr.startValue(); + iceReadImpl(istr); + istr.endValue(false); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected virtual void iceWriteImpl(OutputStream ostr) + { + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected virtual void iceReadImpl(InputStream istr) + { + } + + /// <summary> + /// Returns a copy of the object. The cloned object contains field-for-field copies + /// of the state. + /// </summary> + /// <returns>The cloned object.</returns> + public object Clone() + { + return MemberwiseClone(); + } + } + + public class InterfaceByValue : Value + { + public InterfaceByValue(string id) + { + _id = id; + } + + public override string ice_id() + { + return _id; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected override void iceWriteImpl(OutputStream ostr) + { + ostr.startSlice(ice_id(), -1, true); + ostr.endSlice(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected override void iceReadImpl(InputStream istr) + { + istr.startSlice(); + istr.endSlice(); + } + + private string _id; + } +} diff --git a/csharp/src/Ice/ValueFactoryManager.cs b/csharp/src/Ice/ValueFactoryManager.cs new file mode 100644 index 00000000000..c4c7075d9ef --- /dev/null +++ b/csharp/src/Ice/ValueFactoryManager.cs @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +namespace IceInternal +{ + + using System.Collections.Generic; + + public sealed class ValueFactoryManagerI : Ice.ValueFactoryManager + { + public void add(Ice.ValueFactory factory, string id) + { + lock(this) + { + if(_factoryMap.ContainsKey(id)) + { + Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); + ex.id = id; + ex.kindOfObject = "value factory"; + throw ex; + } + _factoryMap[id] = factory; + } + } + + public Ice.ValueFactory find(string id) + { + lock(this) + { + Ice.ValueFactory factory = null; + _factoryMap.TryGetValue(id, out factory); + return factory; + } + } + + private Dictionary<string, Ice.ValueFactory> _factoryMap = new Dictionary<string, Ice.ValueFactory>(); + } + +} diff --git a/csharp/src/Ice/ValueWriter.cs b/csharp/src/Ice/ValueWriter.cs index ead5bafcd40..936a68c5d3f 100644 --- a/csharp/src/Ice/ValueWriter.cs +++ b/csharp/src/Ice/ValueWriter.cs @@ -9,7 +9,6 @@ namespace IceInternal { - using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -71,7 +70,7 @@ namespace IceInternal { writeName(name, output); Ice.ObjectPrxHelperBase proxy = (Ice.ObjectPrxHelperBase)val; - output.print(proxy.reference__().ToString()); + output.print(proxy.iceReference().ToString()); } else if(val is Ice.Object) { diff --git a/csharp/src/Ice/WSAcceptor.cs b/csharp/src/Ice/WSAcceptor.cs index 4a77bcf97d3..45e96c27045 100644 --- a/csharp/src/Ice/WSAcceptor.cs +++ b/csharp/src/Ice/WSAcceptor.cs @@ -9,8 +9,6 @@ namespace IceInternal { - using System.Diagnostics; - class WSAcceptor : Acceptor { public void close() diff --git a/csharp/src/Ice/WSConnector.cs b/csharp/src/Ice/WSConnector.cs index 74567c578b3..d106d5fe87c 100644 --- a/csharp/src/Ice/WSConnector.cs +++ b/csharp/src/Ice/WSConnector.cs @@ -13,7 +13,7 @@ namespace IceInternal { public IceInternal.Transceiver connect() { - return new WSTransceiver(_instance, _delegate.connect(), _host, _port, _resource); + return new WSTransceiver(_instance, _delegate.connect(), _host, _resource); } public short type() @@ -21,12 +21,11 @@ namespace IceInternal return _delegate.type(); } - internal WSConnector(ProtocolInstance instance, IceInternal.Connector del, string host, int port, string resource) + internal WSConnector(ProtocolInstance instance, IceInternal.Connector del, string host, string resource) { _instance = instance; _delegate = del; _host = host; - _port = port; _resource = resource; } @@ -67,9 +66,8 @@ namespace IceInternal } private ProtocolInstance _instance; - private IceInternal.Connector _delegate; + private Connector _delegate; private string _host; - private int _port; private string _resource; } } diff --git a/csharp/src/Ice/WSEndpoint.cs b/csharp/src/Ice/WSEndpoint.cs index dcdcf5f6023..d4e1e044732 100644 --- a/csharp/src/Ice/WSEndpoint.cs +++ b/csharp/src/Ice/WSEndpoint.cs @@ -12,30 +12,20 @@ namespace IceInternal using System; using System.Diagnostics; using System.Collections.Generic; - using System.Globalization; - - // - // Delegate interface implemented by TcpEndpoint or IceSSL.EndpointI or any endpoint that WS can - // delegate to. - // - public interface WSEndpointDelegate - { - Ice.EndpointInfo getWSInfo(string resource); - }; sealed class WSEndpoint : EndpointI { internal WSEndpoint(ProtocolInstance instance, EndpointI del, string res) { _instance = instance; - _delegate = (IPEndpointI)del; + _delegate = del; _resource = res; } internal WSEndpoint(ProtocolInstance instance, EndpointI del, List<string> args) { _instance = instance; - _delegate = (IPEndpointI)del; + _delegate = del; initWithOptions(args); @@ -45,10 +35,10 @@ namespace IceInternal } } - internal WSEndpoint(ProtocolInstance instance, EndpointI del, BasicStream s) + internal WSEndpoint(ProtocolInstance instance, EndpointI del, Ice.InputStream s) { _instance = instance; - _delegate = (IPEndpointI)del; + _delegate = del; _resource = s.readString(); } @@ -80,8 +70,12 @@ namespace IceInternal public override Ice.EndpointInfo getInfo() { - Debug.Assert(_delegate is WSEndpointDelegate); - return ((WSEndpointDelegate)_delegate).getWSInfo(_resource); + Ice.WSEndpointInfo info = new InfoI(this); + info.underlying = _delegate.getInfo(); + info.resource = _resource; + info.compress = info.underlying.compress; + info.timeout = info.underlying.timeout; + return info; } public override short type() @@ -94,12 +88,10 @@ namespace IceInternal return _delegate.protocol(); } - public override void streamWrite(BasicStream s) + public override void streamWriteImpl(Ice.OutputStream s) { - s.startWriteEncaps(); _delegate.streamWriteImpl(s); s.writeString(_resource); - s.endWriteEncaps(); } public override int timeout() @@ -170,13 +162,11 @@ namespace IceInternal private sealed class EndpointI_connectorsI : EndpointI_connectors { - public EndpointI_connectorsI(ProtocolInstance instance, string host, int port, string resource, - EndpointI_connectors cb) + public EndpointI_connectorsI(ProtocolInstance instance, string host, string res, EndpointI_connectors cb) { _instance = instance; _host = host; - _port = port; - _resource = resource; + _resource = res; _callback = cb; } @@ -185,7 +175,7 @@ namespace IceInternal List<Connector> l = new List<Connector>(); foreach(Connector c in connectors) { - l.Add(new WSConnector(_instance, c, _host, _port, _resource)); + l.Add(new WSConnector(_instance, c, _host, _resource)); } _callback.connectors(l); } @@ -197,23 +187,27 @@ namespace IceInternal private ProtocolInstance _instance; private string _host; - private int _port; private string _resource; private EndpointI_connectors _callback; } - public override void connectors_async(Ice.EndpointSelectionType selType, - EndpointI_connectors callback) + public override void connectors_async(Ice.EndpointSelectionType selType, EndpointI_connectors callback) { - EndpointI_connectorsI cb = - new EndpointI_connectorsI(_instance, _delegate.host(), _delegate.port(), _resource, callback); - _delegate.connectors_async(selType, cb); + string host = ""; + for(Ice.EndpointInfo p = _delegate.getInfo(); p != null; p = p.underlying) + { + if(p is Ice.IPEndpointInfo) + { + Ice.IPEndpointInfo ipInfo = (Ice.IPEndpointInfo)p; + host = ipInfo.host + ":" + ipInfo.port; + } + } + _delegate.connectors_async(selType, new EndpointI_connectorsI(_instance, host, _resource, callback)); } public override Acceptor acceptor(string adapterName) { - Acceptor delAcc = _delegate.acceptor(adapterName); - return new WSAcceptor(this, _instance, delAcc); + return new WSAcceptor(this, _instance, _delegate.acceptor(adapterName)); } public WSEndpoint endpoint(EndpointI delEndp) @@ -300,11 +294,6 @@ namespace IceInternal return _delegate.CompareTo(p._delegate); } - public EndpointI getDelegate() - { - return _delegate; - } - protected override bool checkOption(string option, string argument, string endpoint) { switch(option[1]) @@ -329,7 +318,7 @@ namespace IceInternal } private ProtocolInstance _instance; - private IPEndpointI _delegate; + private EndpointI _delegate; private string _resource; } @@ -356,7 +345,7 @@ namespace IceInternal return new WSEndpoint(_instance, _delegate.create(args, oaEndpoint), args); } - public EndpointI read(BasicStream s) + public EndpointI read(Ice.InputStream s) { return new WSEndpoint(_instance, _delegate.read(s), s); } @@ -367,10 +356,9 @@ namespace IceInternal _instance = null; } - public EndpointFactory clone(ProtocolInstance instance) + public EndpointFactory clone(ProtocolInstance instance, EndpointFactory del) { - Debug.Assert(false); // We don't support cloning this transport. - return null; + return new WSEndpointFactory(instance, del); } private ProtocolInstance _instance; diff --git a/csharp/src/Ice/WSTransceiver.cs b/csharp/src/Ice/WSTransceiver.cs index 11fddee4c6b..b5b4716b9cb 100644 --- a/csharp/src/Ice/WSTransceiver.cs +++ b/csharp/src/Ice/WSTransceiver.cs @@ -11,20 +11,10 @@ namespace IceInternal { using System; using System.Diagnostics; - using System.Collections.Generic; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; - // - // Delegate interface implemented by TcpTransceiver or IceSSL.TransceiverI or any endpoint that WS can - // delegate to. - // - public interface WSTransceiverDelegate - { - Ice.ConnectionInfo getWSInfo(Dictionary<string, string> headers); - }; - sealed class WSTransceiver : Transceiver { public Socket fd() @@ -70,9 +60,7 @@ namespace IceInternal // StringBuilder @out = new StringBuilder(); @out.Append("GET " + _resource + " HTTP/1.1\r\n"); - @out.Append("Host: " + _host + ":"); - @out.Append(_port); - @out.Append("\r\n"); + @out.Append("Host: " + _host + "\r\n"); @out.Append("Upgrade: websocket\r\n"); @out.Append("Connection: Upgrade\r\n"); @out.Append("Sec-WebSocket-Protocol: " + _iceProtocol + "\r\n"); @@ -85,7 +73,7 @@ namespace IceInternal // byte[] key = new byte[16]; _rand.NextBytes(key); - _key = IceUtilInternal.Base64.encode(key); + _key = System.Convert.ToBase64String(key); @out.Append(_key + "\r\n\r\n"); // EOM byte[] bytes = _utf8.GetBytes(@out.ToString()); @@ -665,8 +653,10 @@ namespace IceInternal public Ice.ConnectionInfo getInfo() { - Debug.Assert(_delegate is WSTransceiverDelegate); - return ((WSTransceiverDelegate)_delegate).getWSInfo(_parser.getHeaders()); + Ice.WSConnectionInfo info = new Ice.WSConnectionInfo(); + info.headers = _parser.getHeaders(); + info.underlying = _delegate.getInfo(); + return info; } public void checkSendSize(Buffer buf) @@ -690,11 +680,10 @@ namespace IceInternal } internal - WSTransceiver(ProtocolInstance instance, Transceiver del, string host, int port, string resource) + WSTransceiver(ProtocolInstance instance, Transceiver del, string host, string resource) { init(instance, del); _host = host; - _port = port; _resource = resource; _incoming = false; @@ -718,7 +707,6 @@ namespace IceInternal { init(instance, del); _host = ""; - _port = -1; _resource = ""; _incoming = true; @@ -840,7 +828,7 @@ namespace IceInternal throw new WebSocketException("missing value for WebSocket key"); } - byte[] decodedKey = IceUtilInternal.Base64.decode(key); + byte[] decodedKey = Convert.FromBase64String(key); if(decodedKey.Length != 16) { throw new WebSocketException("invalid value `" + key + "' for WebSocket key"); @@ -875,13 +863,8 @@ namespace IceInternal // @out.Append("Sec-WebSocket-Accept: "); string input = key + _wsUUID; -#if SILVERLIGHT - SHA1Managed sha1 = new SHA1Managed(); - byte[] hash = sha1.ComputeHash(_utf8.GetBytes(input)); -#else byte[] hash = SHA1.Create().ComputeHash(_utf8.GetBytes(input)); -#endif - @out.Append(IceUtilInternal.Base64.encode(hash) + "\r\n" + "\r\n"); // EOM + @out.Append(Convert.ToBase64String(hash) + "\r\n" + "\r\n"); // EOM byte[] bytes = _utf8.GetBytes(@out.ToString()); Debug.Assert(bytes.Length == @out.Length); @@ -982,13 +965,8 @@ namespace IceInternal } string input = _key + _wsUUID; -#if SILVERLIGHT - SHA1Managed sha1 = new SHA1Managed(); - byte[] hash = sha1.ComputeHash(_utf8.GetBytes(input)); -#else byte[] hash = SHA1.Create().ComputeHash(_utf8.GetBytes(input)); -#endif - if(!val.Equals(IceUtilInternal.Base64.encode(hash))) + if(!val.Equals(Convert.ToBase64String(hash))) { throw new WebSocketException("invalid value `" + val + "' for Sec-WebSocket-Accept"); } @@ -1602,7 +1580,7 @@ namespace IceInternal // // Use an extra 16 bits to encode the payload length. // - _writeBuffer.b.put((byte)126); + _writeBuffer.b.put(126); _writeBuffer.b.putShort((short)payloadLength); } else if(payloadLength > 65535) @@ -1610,7 +1588,7 @@ namespace IceInternal // // Use an extra 64 bits to encode the payload length. // - _writeBuffer.b.put((byte)127); + _writeBuffer.b.put(127); _writeBuffer.b.putLong(payloadLength); } @@ -1629,7 +1607,6 @@ namespace IceInternal private ProtocolInstance _instance; private Transceiver _delegate; private string _host; - private int _port; private string _resource; private bool _incoming; @@ -1720,6 +1697,6 @@ namespace IceInternal private const string _iceProtocol = "ice.zeroc.com"; private const string _wsUUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - private static System.Text.UTF8Encoding _utf8 = new System.Text.UTF8Encoding(false, true); + private static UTF8Encoding _utf8 = new UTF8Encoding(false, true); } } diff --git a/csharp/src/Ice/generated/.gitignore b/csharp/src/Ice/generated/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/csharp/src/Ice/generated/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/csharp/src/Ice/msbuild/ice.csproj b/csharp/src/Ice/msbuild/ice.csproj new file mode 100644 index 00000000000..ed21534e3fc --- /dev/null +++ b/csharp/src/Ice/msbuild/ice.csproj @@ -0,0 +1,474 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{7CB4715E-DD8B-48F8-B478-27B8BD4008C7}</ProjectGuid> + <OutputType>Library</OutputType> + <AssemblyName>Ice</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\Assemblies\Ice.XML</DocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\Acceptor.cs"> + <Link>Acceptor.cs</Link> + </Compile> + <Compile Include="..\ACM.cs"> + <Link>ACM.cs</Link> + </Compile> + <Compile Include="..\Application.cs"> + <Link>Application.cs</Link> + </Compile> + <Compile Include="..\Arrays.cs"> + <Link>Arrays.cs</Link> + </Compile> + <Compile Include="..\AssemblyInfo.cs"> + <Link>AssemblyInfo.cs</Link> + </Compile> + <Compile Include="..\AssemblyUtil.cs"> + <Link>AssemblyUtil.cs</Link> + </Compile> + <Compile Include="..\AsyncIOThread.cs"> + <Link>AsyncIOThread.cs</Link> + </Compile> + <Compile Include="..\AsyncResult.cs"> + <Link>AsyncResult.cs</Link> + </Compile> + <Compile Include="..\BatchRequestInterceptor.cs"> + <Link>BatchRequestInterceptor.cs</Link> + </Compile> + <Compile Include="..\BatchRequestQueue.cs"> + <Link>BatchRequestQueue.cs</Link> + </Compile> + <Compile Include="..\Buffer.cs"> + <Link>Buffer.cs</Link> + </Compile> + <Compile Include="..\ByteBuffer.cs"> + <Link>ByteBuffer.cs</Link> + </Compile> + <Compile Include="..\BZip2.cs"> + <Link>BZip2.cs</Link> + </Compile> + <Compile Include="..\Collections.cs"> + <Link>Collections.cs</Link> + </Compile> + <Compile Include="..\CollocatedRequestHandler.cs"> + <Link>CollocatedRequestHandler.cs</Link> + </Compile> + <Compile Include="..\CommunicatorI.cs"> + <Link>CommunicatorI.cs</Link> + </Compile> + <Compile Include="..\Compare.cs"> + <Link>Compare.cs</Link> + </Compile> + <Compile Include="..\ConnectionFactory.cs"> + <Link>ConnectionFactory.cs</Link> + </Compile> + <Compile Include="..\ConnectionI.cs"> + <Link>ConnectionI.cs</Link> + </Compile> + <Compile Include="..\ConnectionRequestHandler.cs"> + <Link>ConnectionRequestHandler.cs</Link> + </Compile> + <Compile Include="..\Connector.cs"> + <Link>Connector.cs</Link> + </Compile> + <Compile Include="..\ConnectRequestHandler.cs"> + <Link>ConnectRequestHandler.cs</Link> + </Compile> + <Compile Include="..\DefaultsAndOverrides.cs"> + <Link>DefaultsAndOverrides.cs</Link> + </Compile> + <Compile Include="..\DispatchInterceptor.cs"> + <Link>DispatchInterceptor.cs</Link> + </Compile> + <Compile Include="..\EndpointFactory.cs"> + <Link>EndpointFactory.cs</Link> + </Compile> + <Compile Include="..\EndpointFactoryManager.cs"> + <Link>EndpointFactoryManager.cs</Link> + </Compile> + <Compile Include="..\EndpointHostResolver.cs"> + <Link>EndpointHostResolver.cs</Link> + </Compile> + <Compile Include="..\EndpointI.cs"> + <Link>EndpointI.cs</Link> + </Compile> + <Compile Include="..\EventHandler.cs"> + <Link>EventHandler.cs</Link> + </Compile> + <Compile Include="..\Exception.cs"> + <Link>Exception.cs</Link> + </Compile> + <Compile Include="..\FormatType.cs"> + <Link>FormatType.cs</Link> + </Compile> + <Compile Include="..\HttpParser.cs"> + <Link>HttpParser.cs</Link> + </Compile> + <Compile Include="..\ImplicitContextI.cs"> + <Link>ImplicitContextI.cs</Link> + </Compile> + <Compile Include="..\Incoming.cs"> + <Link>Incoming.cs</Link> + </Compile> + <Compile Include="..\InputStream.cs"> + <Link>InputStream.cs</Link> + </Compile> + <Compile Include="..\Instance.cs"> + <Link>Instance.cs</Link> + </Compile> + <Compile Include="..\InstrumentationI.cs"> + <Link>InstrumentationI.cs</Link> + </Compile> + <Compile Include="..\IPEndpointI.cs"> + <Link>IPEndpointI.cs</Link> + </Compile> + <Compile Include="..\LocatorInfo.cs"> + <Link>LocatorInfo.cs</Link> + </Compile> + <Compile Include="..\LoggerAdminI.cs"> + <Link>LoggerAdminI.cs</Link> + </Compile> + <Compile Include="..\LoggerAdminLoggerI.cs"> + <Link>LoggerAdminLoggerI.cs</Link> + </Compile> + <Compile Include="..\LoggerI.cs"> + <Link>LoggerI.cs</Link> + </Compile> + <Compile Include="..\LoggerPlugin.cs"> + <Link>LoggerPlugin.cs</Link> + </Compile> + <Compile Include="..\MetricsAdminI.cs"> + <Link>MetricsAdminI.cs</Link> + </Compile> + <Compile Include="..\MetricsObserverI.cs"> + <Link>MetricsObserverI.cs</Link> + </Compile> + <Compile Include="..\Network.cs"> + <Link>Network.cs</Link> + </Compile> + <Compile Include="..\NetworkProxy.cs"> + <Link>NetworkProxy.cs</Link> + </Compile> + <Compile Include="..\Object.cs"> + <Link>Object.cs</Link> + </Compile> + <Compile Include="..\ObjectAdapterFactory.cs"> + <Link>ObjectAdapterFactory.cs</Link> + </Compile> + <Compile Include="..\ObjectAdapterI.cs"> + <Link>ObjectAdapterI.cs</Link> + </Compile> + <Compile Include="..\ObserverHelper.cs"> + <Link>ObserverHelper.cs</Link> + </Compile> + <Compile Include="..\OpaqueEndpointI.cs"> + <Link>OpaqueEndpointI.cs</Link> + </Compile> + <Compile Include="..\Optional.cs"> + <Link>Optional.cs</Link> + </Compile> + <Compile Include="..\Options.cs"> + <Link>Options.cs</Link> + </Compile> + <Compile Include="..\OutgoingAsync.cs"> + <Link>OutgoingAsync.cs</Link> + </Compile> + <Compile Include="..\OutputBase.cs"> + <Link>OutputBase.cs</Link> + </Compile> + <Compile Include="..\OutputStream.cs"> + <Link>OutputStream.cs</Link> + </Compile> + <Compile Include="..\Patcher.cs"> + <Link>Patcher.cs</Link> + </Compile> + <Compile Include="..\PluginManagerI.cs"> + <Link>PluginManagerI.cs</Link> + </Compile> + <Compile Include="..\ProcessI.cs"> + <Link>ProcessI.cs</Link> + </Compile> + <Compile Include="..\PropertiesAdminI.cs"> + <Link>PropertiesAdminI.cs</Link> + </Compile> + <Compile Include="..\PropertiesI.cs"> + <Link>PropertiesI.cs</Link> + </Compile> + <Compile Include="..\Property.cs"> + <Link>Property.cs</Link> + </Compile> + <Compile Include="..\PropertyNames.cs"> + <Link>PropertyNames.cs</Link> + </Compile> + <Compile Include="..\Protocol.cs"> + <Link>Protocol.cs</Link> + </Compile> + <Compile Include="..\ProtocolInstance.cs"> + <Link>ProtocolInstance.cs</Link> + </Compile> + <Compile Include="..\ProtocolPluginFacade.cs"> + <Link>ProtocolPluginFacade.cs</Link> + </Compile> + <Compile Include="..\Proxy.cs"> + <Link>Proxy.cs</Link> + </Compile> + <Compile Include="..\ProxyFactory.cs"> + <Link>ProxyFactory.cs</Link> + </Compile> + <Compile Include="..\ProxyIdentityKey.cs"> + <Link>ProxyIdentityKey.cs</Link> + </Compile> + <Compile Include="..\Reference.cs"> + <Link>Reference.cs</Link> + </Compile> + <Compile Include="..\ReferenceFactory.cs"> + <Link>ReferenceFactory.cs</Link> + </Compile> + <Compile Include="..\ReplyStatus.cs"> + <Link>ReplyStatus.cs</Link> + </Compile> + <Compile Include="..\RequestHandler.cs"> + <Link>RequestHandler.cs</Link> + </Compile> + <Compile Include="..\RequestHandlerFactory.cs"> + <Link>RequestHandlerFactory.cs</Link> + </Compile> + <Compile Include="..\ResponseHandler.cs"> + <Link>ResponseHandler.cs</Link> + </Compile> + <Compile Include="..\RetryQueue.cs"> + <Link>RetryQueue.cs</Link> + </Compile> + <Compile Include="..\RouterInfo.cs"> + <Link>RouterInfo.cs</Link> + </Compile> + <Compile Include="..\ServantManager.cs"> + <Link>ServantManager.cs</Link> + </Compile> + <Compile Include="..\SliceChecksums.cs"> + <Link>SliceChecksums.cs</Link> + </Compile> + <Compile Include="..\SlicedData.cs"> + <Link>SlicedData.cs</Link> + </Compile> + <Compile Include="..\SocketOperation.cs"> + <Link>SocketOperation.cs</Link> + </Compile> + <Compile Include="..\StreamSocket.cs"> + <Link>StreamSocket.cs</Link> + </Compile> + <Compile Include="..\StreamWrapper.cs"> + <Link>StreamWrapper.cs</Link> + </Compile> + <Compile Include="..\StringUtil.cs"> + <Link>StringUtil.cs</Link> + </Compile> + <Compile Include="..\TcpAcceptor.cs"> + <Link>TcpAcceptor.cs</Link> + </Compile> + <Compile Include="..\TcpConnector.cs"> + <Link>TcpConnector.cs</Link> + </Compile> + <Compile Include="..\TcpEndpointI.cs"> + <Link>TcpEndpointI.cs</Link> + </Compile> + <Compile Include="..\TcpTransceiver.cs"> + <Link>TcpTransceiver.cs</Link> + </Compile> + <Compile Include="..\ThreadHookPlugin.cs"> + <Link>ThreadHookPlugin.cs</Link> + </Compile> + <Compile Include="..\ThreadPool.cs"> + <Link>ThreadPool.cs</Link> + </Compile> + <Compile Include="..\TieBase.cs"> + <Link>TieBase.cs</Link> + </Compile> + <Compile Include="..\Time.cs"> + <Link>Time.cs</Link> + </Compile> + <Compile Include="..\Timer.cs"> + <Link>Timer.cs</Link> + </Compile> + <Compile Include="..\TraceLevels.cs"> + <Link>TraceLevels.cs</Link> + </Compile> + <Compile Include="..\TraceUtil.cs"> + <Link>TraceUtil.cs</Link> + </Compile> + <Compile Include="..\Transceiver.cs"> + <Link>Transceiver.cs</Link> + </Compile> + <Compile Include="..\UdpConnector.cs"> + <Link>UdpConnector.cs</Link> + </Compile> + <Compile Include="..\UdpEndpointI.cs"> + <Link>UdpEndpointI.cs</Link> + </Compile> + <Compile Include="..\UdpTransceiver.cs"> + <Link>UdpTransceiver.cs</Link> + </Compile> + <Compile Include="..\UnknownSlicedValue.cs"> + <Link>UnknownSlicedValue.cs</Link> + </Compile> + <Compile Include="..\Util.cs"> + <Link>Util.cs</Link> + </Compile> + <Compile Include="..\Value.cs"> + <Link>Value.cs</Link> + </Compile> + <Compile Include="..\ValueFactoryManager.cs"> + <Link>ValueFactoryManager.cs</Link> + </Compile> + <Compile Include="..\ValueWriter.cs"> + <Link>ValueWriter.cs</Link> + </Compile> + <Compile Include="..\WSAcceptor.cs"> + <Link>WSAcceptor.cs</Link> + </Compile> + <Compile Include="..\WSConnector.cs"> + <Link>WSConnector.cs</Link> + </Compile> + <Compile Include="..\WSEndpoint.cs"> + <Link>WSEndpoint.cs</Link> + </Compile> + <Compile Include="..\WSTransceiver.cs"> + <Link>WSTransceiver.cs</Link> + </Compile> + <Compile Include="generated\BuiltinSequences.cs" /> + <Compile Include="generated\Communicator.cs" /> + <Compile Include="generated\Connection.cs" /> + <Compile Include="generated\Current.cs" /> + <Compile Include="generated\Endpoint.cs" /> + <Compile Include="generated\EndpointTypes.cs" /> + <Compile Include="generated\FacetMap.cs" /> + <Compile Include="generated\Identity.cs" /> + <Compile Include="generated\ImplicitContext.cs" /> + <Compile Include="generated\Instrumentation.cs" /> + <Compile Include="generated\LocalException.cs" /> + <Compile Include="generated\Locator.cs" /> + <Compile Include="generated\Logger.cs" /> + <Compile Include="generated\Metrics.cs" /> + <Compile Include="generated\ObjectAdapter.cs" /> + <Compile Include="generated\ObjectFactory.cs" /> + <Compile Include="generated\Plugin.cs" /> + <Compile Include="generated\Process.cs" /> + <Compile Include="generated\Properties.cs" /> + <Compile Include="generated\PropertiesAdmin.cs" /> + <Compile Include="generated\RemoteLogger.cs" /> + <Compile Include="generated\Router.cs" /> + <Compile Include="generated\ServantLocator.cs" /> + <Compile Include="generated\SliceChecksumDict.cs" /> + <Compile Include="generated\ValueFactory.cs" /> + <Compile Include="generated\Version.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\slice\Ice\BuiltinSequences.ice"> + <Link>BuiltinSequences.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Communicator.ice"> + <Link>Communicator.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Connection.ice"> + <Link>Connection.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Current.ice"> + <Link>Current.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Endpoint.ice"> + <Link>Endpoint.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\EndpointTypes.ice"> + <Link>EndpointTypes.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\FacetMap.ice"> + <Link>FacetMap.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Identity.ice"> + <Link>Identity.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\ImplicitContext.ice"> + <Link>ImplicitContext.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Instrumentation.ice"> + <Link>Instrumentation.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\LocalException.ice"> + <Link>LocalException.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Locator.ice"> + <Link>Locator.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Logger.ice"> + <Link>Logger.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Metrics.ice"> + <Link>Metrics.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\ObjectAdapter.ice"> + <Link>ObjectAdapter.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\ObjectFactory.ice"> + <Link>ObjectFactory.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Plugin.ice"> + <Link>Plugin.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Process.ice"> + <Link>Process.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Properties.ice"> + <Link>Properties.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\PropertiesAdmin.ice"> + <Link>PropertiesAdmin.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\RemoteLogger.ice"> + <Link>RemoteLogger.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Router.ice"> + <Link>Router.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\ServantLocator.ice"> + <Link>ServantLocator.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\SliceChecksumDict.ice"> + <Link>SliceChecksumDict.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\ValueFactory.ice"> + <Link>ValueFactory.ice</Link> + </None> + <None Include="..\..\..\..\slice\Ice\Version.ice"> + <Link>Version.ice</Link> + </None> + </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\config\ice.sign.targets" /> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/IceBox/.depend.mak b/csharp/src/IceBox/.depend.mak deleted file mode 100644 index bf680c6be59..00000000000 --- a/csharp/src/IceBox/.depend.mak +++ /dev/null @@ -1,7 +0,0 @@ - -IceBox.cs: \ - "$(slicedir)\IceBox\IceBox.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/CommunicatorF.ice" \ - "$(slicedir)/Ice/PropertiesF.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" diff --git a/csharp/src/IceBox/AssemblyInfo.cs b/csharp/src/IceBox/AssemblyInfo.cs index ff125c90516..81c50baf613 100644 --- a/csharp/src/IceBox/AssemblyInfo.cs +++ b/csharp/src/IceBox/AssemblyInfo.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/IceBox/AssemblyInfoExe.cs b/csharp/src/IceBox/AssemblyInfoExe.cs index e2f821faff1..c8875f20986 100644 --- a/csharp/src/IceBox/AssemblyInfoExe.cs +++ b/csharp/src/IceBox/AssemblyInfoExe.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/IceBox/Makefile b/csharp/src/IceBox/Makefile deleted file mode 100644 index f4cfe4e4634..00000000000 --- a/csharp/src/IceBox/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -PKG = IceBox -LIBNAME = $(PKG).dll -ICEBOXNET = $(bindir)/iceboxnet.exe -TARGETS = $(ICEBOXNET) $(assembliesdir)/$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -L_SRCS = AssemblyInfo.cs -I_SRCS = AssemblyInfoExe.cs Server.cs ServiceManagerI.cs - -SLICE_SRCS = $(SDIR)/IceBox.ice - -SDIR = $(slicedir)/IceBox -GDIR = generated - -include $(top_srcdir)/config/Make.rules.cs - -EXE_MCSFLAGS := $(MCSFLAGS) -target:exe - -LIB_MCSFLAGS := $(MCSFLAGS) -target:library -out:$(assembliesdir)/$(LIBNAME) -LIB_MCSFLAGS := $(LIB_MCSFLAGS) -keyfile:$(KEYFILE) -LIB_MCSFLAGS := $(LIB_MCSFLAGS) /doc:$(assembliesdir)/$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS := $(SLICE2CSFLAGS) --checksum --ice -I. -I$(slicedir) - -$(ICEBOXNET): $(I_SRCS) $(assembliesdir)/$(LIBNAME) - $(MCS) $(EXE_MCSFLAGS) -out:$@ $(call ref,$(PKG)) $(call ref,Ice) $(I_SRCS) - -$(assembliesdir)/$(LIBNAME): $(L_SRCS) $(GEN_SRCS) - $(MCS) $(LIB_MCSFLAGS) $(call ref,Ice) $(subst /,$(DSEP),$^) - -install:: all - (cd $(assembliesdir); $(call installassembly,$(LIBNAME),$(PKG)); $(call installpolicy,$(POLICY)); \ - $(call installmdb,$(LIBNAME).mdb); \ - $(call installdata,$(PKG).xml,$(DESTDIR)$(install_assembliesdir))) - -install:: all - $(call installprogram,$(ICEBOXNET),$(DESTDIR)$(install_bindir)) - $(call installdata,$(top_srcdir)/../man/man1/iceboxnet.1,$(DESTDIR)$(install_mandir)) - $(call installmdb,$(ICEBOXNET).mdb) - -ifeq ($(GACINSTALL),yes) -install:: all - $(call installdata,../../lib/pkgconfig/$(PKG).pc,$(DESTDIR)$(install_pkgconfigdir)) -endif - -clean:: - -rm -f $(assembliesdir)/$(PKG).xml diff --git a/csharp/src/IceBox/Makefile.mak b/csharp/src/IceBox/Makefile.mak deleted file mode 100644 index 1509aa3b253..00000000000 --- a/csharp/src/IceBox/Makefile.mak +++ /dev/null @@ -1,115 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -PKG = IceBox -LIBNAME = $(assembliesdir)\$(PKG).dll -ICEBOXNET = $(bindir)\iceboxnet.exe -TARGETS = $(LIBNAME) $(ICEBOXNET) -POLICY_TARGET = $(POLICY).dll - -L_SRCS = AssemblyInfo.cs -I_SRCS = AssemblyInfoExe.cs Server.cs ServiceManagerI.cs - -GEN_SRCS = $(GDIR)\IceBox.cs - -SDIR = $(slicedir)\IceBox -GDIR = generated - - -!include $(top_srcdir)/config/Make.rules.mak.cs - -all:: $(ICEBOXNET).config - -EXE_MCSFLAGS = $(MCSFLAGS) -target:exe - -LIB_MCSFLAGS = $(MCSFLAGS) -target:library -out:$(LIBNAME) -LIB_MCSFLAGS = $(LIB_MCSFLAGS) -keyfile:"$(KEYFILE)" -LIB_MCSFLAGS = $(LIB_MCSFLAGS) /doc:$(assembliesdir)\$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS = $(SLICE2CSFLAGS) --checksum --ice -I. -I$(slicedir) - -$(ICEBOXNET): $(I_SRCS) $(LIBNAME) - $(MCS) $(EXE_MCSFLAGS) -out:$@ -r:$(LIBNAME) -r:$(refdir)\Ice.dll $(I_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -$(LIBNAME): $(L_SRCS) $(GEN_SRCS) - $(MCS) /baseaddress:0x25000000 $(LIB_MCSFLAGS) -r:$(refdir)\Ice.dll $(L_SRCS) $(GEN_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -!if "$(DEBUG)" == "yes" -clean:: - del /q $(assembliesdir)\$(PKG).pdb - del /q $(bindir)\iceboxnet.pdb -!endif - -clean:: - del /q $(assembliesdir)\$(PKG).xml - -!if "$(PUBLIC_KEY_TOKEN)" == "" -$(ICEBOXNET).config: - @sn -q -T $(assembliesdir)\Ice.dll > tmp.publicKeyToken && \ - set /P TMP_TOKEN= < tmp.publicKeyToken && \ - cmd /c "set PUBLIC_KEY_TOKEN=%TMP_TOKEN:~-16% && \ - del tmp.publicKeyToken && \ - nmake /nologo /f Makefile.mak iceboxnetconfig" -!endif - -publicKeyToken = $(PUBLIC_KEY_TOKEN: =) - -iceboxnetconfig: - echo <<$(ICEBOXNET).config -<?xml version="1.0"?> -<configuration> - <runtime> - <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> - <dependentAssembly> - <assemblyIdentity name="Ice" culture="neutral" publicKeyToken="$(publicKeyToken)"/> - <codeBase version="3.6.3.0" href="..\Assemblies\Ice.dll"/> - </dependentAssembly> - <dependentAssembly> - <assemblyIdentity name="IceBox" culture="neutral" publicKeyToken="$(publicKeyToken)"/> - <codeBase version="3.6.3.0" href="..\Assemblies\IceBox.dll"/> - </dependentAssembly> - <!-- - This allows iceboxnet to load the IceSSL plug-in using a strong name. We omit the - optional attributes culture and publicKeyToken so they can be also omitted in the - IceSSL entry point. - --> - <dependentAssembly> - <assemblyIdentity name="IceSSL"/> - <codeBase version="3.6.3.0" href="..\Assemblies\IceSSL.dll"/> - </dependentAssembly> - </assemblyBinding> - </runtime> -</configuration> -<<KEEP - -install:: all - copy $(LIBNAME) "$(install_assembliesdir)" - copy $(assembliesdir)\$(PKG).xml "$(install_assembliesdir)" -!if "$(generate_policies)" == "yes" - copy $(assembliesdir)\$(POLICY_TARGET) "$(install_assembliesdir)" -!endif -!if "$(DEBUG)" == "yes" - copy $(assembliesdir)\$(PKG).pdb "$(install_assembliesdir)" -!endif - -install:: all - copy $(ICEBOXNET) "$(install_bindir)" - copy $(ICEBOXNET).config "$(install_bindir)" -!if "$(DEBUG)" == "yes" - copy $(bindir)\iceboxnet.pdb "$(install_bindir)" -!endif - -clean:: - del /q $(ICEBOXNET).config diff --git a/csharp/src/IceBox/Server.cs b/csharp/src/IceBox/Server.cs index 95fb2db38e4..0662c93ad31 100644 --- a/csharp/src/IceBox/Server.cs +++ b/csharp/src/IceBox/Server.cs @@ -28,13 +28,13 @@ public class Server public override int run(string[] args) { - List<String> argSeq = new List<String>(args); - const String prefix = "IceBox.Service."; + List<string> argSeq = new List<string>(args); + const string prefix = "IceBox.Service."; Ice.Properties properties = communicator().getProperties(); Dictionary<string, string> services = properties.getPropertiesForPrefix(prefix); foreach(KeyValuePair<string, string> pair in services) { - String name = pair.Key.Substring(prefix.Length); + string name = pair.Key.Substring(prefix.Length); for(int i = 0; i < argSeq.Count; ++i) { if(argSeq[i].StartsWith("--" + name, StringComparison.CurrentCulture)) @@ -45,13 +45,18 @@ public class Server } } - foreach(String s in argSeq) + foreach(string s in argSeq) { if(s.Equals("-h") || s.Equals("--help")) { usage(); return 0; } + else if(s.Equals("-v") || s.Equals("--version")) + { + Console.Out.WriteLine(Ice.Util.stringVersion()); + return 0; + } else { Console.Error.WriteLine("Server: unknown option `" + s + "'"); diff --git a/csharp/src/IceBox/ServiceManagerI.cs b/csharp/src/IceBox/ServiceManagerI.cs index 3e369925cc4..129fdb5a468 100644 --- a/csharp/src/IceBox/ServiceManagerI.cs +++ b/csharp/src/IceBox/ServiceManagerI.cs @@ -10,7 +10,7 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Threading; +using System.Threading.Tasks; using System.Diagnostics; namespace IceBox @@ -210,7 +210,6 @@ class ServiceManagerI : ServiceManagerDisp_ // // Null observers and duplicate registrations are ignored // - lock(this) { if(observer != null) @@ -242,7 +241,7 @@ class ServiceManagerI : ServiceManagerDisp_ if(activeServices.Count > 0) { - observer.begin_servicesStarted(activeServices.ToArray(), this.observerCompleted, null); + observer.servicesStartedAsync(activeServices.ToArray()).ContinueWith((t) => observerCompleted(observer, t)); } } @@ -474,7 +473,7 @@ class ServiceManagerI : ServiceManagerDisp_ // string err = "ServiceManager: unable to load service '" + entryPoint + "': "; int sepPos = entryPoint.IndexOf(':'); - if(sepPos != -1 && IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows) + if(sepPos != -1) { const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; if(entryPoint.Length > 3 && @@ -520,7 +519,7 @@ class ServiceManagerI : ServiceManagerDisp_ } } } - catch(System.Exception ex) + catch(Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "unable to load assembly: " + assemblyName; @@ -530,12 +529,12 @@ class ServiceManagerI : ServiceManagerDisp_ // // Instantiate the class. // - System.Type c = null; + Type c = null; try { c = serviceAssembly.GetType(className, true); } - catch(System.Exception ex) + catch(Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "GetType failed for '" + className + "'"; @@ -587,9 +586,7 @@ class ServiceManagerI : ServiceManagerDisp_ // Clone the logger to assign a new prefix. If one of the built-in loggers is configured // don't set any logger. // - if(initData.properties.getProperty("Ice.LogFile").Length == 0 && - (initData.properties.getPropertyAsInt("Ice.UseSyslog") <= 0 || - IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows)) + if(initData.properties.getProperty("Ice.LogFile").Length == 0) { initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName")); } @@ -642,11 +639,11 @@ class ServiceManagerI : ServiceManagerDisp_ { try { - Object[] parameters = new Object[1]; + object[] parameters = new object[1]; parameters[0] = _communicator; info.service = (Service)ci.Invoke(parameters); } - catch(System.MethodAccessException ex) + catch(MethodAccessException ex) { FailureException e = new FailureException(ex); e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)"; @@ -668,7 +665,7 @@ class ServiceManagerI : ServiceManagerDisp_ throw e; } } - catch(System.UnauthorizedAccessException ex) + catch(UnauthorizedAccessException ex) { FailureException e = new FailureException(ex); e.reason = err + "unauthorized access to default service constructor for " + className; @@ -680,7 +677,7 @@ class ServiceManagerI : ServiceManagerDisp_ { throw; } - catch(System.InvalidCastException ex) + catch(InvalidCastException ex) { FailureException e = new FailureException(ex); e.reason = err + "service does not implement IceBox.Service"; @@ -688,7 +685,7 @@ class ServiceManagerI : ServiceManagerDisp_ } catch(System.Reflection.TargetInvocationException ex) { - if(ex.InnerException is IceBox.FailureException) + if(ex.InnerException is FailureException) { throw ex.InnerException; } @@ -699,7 +696,7 @@ class ServiceManagerI : ServiceManagerDisp_ throw e; } } - catch(System.Exception ex) + catch(Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "exception in service constructor " + className; @@ -715,7 +712,7 @@ class ServiceManagerI : ServiceManagerDisp_ { throw; } - catch(System.Exception ex) + catch(Exception ex) { FailureException e = new FailureException(ex); e.reason = "exception while starting service " + service; @@ -725,14 +722,14 @@ class ServiceManagerI : ServiceManagerDisp_ info.status = ServiceStatus.Started; _services.Add(info); } - catch(System.Exception ex) + catch(Exception) { if(info.communicator != null) { destroyServiceCommunicator(service, info.communicator); } - throw ex; + throw; } } @@ -765,7 +762,7 @@ class ServiceManagerI : ServiceManagerDisp_ info.service.stop(); stoppedServices.Add(info.name); } - catch(System.Exception e) + catch(Exception e) { _logger.warning("IceBox.ServiceManager: exception while stopping service " + info.name + ":\n" + e.ToString()); @@ -786,7 +783,7 @@ class ServiceManagerI : ServiceManagerDisp_ { _sharedCommunicator.destroy(); } - catch(System.Exception e) + catch(Exception e) { _logger.warning("ServiceManager: exception while destroying shared communicator:\n" + e.ToString()); } @@ -798,7 +795,7 @@ class ServiceManagerI : ServiceManagerDisp_ } } - private void servicesStarted(List<String> services, Dictionary<ServiceObserverPrx, bool>.KeyCollection observers) + private void servicesStarted(List<string> services, Dictionary<ServiceObserverPrx, bool>.KeyCollection observers) { // // Must be called with 'this' unlocked @@ -810,7 +807,7 @@ class ServiceManagerI : ServiceManagerDisp_ foreach(ServiceObserverPrx observer in observers) { - observer.begin_servicesStarted(servicesArray, this.observerCompleted, null); + observer.servicesStartedAsync(servicesArray).ContinueWith((t) => observerCompleted(observer, t)); } } } @@ -827,32 +824,31 @@ class ServiceManagerI : ServiceManagerDisp_ foreach(ServiceObserverPrx observer in observers) { - observer.begin_servicesStopped(servicesArray, this.observerCompleted, null); + observer.servicesStoppedAsync(servicesArray).ContinueWith((t) => observerCompleted(observer, t)); } } } private void - observerCompleted(Ice.AsyncResult result) + observerCompleted(ServiceObserverPrx observer, Task t) { try { - result.throwLocalException(); + t.Wait(); } - catch(Ice.LocalException ex) + catch(AggregateException ae) { lock(this) { - ServiceObserverPrx observer = ServiceObserverPrxHelper.uncheckedCast(result.getProxy()); if(_observers.Remove(observer)) { - observerRemoved(observer, ex); + observerRemoved(observer, ae.InnerException); } } } } - private void observerRemoved(ServiceObserverPrx observer, System.Exception ex) + private void observerRemoved(ServiceObserverPrx observer, Exception ex) { if(_traceServiceObserver >= 1) { @@ -941,7 +937,7 @@ class ServiceManagerI : ServiceManagerDisp_ public string[] args; } - private Ice.Properties createServiceProperties(String service) + private Ice.Properties createServiceProperties(string service) { Ice.Properties properties; Ice.Properties communicatorProperties = _communicator.getProperties(); @@ -959,7 +955,7 @@ class ServiceManagerI : ServiceManagerDisp_ properties = Ice.Util.createProperties(); } - String programName = communicatorProperties.getProperty("Ice.ProgramName"); + string programName = communicatorProperties.getProperty("Ice.ProgramName"); if(programName.Length == 0) { properties.setProperty("Ice.ProgramName", service); @@ -987,23 +983,14 @@ class ServiceManagerI : ServiceManagerDisp_ // the communicator for its own reasons. // } - catch(System.Exception e) + catch(Exception e) { _logger.warning("ServiceManager: exception while shutting down communicator for service " + service + "\n" + e.ToString()); } removeAdminFacets("IceBox.Service." + service + "."); - - try - { - communicator.destroy(); - } - catch(System.Exception e) - { - _logger.warning("ServiceManager: exception while destroying communicator for service " - + service + "\n" + e.ToString()); - } + communicator.destroy(); } } @@ -1027,7 +1014,7 @@ class ServiceManagerI : ServiceManagerDisp_ if(facetNames.Count > 0) { // TODO: need String.Join with escape! - properties.setProperty("Ice.Admin.Facets", String.Join(" ", facetNames.ToArray())); + properties.setProperty("Ice.Admin.Facets", string.Join(" ", facetNames.ToArray())); } return true; } diff --git a/csharp/src/IceBox/generated/.gitignore b/csharp/src/IceBox/generated/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/csharp/src/IceBox/generated/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/csharp/src/IceBox/msbuild/icebox/icebox.csproj b/csharp/src/IceBox/msbuild/icebox/icebox.csproj new file mode 100644 index 00000000000..294b12fd1b6 --- /dev/null +++ b/csharp/src/IceBox/msbuild/icebox/icebox.csproj @@ -0,0 +1,72 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{30ED316B-AA69-4A88-A1A3-DB27A425D6BD}</ProjectGuid> + <OutputType>Exe</OutputType> + <AssemblyName>iceboxnet</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\..\bin\iceboxnet.XML</DocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Folder Include="generated\" /> + <Folder Include="Properties\" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\..\AssemblyInfoExe.cs"> + <Link>AssemblyInfoExe.cs</Link> + </Compile> + <Compile Include="..\..\Server.cs"> + <Link>Server.cs</Link> + </Compile> + <Compile Include="..\..\ServiceManagerI.cs"> + <Link>ServiceManagerI.cs</Link> + </Compile> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\..\Ice\msbuild\ice.csproj"> + <Project>{7cb4715e-dd8b-48f8-b478-27b8bd4008c7}</Project> + <Name>ice</Name> + <Private>False</Private> + </ProjectReference> + <ProjectReference Include="..\iceboxlib\iceboxlib.csproj"> + <Project>{ff25599c-3654-4df3-8078-b8235341df83}</Project> + <Name>iceboxlib</Name> + <Private>False</Private> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\..\config\ice.sign.targets" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\msbuild\ice.common.targets" /> + <!-- Generate iceboxnet.exe.config with the correct assembly pulbic key token and + assembly paths --> + <Target Name="PostBuild" AfterTargets="Build"> + <GetPublicKeyToken AssemblyFile="$(MSBuildThisFileDirectory)..\..\..\..\Assemblies\Ice.dll"> + <Output TaskParameter="PublicKeyToken" PropertyName="PublicKeyToken" /> + </GetPublicKeyToken> + <WriteFileWithReplacements InputFile="$(MSBuildThisFileDirectory)..\..\..\..\msbuild\iceboxnet.exe.config" OutputFile="$(MSBuildThisFileDirectory)..\..\..\..\bin\iceboxnet.exe.config" Tokens="@PublicKeyToken@;@AssemblyDir@" Replacements="$(PublicKeyToken);..\Assemblies" /> + </Target> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/IceBox/msbuild/iceboxlib/iceboxlib.csproj b/csharp/src/IceBox/msbuild/iceboxlib/iceboxlib.csproj new file mode 100644 index 00000000000..d161f13b9a0 --- /dev/null +++ b/csharp/src/IceBox/msbuild/iceboxlib/iceboxlib.csproj @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{FF25599C-3654-4DF3-8078-B8235341DF83}</ProjectGuid> + <OutputType>Library</OutputType> + <AssemblyName>IceBox</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\..\Assemblies\IceBox.XML</DocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\..\AssemblyInfo.cs"> + <Link>AssemblyInfo.cs</Link> + </Compile> + <Compile Include="generated\IceBox.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\..\slice\IceBox\IceBox.ice"> + <Link>IceBox.ice</Link> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\..\Ice\msbuild\ice.csproj"> + <Project>{7cb4715e-dd8b-48f8-b478-27b8bd4008c7}</Project> + <Name>ice</Name> + <Private>False</Private> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\..\config\ice.sign.targets" /> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/IceDiscovery/.depend.mak b/csharp/src/IceDiscovery/.depend.mak deleted file mode 100644 index 0f34b397f12..00000000000 --- a/csharp/src/IceDiscovery/.depend.mak +++ /dev/null @@ -1,4 +0,0 @@ - -IceDiscovery.cs: \ - "$(slicedir)\IceDiscovery\IceDiscovery.ice" \ - "$(slicedir)/Ice/Identity.ice" diff --git a/csharp/src/IceDiscovery/AssemblyInfo.cs b/csharp/src/IceDiscovery/AssemblyInfo.cs index 42401975335..048d59c02ac 100644 --- a/csharp/src/IceDiscovery/AssemblyInfo.cs +++ b/csharp/src/IceDiscovery/AssemblyInfo.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/IceDiscovery/LocatorI.cs b/csharp/src/IceDiscovery/LocatorI.cs index 6413187b594..41859bdec6f 100644 --- a/csharp/src/IceDiscovery/LocatorI.cs +++ b/csharp/src/IceDiscovery/LocatorI.cs @@ -9,22 +9,19 @@ namespace IceDiscovery { - using System; using System.Collections.Generic; + using System.Threading.Tasks; class LocatorRegistryI : Ice.LocatorRegistryDisp_ { - public + public LocatorRegistryI(Ice.Communicator com) { _wellKnownProxy = com.stringToProxy("p").ice_locator(null).ice_router(null).ice_collocationOptimized(true); } - public override void - setAdapterDirectProxy_async(Ice.AMD_LocatorRegistry_setAdapterDirectProxy cb, - string adapterId, - Ice.ObjectPrx proxy, - Ice.Current current) + public override Task + setAdapterDirectProxyAsync(string adapterId, Ice.ObjectPrx proxy, Ice.Current current) { lock(this) { @@ -36,16 +33,13 @@ namespace IceDiscovery { _adapters.Remove(adapterId); } - cb.ice_response(); } + return null; } - public override void - setReplicatedAdapterDirectProxy_async(Ice.AMD_LocatorRegistry_setReplicatedAdapterDirectProxy cb, - string adapterId, - string replicaGroupId, - Ice.ObjectPrx proxy, - Ice.Current current) + public override Task + setReplicatedAdapterDirectProxyAsync(string adapterId, string replicaGroupId, Ice.ObjectPrx proxy, + Ice.Current current) { lock(this) { @@ -74,16 +68,13 @@ namespace IceDiscovery } } } - cb.ice_response(); + return null; } - public override void - setServerProcessProxy_async(Ice.AMD_LocatorRegistry_setServerProcessProxy cb, - string id, - Ice.ProcessPrx process, - Ice.Current current) + public override Task + setServerProcessProxyAsync(string id, Ice.ProcessPrx process, Ice.Current current) { - cb.ice_response(); + return null; } internal Ice.ObjectPrx findObject(Ice.Identity id) @@ -123,7 +114,7 @@ namespace IceDiscovery } } } - + if(adapterIds.Count == 0) { return null; @@ -143,7 +134,7 @@ namespace IceDiscovery isReplicaGroup = false; return result; } - + HashSet<string> adapterIds; if(_replicaGroups.TryGetValue(adapterId, out adapterIds)) { @@ -155,15 +146,15 @@ namespace IceDiscovery { continue; // TODO: Inconsistency } - + if(result == null) { result = proxy; } - + endpoints.AddRange(proxy.ice_getEndpoints()); } - + if(result != null) { isReplicaGroup = true; @@ -189,21 +180,23 @@ namespace IceDiscovery _registry = registry; } - public override void findObjectById_async(Ice.AMD_Locator_findObjectById cb, Ice.Identity id, Ice.Current c) + public override Task<Ice.ObjectPrx> + findObjectByIdAsync(Ice.Identity id, Ice.Current current) { - _lookup.findObject(cb, id); + return _lookup.findObject(id); } - public override void findAdapterById_async(Ice.AMD_Locator_findAdapterById cb, string adapterId, Ice.Current c) + public override Task<Ice.ObjectPrx> + findAdapterByIdAsync(string adapterId, Ice.Current current) { - _lookup.findAdapter(cb, adapterId); + return _lookup.findAdapter(adapterId); } public override Ice.LocatorRegistryPrx getRegistry(Ice.Current current) { return _registry; } - + private LookupI _lookup; private Ice.LocatorRegistryPrx _registry; }; diff --git a/csharp/src/IceDiscovery/LookupI.cs b/csharp/src/IceDiscovery/LookupI.cs index 2db8c60ad33..ee1775bb444 100644 --- a/csharp/src/IceDiscovery/LookupI.cs +++ b/csharp/src/IceDiscovery/LookupI.cs @@ -11,8 +11,9 @@ namespace IceDiscovery { using System; using System.Collections.Generic; + using System.Threading.Tasks; - class Request<T, AmdCB> + class Request<T> { protected Request(LookupI lookup, T id, int retryCount) { @@ -26,7 +27,7 @@ namespace IceDiscovery return _id; } - public bool addCallback(AmdCB cb) + public bool addCallback(TaskCompletionSource<Ice.ObjectPrx> cb) { callbacks_.Add(cb); return callbacks_.Count == 1; @@ -39,16 +40,16 @@ namespace IceDiscovery protected LookupI lookup_; protected int nRetry_; - protected List<AmdCB> callbacks_ = new List<AmdCB>(); + protected List<TaskCompletionSource<Ice.ObjectPrx>> callbacks_ = new List<TaskCompletionSource<Ice.ObjectPrx>>(); private T _id; }; - class AdapterRequest : Request<string, Ice.AMD_Locator_findAdapterById>, IceInternal.TimerTask + class AdapterRequest : Request<string>, IceInternal.TimerTask { public AdapterRequest(LookupI lookup, string id, int retryCount) : base(lookup, id, retryCount) { - _start = System.DateTime.Now.Ticks; + _start = DateTime.Now.Ticks; } public override bool retry() @@ -63,7 +64,7 @@ namespace IceDiscovery _proxies.Add(proxy); if(_latency == 0) { - _latency = (long)((System.DateTime.Now.Ticks - _start) * lookup_.latencyMultiplier() / 10000.0); + _latency = (long)((DateTime.Now.Ticks - _start) * lookup_.latencyMultiplier() / 10000.0); if(_latency == 0) { _latency = 1; // 1ms @@ -110,9 +111,9 @@ namespace IceDiscovery private void sendResponse(Ice.ObjectPrx proxy) { - foreach(Ice.AMD_Locator_findAdapterById cb in callbacks_) + foreach(var cb in callbacks_) { - cb.ice_response(proxy); + cb.SetResult(proxy); } callbacks_.Clear(); } @@ -122,7 +123,7 @@ namespace IceDiscovery private long _latency; }; - class ObjectRequest : Request<Ice.Identity, Ice.AMD_Locator_findObjectById>, IceInternal.TimerTask + class ObjectRequest : Request<Ice.Identity>, IceInternal.TimerTask { public ObjectRequest(LookupI lookup, Ice.Identity id, int retryCount) : base(lookup, id, retryCount) { @@ -135,9 +136,9 @@ namespace IceDiscovery public void finished(Ice.ObjectPrx proxy) { - foreach(Ice.AMD_Locator_findObjectById cb in callbacks_) + foreach(var cb in callbacks_) { - cb.ice_response(proxy); + cb.SetResult(proxy); } callbacks_.Clear(); } @@ -166,8 +167,8 @@ namespace IceDiscovery _lookupReply = lookupReply; } - public override void findObjectById(string domainId, Ice.Identity id, IceDiscovery.LookupReplyPrx reply, - Ice.Current c) + public override void findObjectById(string domainId, Ice.Identity id, LookupReplyPrx reply, + Ice.Current current) { if(!domainId.Equals(_domainId)) { @@ -182,7 +183,7 @@ namespace IceDiscovery // try { - reply.begin_foundObjectById(id, proxy); + reply.foundObjectByIdAsync(id, proxy); } catch(Ice.LocalException) { @@ -191,8 +192,8 @@ namespace IceDiscovery } } - public override void findAdapterById(string domainId, string adapterId, IceDiscovery.LookupReplyPrx reply, - Ice.Current c) + public override void findAdapterById(string domainId, string adapterId, LookupReplyPrx reply, + Ice.Current current) { if(!domainId.Equals(_domainId)) { @@ -208,7 +209,7 @@ namespace IceDiscovery // try { - reply.begin_foundAdapterById(adapterId, proxy, isReplicaGroup); + reply.foundAdapterByIdAsync(adapterId, proxy, isReplicaGroup); } catch(Ice.LocalException) { @@ -217,7 +218,7 @@ namespace IceDiscovery } } - internal void findObject(Ice.AMD_Locator_findObjectById cb, Ice.Identity id) + internal Task<Ice.ObjectPrx> findObject(Ice.Identity id) { lock(this) { @@ -227,11 +228,13 @@ namespace IceDiscovery request = new ObjectRequest(this, id, _retryCount); _objectRequests.Add(id, request); } - if(request.addCallback(cb)) + + var task = new TaskCompletionSource<Ice.ObjectPrx>(); + if(request.addCallback(task)) { try { - _lookup.begin_findObjectById(_domainId, id, _lookupReply); + _lookup.findObjectByIdAsync(_domainId, id, _lookupReply); _timer.schedule(request, _timeout); } catch(Ice.LocalException) @@ -240,10 +243,11 @@ namespace IceDiscovery _objectRequests.Remove(id); } } + return task.Task; } } - internal void findAdapter(Ice.AMD_Locator_findAdapterById cb, string adapterId) + internal Task<Ice.ObjectPrx> findAdapter(string adapterId) { lock(this) { @@ -253,11 +257,13 @@ namespace IceDiscovery request = new AdapterRequest(this, adapterId, _retryCount); _adapterRequests.Add(adapterId, request); } - if(request.addCallback(cb)) + + var task = new TaskCompletionSource<Ice.ObjectPrx>(); + if(request.addCallback(task)) { try { - _lookup.begin_findAdapterById(_domainId, adapterId, _lookupReply); + _lookup.findAdapterByIdAsync(_domainId, adapterId, _lookupReply); _timer.schedule(request, _timeout); } catch(Ice.LocalException) @@ -266,6 +272,7 @@ namespace IceDiscovery _adapterRequests.Remove(adapterId); } } + return task.Task; } } @@ -316,7 +323,7 @@ namespace IceDiscovery { try { - _lookup.begin_findObjectById(_domainId, request.getId(), _lookupReply); + _lookup.findObjectByIdAsync(_domainId, request.getId(), _lookupReply); _timer.schedule(request, _timeout); return; } @@ -345,7 +352,7 @@ namespace IceDiscovery { try { - _lookup.begin_findAdapterById(_domainId, request.getId(), _lookupReply); + _lookup.findAdapterByIdAsync(_domainId, request.getId(), _lookupReply); _timer.schedule(request, _timeout); return; } diff --git a/csharp/src/IceDiscovery/Makefile b/csharp/src/IceDiscovery/Makefile deleted file mode 100644 index bbee6d6be00..00000000000 --- a/csharp/src/IceDiscovery/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -PKG = IceDiscovery -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)/$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs \ - LocatorI.cs \ - LookupI.cs \ - PluginI.cs - -SLICE_SRCS = $(SDIR)/IceDiscovery.ice - -SDIR = $(slicedir)/IceDiscovery -GDIR = generated - -include $(top_srcdir)/config/Make.rules.cs - -MCSFLAGS := $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS := $(MCSFLAGS) -keyfile:$(KEYFILE) -MCSFLAGS := $(MCSFLAGS) /doc:$(assembliesdir)/$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS := $(SLICE2CSFLAGS) --ice -I$(slicedir) - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) $(call ref,Ice) $(subst /,$(DSEP),$^) - -install:: all - (cd $(assembliesdir); $(call installassembly,$(LIBNAME),$(PKG)); $(call installpolicy,$(POLICY)); \ - $(call installmdb,$(LIBNAME).mdb); \ - $(call installdata,$(PKG).xml,$(DESTDIR)$(install_assembliesdir))) - -ifeq ($(GACINSTALL),yes) -install:: all - $(call installdata,../../lib/pkgconfig/$(PKG).pc,$(DESTDIR)$(install_pkgconfigdir)) -endif - -clean:: - -rm -f $(assembliesdir)/$(PKG).xml diff --git a/csharp/src/IceDiscovery/Makefile.mak b/csharp/src/IceDiscovery/Makefile.mak deleted file mode 100644 index eaf7e971905..00000000000 --- a/csharp/src/IceDiscovery/Makefile.mak +++ /dev/null @@ -1,56 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -PKG = IceDiscovery -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)\$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs \ - LocatorI.cs \ - LookupI.cs \ - PluginI.cs - -GEN_SRCS = $(GDIR)\IceDiscovery.cs - -SDIR = $(slicedir)\IceDiscovery -GDIR = generated - -!include $(top_srcdir)\config\Make.rules.mak.cs - -MCSFLAGS = $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS = $(MCSFLAGS) -keyfile:"$(KEYFILE)" -MCSFLAGS = $(MCSFLAGS) /doc:$(assembliesdir)\$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS = $(SLICE2CSFLAGS) --ice -I$(slicedir) - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) -r:$(refdir)\Ice.dll $(SRCS) $(GEN_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -!if "$(DEBUG)" == "yes" -clean:: - del /q $(assembliesdir)\$(PKG).pdb -!endif - -clean:: - del /q $(assembliesdir)\$(PKG).xml - -install:: all - copy $(assembliesdir)\$(LIBNAME) "$(install_assembliesdir)" - copy $(assembliesdir)\$(PKG).xml "$(install_assembliesdir)" -!if "$(generate_policies)" == "yes" - copy $(assembliesdir)\$(POLICY_TARGET) "$(install_assembliesdir)" -!endif -!if "$(DEBUG)" == "yes" - copy $(assembliesdir)\$(PKG).pdb "$(install_assembliesdir)" -!endif diff --git a/csharp/src/IceDiscovery/PluginI.cs b/csharp/src/IceDiscovery/PluginI.cs index 1fe420a66c6..5883dabeaf5 100644 --- a/csharp/src/IceDiscovery/PluginI.cs +++ b/csharp/src/IceDiscovery/PluginI.cs @@ -11,7 +11,6 @@ namespace IceDiscovery { using System; using System.Text; - using System.Collections.Generic; public sealed class PluginFactory : Ice.PluginFactory { @@ -115,7 +114,7 @@ namespace IceDiscovery // Add lookup and lookup reply Ice objects // LookupI lookup = new LookupI(locatorRegistry, LookupPrxHelper.uncheckedCast(lookupPrx), properties); - _multicastAdapter.add(lookup, _communicator.stringToIdentity("IceDiscovery/Lookup")); + _multicastAdapter.add(lookup, Ice.Util.stringToIdentity("IceDiscovery/Lookup")); Ice.ObjectPrx lookupReply = _replyAdapter.addWithUUID(new LookupReplyI(lookup)).ice_datagram(); lookup.setLookupReply(LookupReplyPrxHelper.uncheckedCast(lookupReply)); diff --git a/csharp/src/IceDiscovery/generated/.gitignore b/csharp/src/IceDiscovery/generated/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/csharp/src/IceDiscovery/generated/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/csharp/src/IceDiscovery/msbuild/icediscovery.csproj b/csharp/src/IceDiscovery/msbuild/icediscovery.csproj new file mode 100644 index 00000000000..89ea1449060 --- /dev/null +++ b/csharp/src/IceDiscovery/msbuild/icediscovery.csproj @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{CFFB222B-19D5-499E-B833-B0F7E523B16F}</ProjectGuid> + <OutputType>Library</OutputType> + <AssemblyName>IceDiscovery</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\Assemblies\IceDiscovery.XML</DocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\AssemblyInfo.cs"> + <Link>AssemblyInfo.cs</Link> + </Compile> + <Compile Include="..\LocatorI.cs"> + <Link>LocatorI.cs</Link> + </Compile> + <Compile Include="..\LookupI.cs"> + <Link>LookupI.cs</Link> + </Compile> + <Compile Include="..\PluginI.cs"> + <Link>PluginI.cs</Link> + </Compile> + <Compile Include="generated\IceDiscovery.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\slice\IceDiscovery\IceDiscovery.ice"> + <Link>IceDiscovery.ice</Link> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\Ice\msbuild\ice.csproj"> + <Project>{7cb4715e-dd8b-48f8-b478-27b8bd4008c7}</Project> + <Name>ice</Name> + <Private>False</Private> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\config\ice.sign.targets" /> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/IceGrid/.depend.mak b/csharp/src/IceGrid/.depend.mak deleted file mode 100644 index c88e67a088b..00000000000 --- a/csharp/src/IceGrid/.depend.mak +++ /dev/null @@ -1,92 +0,0 @@ - -Admin.cs: \ - "$(slicedir)\IceGrid\Admin.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Exception.ice" \ - "$(slicedir)/IceGrid/Descriptor.ice" - -Descriptor.cs: \ - "$(slicedir)\IceGrid\Descriptor.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Discovery.cs: \ - "$(slicedir)\IceGrid\Discovery.ice" \ - "$(slicedir)/IceGrid/Locator.ice" \ - "$(slicedir)/Ice/Locator.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/ProcessF.ice" - -Exception.cs: \ - "$(slicedir)\IceGrid\Exception.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -FileParser.cs: \ - "$(slicedir)\IceGrid\FileParser.ice" \ - "$(slicedir)/IceGrid/Admin.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Exception.ice" \ - "$(slicedir)/IceGrid/Descriptor.ice" - -Locator.cs: \ - "$(slicedir)\IceGrid\Locator.ice" \ - "$(slicedir)/Ice/Locator.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/ProcessF.ice" - -Observer.cs: \ - "$(slicedir)\IceGrid\Observer.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Exception.ice" \ - "$(slicedir)/IceGrid/Descriptor.ice" \ - "$(slicedir)/IceGrid/Admin.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" - -Query.cs: \ - "$(slicedir)\IceGrid\Query.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/IceGrid/Exception.ice" - -Registry.cs: \ - "$(slicedir)\IceGrid\Registry.ice" \ - "$(slicedir)/IceGrid/Exception.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/IceGrid/Session.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Admin.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" \ - "$(slicedir)/IceGrid/Descriptor.ice" - -Session.cs: \ - "$(slicedir)\IceGrid\Session.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Exception.ice" - -UserAccountMapper.cs: \ - "$(slicedir)\IceGrid\UserAccountMapper.ice" diff --git a/csharp/src/IceGrid/AssemblyInfo.cs b/csharp/src/IceGrid/AssemblyInfo.cs index 1ab7ea233e0..8d2acbfd678 100644 --- a/csharp/src/IceGrid/AssemblyInfo.cs +++ b/csharp/src/IceGrid/AssemblyInfo.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/IceGrid/Makefile b/csharp/src/IceGrid/Makefile deleted file mode 100644 index bbdc34c8855..00000000000 --- a/csharp/src/IceGrid/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -PKG = IceGrid -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)/$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs - -SLICE_SRCS = $(SDIR)/Admin.ice \ - $(SDIR)/Descriptor.ice \ - $(SDIR)/Exception.ice \ - $(SDIR)/FileParser.ice \ - $(SDIR)/Locator.ice \ - $(SDIR)/Observer.ice \ - $(SDIR)/Query.ice \ - $(SDIR)/Registry.ice \ - $(SDIR)/Session.ice \ - $(SDIR)/UserAccountMapper.ice - -SDIR = $(slicedir)/IceGrid -GDIR = generated - -include $(top_srcdir)/config/Make.rules.cs - -MCSFLAGS := $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS := $(MCSFLAGS) -keyfile:$(KEYFILE) -MCSFLAGS := $(MCSFLAGS) /doc:$(assembliesdir)/$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS := $(SLICE2CSFLAGS) --ice -I$(slicedir) - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) $(call ref,Glacier2) $(call ref,Ice) $(subst /,$(DSEP),$^) - -install:: all - (cd $(assembliesdir); $(call installassembly,$(LIBNAME),$(PKG)); $(call installpolicy,$(POLICY)); \ - $(call installmdb,$(LIBNAME).mdb); \ - $(call installdata,$(PKG).xml,$(DESTDIR)$(install_assembliesdir))) - -ifeq ($(GACINSTALL),yes) -install:: all - $(call installdata,../../lib/pkgconfig/$(PKG).pc,$(DESTDIR)$(install_pkgconfigdir)) -endif - -clean:: - -rm -f $(assembliesdir)/$(PKG).xml diff --git a/csharp/src/IceGrid/Makefile.mak b/csharp/src/IceGrid/Makefile.mak deleted file mode 100644 index 8e973634f43..00000000000 --- a/csharp/src/IceGrid/Makefile.mak +++ /dev/null @@ -1,62 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -PKG = IceGrid -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)\$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs - -GEN_SRCS = $(GDIR)\Admin.cs \ - $(GDIR)\Descriptor.cs \ - $(GDIR)\Exception.cs \ - $(GDIR)\FileParser.cs \ - $(GDIR)\Locator.cs \ - $(GDIR)\Observer.cs \ - $(GDIR)\Query.cs \ - $(GDIR)\Registry.cs \ - $(GDIR)\Session.cs \ - $(GDIR)\UserAccountMapper.cs - -SDIR = $(slicedir)\IceGrid -GDIR = generated - -!include $(top_srcdir)\config\Make.rules.mak.cs - -MCSFLAGS = $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS = $(MCSFLAGS) -keyfile:"$(KEYFILE)" -MCSFLAGS = $(MCSFLAGS) /doc:$(assembliesdir)\$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS = $(SLICE2CSFLAGS) --ice -I$(slicedir) - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) /baseaddress:0x24000000 $(MCSFLAGS) -r:$(refdir)\Glacier2.dll -r:$(refdir)\Ice.dll $(SRCS) $(GEN_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -!if "$(DEBUG)" == "yes" -clean:: - del /q $(assembliesdir)\$(PKG).pdb -!endif - -clean:: - del /q $(assembliesdir)\$(PKG).xml - -install:: all - copy $(assembliesdir)\$(LIBNAME) "$(install_assembliesdir)" - copy $(assembliesdir)\$(PKG).xml "$(install_assembliesdir)" -!if "$(generate_policies)" == "yes" - copy $(assembliesdir)\$(POLICY_TARGET) "$(install_assembliesdir)" -!endif -!if "$(DEBUG)" == "yes" - copy $(assembliesdir)\$(PKG).pdb "$(install_assembliesdir)" -!endif diff --git a/csharp/src/IceGrid/generated/.gitignore b/csharp/src/IceGrid/generated/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/csharp/src/IceGrid/generated/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/csharp/src/IceGrid/msbuild/icegrid.csproj b/csharp/src/IceGrid/msbuild/icegrid.csproj new file mode 100644 index 00000000000..247957019a4 --- /dev/null +++ b/csharp/src/IceGrid/msbuild/icegrid.csproj @@ -0,0 +1,90 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{1153F70C-80E9-469A-952F-5117DAEE71A9}</ProjectGuid> + <OutputType>Library</OutputType> + <AssemblyName>IceGrid</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\Assemblies\IceGrid.XML</DocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\AssemblyInfo.cs"> + <Link>AssemblyInfo.cs</Link> + </Compile> + <Compile Include="generated\Admin.cs" /> + <Compile Include="generated\Descriptor.cs" /> + <Compile Include="generated\Exception.cs" /> + <Compile Include="generated\FileParser.cs" /> + <Compile Include="generated\PluginFacade.cs" /> + <Compile Include="generated\Registry.cs" /> + <Compile Include="generated\Session.cs" /> + <Compile Include="generated\UserAccountMapper.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\slice\IceGrid\Admin.ice"> + <Link>Admin.ice</Link> + </None> + <None Include="..\..\..\..\slice\IceGrid\Descriptor.ice"> + <Link>Descriptor.ice</Link> + </None> + <None Include="..\..\..\..\slice\IceGrid\Exception.ice"> + <Link>Exception.ice</Link> + </None> + <None Include="..\..\..\..\slice\IceGrid\FileParser.ice"> + <Link>FileParser.ice</Link> + </None> + <None Include="..\..\..\..\slice\IceGrid\PluginFacade.ice"> + <Link>PluginFacade.ice</Link> + </None> + <None Include="..\..\..\..\slice\IceGrid\Registry.ice"> + <Link>Registry.ice</Link> + </None> + <None Include="..\..\..\..\slice\IceGrid\Session.ice"> + <Link>Session.ice</Link> + </None> + <None Include="..\..\..\..\slice\IceGrid\UserAccountMapper.ice"> + <Link>UserAccountMapper.ice</Link> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\Glacier2\msbuild\glacier2.csproj"> + <Project>{d765a8a0-01c2-4eee-b6c0-5dd6f9c1087a}</Project> + <Name>glacier2</Name> + <Private>False</Private> + </ProjectReference> + <ProjectReference Include="..\..\Ice\msbuild\ice.csproj"> + <Project>{7cb4715e-dd8b-48f8-b478-27b8bd4008c7}</Project> + <Name>ice</Name> + <Private>False</Private> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\config\ice.sign.targets" /> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/IceLocatorDiscovery/AssemblyInfo.cs b/csharp/src/IceLocatorDiscovery/AssemblyInfo.cs index 7c38f607ead..e41546c7311 100644 --- a/csharp/src/IceLocatorDiscovery/AssemblyInfo.cs +++ b/csharp/src/IceLocatorDiscovery/AssemblyInfo.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/IceLocatorDiscovery/Makefile b/csharp/src/IceLocatorDiscovery/Makefile deleted file mode 100644 index 66c56cb7fbe..00000000000 --- a/csharp/src/IceLocatorDiscovery/Makefile +++ /dev/null @@ -1,47 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -PKG = IceLocatorDiscovery -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)/$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs \ - PluginI.cs - -SLICE_SRCS = $(SDIR)/IceLocatorDiscovery.ice - -SDIR = $(slicedir)/IceLocatorDiscovery -GDIR = generated - -include $(top_srcdir)/config/Make.rules.cs - -MCSFLAGS := $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS := $(MCSFLAGS) -keyfile:$(KEYFILE) -MCSFLAGS := $(MCSFLAGS) /doc:$(assembliesdir)/$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS := $(SLICE2CSFLAGS) --ice -I$(slicedir) - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) $(call ref,Ice) $(subst /,$(DSEP),$^) - -install:: all - (cd $(assembliesdir); $(call installassembly,$(LIBNAME),$(PKG)); $(call installpolicy,$(POLICY)); \ - $(call installmdb,$(LIBNAME).mdb); \ - $(call installdata,$(PKG).xml,$(DESTDIR)$(install_assembliesdir))) - -ifeq ($(GACINSTALL),yes) -install:: all - $(call installdata,../../lib/pkgconfig/$(PKG).pc,$(DESTDIR)$(install_pkgconfigdir)) -endif - -clean:: - -rm -f $(assembliesdir)/$(PKG).xml diff --git a/csharp/src/IceLocatorDiscovery/Makefile.mak b/csharp/src/IceLocatorDiscovery/Makefile.mak deleted file mode 100644 index f12349f9324..00000000000 --- a/csharp/src/IceLocatorDiscovery/Makefile.mak +++ /dev/null @@ -1,54 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -PKG = IceLocatorDiscovery -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)\$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs \ - PluginI.cs - -GEN_SRCS = $(GDIR)\IceLocatorDiscovery.cs - -SDIR = $(slicedir)\IceLocatorDiscovery -GDIR = generated - -!include $(top_srcdir)\config\Make.rules.mak.cs - -MCSFLAGS = $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS = $(MCSFLAGS) -keyfile:"$(KEYFILE)" -MCSFLAGS = $(MCSFLAGS) /doc:$(assembliesdir)\$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS = $(SLICE2CSFLAGS) --ice -I$(slicedir) - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) -r:$(refdir)\Ice.dll $(SRCS) $(GEN_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -!if "$(DEBUG)" == "yes" -clean:: - del /q $(assembliesdir)\$(PKG).pdb -!endif - -clean:: - del /q $(assembliesdir)\$(PKG).xml - -install:: all - copy $(assembliesdir)\$(LIBNAME) "$(install_assembliesdir)" - copy $(assembliesdir)\$(PKG).xml "$(install_assembliesdir)" -!if "$(generate_policies)" == "yes" - copy $(assembliesdir)\$(POLICY_TARGET) "$(install_assembliesdir)" -!endif -!if "$(DEBUG)" == "yes" - copy $(assembliesdir)\$(PKG).pdb "$(install_assembliesdir)" -!endif diff --git a/csharp/src/IceLocatorDiscovery/PluginI.cs b/csharp/src/IceLocatorDiscovery/PluginI.cs index 75c02349576..7e728d4b2e8 100644 --- a/csharp/src/IceLocatorDiscovery/PluginI.cs +++ b/csharp/src/IceLocatorDiscovery/PluginI.cs @@ -12,7 +12,7 @@ namespace IceLocatorDiscovery using System; using System.Collections.Generic; using System.Diagnostics; - using System.Text; + using System.Threading.Tasks; public sealed class PluginFactory : Ice.PluginFactory { @@ -23,21 +23,19 @@ namespace IceLocatorDiscovery } } - internal class Request + internal class Request : TaskCompletionSource<Ice.Object_Ice_invokeResult> { public Request(LocatorI locator, string operation, Ice.OperationMode mode, byte[] inParams, - Dictionary<string, string> context, - Ice.AMD_Object_ice_invoke amdCB) + Dictionary<string, string> context) { _locator = locator; _operation = operation; _mode = mode; _inParams = inParams; _context = context; - _amdCB = amdCB; } public void @@ -46,22 +44,18 @@ namespace IceLocatorDiscovery if(_locatorPrx == null || !_locatorPrx.Equals(l)) { _locatorPrx = l; - try - { - l.begin_ice_invoke(_operation, _mode, _inParams, _context).whenCompleted( - (bool ok, byte[] outParams) => + l.ice_invokeAsync(_operation, _mode, _inParams, _context).ContinueWith( + (task) => + { + try { - _amdCB.ice_response(ok, outParams); - }, - (Ice.Exception ex) => + SetResult(task.Result); + } + catch(AggregateException ae) { - exception(ex); - }); - } - catch(Ice.LocalException ex) - { - exception(ex); - } + exception(ae.InnerException); + } + }); } else { @@ -71,7 +65,7 @@ namespace IceLocatorDiscovery } private void - exception(Ice.Exception ex) + exception(Exception ex) { try { @@ -79,25 +73,25 @@ namespace IceLocatorDiscovery } catch(Ice.RequestFailedException exc) { - _amdCB.ice_exception(exc); + SetException(exc); } catch(Ice.UnknownException exc) { - _amdCB.ice_exception(exc); + SetException(exc); } catch(Ice.NoEndpointException) { - _amdCB.ice_exception(new Ice.ObjectNotExistException()); + SetException(new Ice.ObjectNotExistException()); } catch(Ice.ObjectAdapterDeactivatedException) { - _amdCB.ice_exception(new Ice.ObjectNotExistException()); + SetException(new Ice.ObjectNotExistException()); } catch(Ice.CommunicatorDestroyedException) { - _amdCB.ice_exception(new Ice.ObjectNotExistException()); + SetException(new Ice.ObjectNotExistException()); } - catch(Ice.Exception exc) + catch(Exception exc) { _exception = exc; _locator.invoke(_locatorPrx, this); // Retry with new locator proxy @@ -109,24 +103,23 @@ namespace IceLocatorDiscovery private readonly Ice.OperationMode _mode; private readonly Dictionary<string, string> _context; private readonly byte[] _inParams; - private readonly Ice.AMD_Object_ice_invoke _amdCB; private Ice.LocatorPrx _locatorPrx; - private Ice.Exception _exception; + private Exception _exception; } internal class VoidLocatorI : Ice.LocatorDisp_ { - public override void - findObjectById_async(Ice.AMD_Locator_findObjectById amdCB, Ice.Identity id, Ice.Current current) + public override Task<Ice.ObjectPrx> + findObjectByIdAsync(Ice.Identity id, Ice.Current current) { - amdCB.ice_response(null); + return null; } - public override void - findAdapterById_async(Ice.AMD_Locator_findAdapterById amdCB, String id, Ice.Current current) + public override Task<Ice.ObjectPrx> + findAdapterByIdAsync(string id, Ice.Current current) { - amdCB.ice_response(null); + return null; } public override Ice.LocatorRegistryPrx @@ -159,12 +152,14 @@ namespace IceLocatorDiscovery _lookupReply = lookupReply; } - public override void - ice_invoke_async(Ice.AMD_Object_ice_invoke amdCB, byte[] inParams, Ice.Current current) + public override Task<Ice.Object_Ice_invokeResult> + ice_invokeAsync(byte[] inParams, Ice.Current current) { lock(this) { - invoke(null, new Request(this, current.operation, current.mode, inParams, current.ctx, amdCB)); + var request = new Request(this, current.operation, current.mode, inParams, current.ctx); + invoke(null, request); + return request.Task; } } @@ -279,7 +274,7 @@ namespace IceLocatorDiscovery _pendingRetryCount = _retryCount; try { - _lookup.begin_findLocator(_instanceName, _lookupReply); // Send multicast request. + _lookup.findLocatorAsync(_instanceName, _lookupReply); // Send multicast request. _timer.schedule(this, _timeout); } catch(Ice.LocalException) @@ -305,7 +300,7 @@ namespace IceLocatorDiscovery { try { - _lookup.begin_findLocator(_instanceName, _lookupReply); // Send multicast request + _lookup.findLocatorAsync(_instanceName, _lookupReply); // Send multicast request _timer.schedule(this, _timeout); return; } diff --git a/csharp/src/IceLocatorDiscovery/generated/.gitignore b/csharp/src/IceLocatorDiscovery/generated/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/csharp/src/IceLocatorDiscovery/generated/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/csharp/src/IceLocatorDiscovery/msbuild/icelocatordiscovery.csproj b/csharp/src/IceLocatorDiscovery/msbuild/icelocatordiscovery.csproj new file mode 100644 index 00000000000..ba547df8c4b --- /dev/null +++ b/csharp/src/IceLocatorDiscovery/msbuild/icelocatordiscovery.csproj @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{8D8AA726-3A35-407B-BD38-BEA828EEE727}</ProjectGuid> + <OutputType>Library</OutputType> + <AssemblyName>IceLocatorDiscovery</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\Assemblies\IceLocatorDiscovery.XML</DocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\AssemblyInfo.cs"> + <Link>AssemblyInfo.cs</Link> + </Compile> + <Compile Include="..\PluginI.cs"> + <Link>PluginI.cs</Link> + </Compile> + <Compile Include="generated\IceLocatorDiscovery.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\slice\IceLocatorDiscovery\IceLocatorDiscovery.ice"> + <Link>IceLocatorDiscovery.ice</Link> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\Ice\msbuild\ice.csproj"> + <Project>{7cb4715e-dd8b-48f8-b478-27b8bd4008c7}</Project> + <Name>ice</Name> + <Private>False</Private> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\config\ice.sign.targets" /> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/IcePatch2/.depend.mak b/csharp/src/IcePatch2/.depend.mak deleted file mode 100644 index c73ea5657cb..00000000000 --- a/csharp/src/IcePatch2/.depend.mak +++ /dev/null @@ -1,9 +0,0 @@ - -FileInfo.cs: \ - "$(slicedir)\IcePatch2\FileInfo.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -FileServer.cs: \ - "$(slicedir)\IcePatch2\FileServer.ice" \ - "$(slicedir)/IcePatch2/FileInfo.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" diff --git a/csharp/src/IcePatch2/AssemblyInfo.cs b/csharp/src/IcePatch2/AssemblyInfo.cs index 7d095ac1023..6a835824d10 100644 --- a/csharp/src/IcePatch2/AssemblyInfo.cs +++ b/csharp/src/IcePatch2/AssemblyInfo.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/IcePatch2/Makefile b/csharp/src/IcePatch2/Makefile deleted file mode 100644 index de0bd194a64..00000000000 --- a/csharp/src/IcePatch2/Makefile +++ /dev/null @@ -1,47 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -PKG = IcePatch2 -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)/$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs - -SLICE_SRCS = $(SDIR)/FileInfo.ice \ - $(SDIR)/FileServer.ice - -SDIR = $(slicedir)/IcePatch2 -GDIR = generated - -include $(top_srcdir)/config/Make.rules.cs - -MCSFLAGS := $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS := $(MCSFLAGS) -keyfile:$(KEYFILE) -MCSFLAGS := $(MCSFLAGS) /doc:$(assembliesdir)/$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS := $(SLICE2CSFLAGS) -I$(slicedir) --ice - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) $(call ref,Ice) $(subst /,$(DSEP),$^) - -install:: all - (cd $(assembliesdir); $(call installassembly,$(LIBNAME),$(PKG)); $(call installpolicy,$(POLICY)); \ - $(call installmdb,$(LIBNAME).mdb); \ - $(call installdata,$(PKG).xml,$(DESTDIR)$(install_assembliesdir))) - -ifeq ($(GACINSTALL),yes) -install:: all - $(call installdata,../../lib/pkgconfig/$(PKG).pc,$(DESTDIR)$(install_pkgconfigdir)) -endif - -clean:: - -rm -f $(assembliesdir)/$(PKG).xml diff --git a/csharp/src/IcePatch2/Makefile.mak b/csharp/src/IcePatch2/Makefile.mak deleted file mode 100644 index 4fbff927dac..00000000000 --- a/csharp/src/IcePatch2/Makefile.mak +++ /dev/null @@ -1,54 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -PKG = IcePatch2 -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)\$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs - -GEN_SRCS = $(GDIR)\FileInfo.cs \ - $(GDIR)\FileServer.cs - -SDIR = $(slicedir)\IcePatch2 -GDIR = generated - -!include $(top_srcdir)\config\Make.rules.mak.cs - -MCSFLAGS = $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS = $(MCSFLAGS) -keyfile:"$(KEYFILE)" -MCSFLAGS = $(MCSFLAGS) /doc:$(assembliesdir)\$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS = $(SLICE2CSFLAGS) -I$(slicedir) --ice - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) /baseaddress:0x23000000 $(MCSFLAGS) -r:$(refdir)\Ice.dll $(SRCS) $(GEN_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -!if "$(DEBUG)" == "yes" -clean:: - del /q $(assembliesdir)\$(PKG).pdb -!endif - -clean:: - del /q $(assembliesdir)\$(PKG).xml - -install:: all - copy $(assembliesdir)\$(LIBNAME) "$(install_assembliesdir)" - copy $(assembliesdir)\$(PKG).xml "$(install_assembliesdir)" -!if "$(generate_policies)" == "yes" - copy $(assembliesdir)\$(POLICY_TARGET) "$(install_assembliesdir)" -!endif -!if "$(DEBUG)" == "yes" - copy $(assembliesdir)\$(PKG).pdb "$(install_assembliesdir)" -!endif diff --git a/csharp/src/IcePatch2/generated/.gitignore b/csharp/src/IcePatch2/generated/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/csharp/src/IcePatch2/generated/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/csharp/src/IcePatch2/msbuild/icepatch2.csproj b/csharp/src/IcePatch2/msbuild/icepatch2.csproj new file mode 100644 index 00000000000..03fd874c9b7 --- /dev/null +++ b/csharp/src/IcePatch2/msbuild/icepatch2.csproj @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{6479EE9D-5730-44BC-B564-97211E1B54C5}</ProjectGuid> + <OutputType>Library</OutputType> + <AssemblyName>IcePatch2</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\Assemblies\IcePatch2.XML</DocumentationFile> + <NoWarn>1591;618</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\AssemblyInfo.cs"> + <Link>AssemblyInfo.cs</Link> + </Compile> + <Compile Include="generated\FileInfo.cs" /> + <Compile Include="generated\FileServer.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\slice\IcePatch2\FileInfo.ice"> + <Link>FileInfo.ice</Link> + </None> + <None Include="..\..\..\..\slice\IcePatch2\FileServer.ice"> + <Link>FileServer.ice</Link> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\Ice\msbuild\ice.csproj"> + <Project>{7cb4715e-dd8b-48f8-b478-27b8bd4008c7}</Project> + <Name>ice</Name> + <Private>False</Private> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\config\ice.sign.targets" /> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/IceSSL/.depend.mak b/csharp/src/IceSSL/.depend.mak deleted file mode 100644 index 96f75256468..00000000000 --- a/csharp/src/IceSSL/.depend.mak +++ /dev/null @@ -1,17 +0,0 @@ - -ConnectionInfo.cs: \ - "$(slicedir)\IceSSL\ConnectionInfo.ice" \ - "$(slicedir)/Ice/Connection.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Endpoint.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/EndpointF.ice" - -EndpointInfo.cs: \ - "$(slicedir)\IceSSL\EndpointInfo.ice" \ - "$(slicedir)/Ice/Endpoint.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/EndpointF.ice" diff --git a/csharp/src/IceSSL/AcceptorI.cs b/csharp/src/IceSSL/AcceptorI.cs index afffc1f9512..9315a32c7fb 100644 --- a/csharp/src/IceSSL/AcceptorI.cs +++ b/csharp/src/IceSSL/AcceptorI.cs @@ -9,41 +9,16 @@ namespace IceSSL { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.IO; - using System.Net; - using System.Net.Security; - using System.Net.Sockets; - using System.Security.Cryptography.X509Certificates; - using System.Text; - class AcceptorI : IceInternal.Acceptor { public void close() { - Debug.Assert(_acceptFd == null); - if(_fd != null) - { - IceInternal.Network.closeSocketNoThrow(_fd); - _fd = null; - } + _delegate.close(); } public IceInternal.EndpointI listen() { - try - { - _addr = IceInternal.Network.doBind(_fd, _addr); - IceInternal.Network.doListen(_fd, _backlog); - } - catch(SystemException) - { - _fd = null; - throw; - } - _endpoint = _endpoint.endpoint(this); + _endpoint = _endpoint.endpoint(_delegate.listen()); return _endpoint; } @@ -58,144 +33,55 @@ namespace IceSSL ex.reason = "IceSSL: plug-in is not initialized"; throw ex; } - - try - { - _result = _fd.BeginAccept(delegate(IAsyncResult result) - { - if(!result.CompletedSynchronously) - { - callback(result.AsyncState); - } - }, state); - return _result.CompletedSynchronously; - } - catch(SocketException ex) - { - throw new Ice.SocketException(ex); - } + return _delegate.startAccept(callback, state); } public void finishAccept() { - if(_fd != null) - { - Debug.Assert(_result != null); - try - { - _acceptFd = _fd.EndAccept(_result); - _result = null; - } - catch(SocketException ex) - { - _acceptError = ex; - } - } + _delegate.finishAccept(); } public IceInternal.Transceiver accept() { - if(_acceptFd == null) - { - throw _acceptError; - } - - Socket acceptFd = _acceptFd; - _acceptFd = null; - _acceptError = null; - return new TransceiverI(_instance, new IceInternal.StreamSocket(_instance, acceptFd), _adapterName, true); + return new TransceiverI(_instance, _delegate.accept(), _adapterName, true); } public string protocol() { - return _instance.protocol(); + return _delegate.protocol(); } public override string ToString() { - return IceInternal.Network.addrToString(_addr); + return _delegate.ToString(); } public string toDetailedString() { - StringBuilder s = new StringBuilder("local address = "); - s.Append(ToString()); - - List<string> intfs = IceInternal.Network.getHostsForEndpointExpand(_addr.Address.ToString(), - _instance.protocolSupport(), - true); - if(intfs.Count != 0) - { - s.Append("\nlocal interfaces = "); - s.Append(String.Join(", ", intfs.ToArray())); - } - return s.ToString(); - } - - internal int effectivePort() - { - return _addr.Port; + return _delegate.toDetailedString(); } - internal AcceptorI(EndpointI endpoint, Instance instance, string adapterName, string host, int port) + internal AcceptorI(EndpointI endpoint, Instance instance, IceInternal.Acceptor del, string adapterName) { _endpoint = endpoint; + _delegate = del; _instance = instance; _adapterName = adapterName; - _backlog = instance.properties().getPropertyAsIntWithDefault("Ice.TCP.Backlog", 511); // // .NET requires that a certificate be supplied. // - X509Certificate2Collection certs = instance.certs(); - if(certs.Count == 0) + if(instance.certs().Count == 0) { Ice.SecurityException ex = new Ice.SecurityException(); ex.reason = "IceSSL: certificate required for server endpoint"; throw ex; } - - try - { - int protocol = instance.protocolSupport(); - _addr = IceInternal.Network.getAddressForServer(host, port, protocol, instance.preferIPv6()) as - IPEndPoint; - _fd = IceInternal.Network.createServerSocket(false, _addr.AddressFamily, protocol); - IceInternal.Network.setBlock(_fd, false); - IceInternal.Network.setTcpBufSize(_fd, _instance); - if(IceInternal.AssemblyUtil.platform_ != IceInternal.AssemblyUtil.Platform.Windows) - { - // - // Enable SO_REUSEADDR on Unix platforms to allow - // re-using the socket even if it's in the TIME_WAIT - // state. On Windows, this doesn't appear to be - // necessary and enabling SO_REUSEADDR would actually - // not be a good thing since it allows a second - // process to bind to an address even it's already - // bound by another process. - // - // TODO: using SO_EXCLUSIVEADDRUSE on Windows would - // probably be better but it's only supported by recent - // Windows versions (XP SP2, Windows Server 2003). - // - IceInternal.Network.setReuseAddress(_fd, true); - } - } - catch(System.Exception) - { - _fd = null; - throw; - } } private EndpointI _endpoint; + private IceInternal.Acceptor _delegate; private Instance _instance; private string _adapterName; - private Socket _fd; - private Socket _acceptFd; - private System.Exception _acceptError; - private int _backlog; - private IPEndPoint _addr; - private IAsyncResult _result; } } diff --git a/csharp/src/IceSSL/AssemblyInfo.cs b/csharp/src/IceSSL/AssemblyInfo.cs index 237f7bb8ffe..800e0715334 100644 --- a/csharp/src/IceSSL/AssemblyInfo.cs +++ b/csharp/src/IceSSL/AssemblyInfo.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/IceSSL/ConnectorI.cs b/csharp/src/IceSSL/ConnectorI.cs index d68762b18bf..213941e991e 100644 --- a/csharp/src/IceSSL/ConnectorI.cs +++ b/csharp/src/IceSSL/ConnectorI.cs @@ -29,37 +29,22 @@ namespace IceSSL throw ex; } - return new TransceiverI(_instance, new IceInternal.StreamSocket(_instance, _proxy, _addr, _sourceAddr), - _host, false); + return new TransceiverI(_instance, _delegate.connect(), _host, false); } public short type() { - return _instance.type(); + return _delegate.type(); } // // Only for use by EndpointI. // - internal ConnectorI(Instance instance, string host, EndPoint addr, IceInternal.NetworkProxy proxy, - EndPoint sourceAddr, int timeout, string conId) + internal ConnectorI(Instance instance, IceInternal.Connector del, string host) { _instance = instance; + _delegate = del; _host = host; - _addr = (IPEndPoint)addr; - _proxy = proxy; - _sourceAddr = sourceAddr; - _timeout = timeout; - _connectionId = conId; - - _hashCode = 5381; - IceInternal.HashUtil.hashAdd(ref _hashCode, _addr); - if(_sourceAddr != null) - { - IceInternal.HashUtil.hashAdd(ref _hashCode, _sourceAddr); - } - IceInternal.HashUtil.hashAdd(ref _hashCode, _timeout); - IceInternal.HashUtil.hashAdd(ref _hashCode, _connectionId); } public override bool Equals(object obj) @@ -75,41 +60,21 @@ namespace IceSSL } ConnectorI p = (ConnectorI)obj; - if(_timeout != p._timeout) - { - return false; - } - - if(!_connectionId.Equals(p._connectionId)) - { - return false; - } - - if(!IceInternal.Network.addressEquals(_sourceAddr, p._sourceAddr)) - { - return false; - } - - return _addr.Equals(p._addr); + return _delegate.Equals(p._delegate); } public override string ToString() { - return IceInternal.Network.addrToString(_proxy == null ? _addr : _proxy.getAddress()); + return _delegate.ToString(); } public override int GetHashCode() { - return _hashCode; + return _delegate.GetHashCode(); } private Instance _instance; + private IceInternal.Connector _delegate; private string _host; - private IPEndPoint _addr; - private IceInternal.NetworkProxy _proxy; - private EndPoint _sourceAddr; - private int _timeout; - private string _connectionId; - private int _hashCode; } } diff --git a/csharp/src/IceSSL/EndpointI.cs b/csharp/src/IceSSL/EndpointI.cs index 47a82f1b5e6..52bf89e712f 100644 --- a/csharp/src/IceSSL/EndpointI.cs +++ b/csharp/src/IceSSL/EndpointI.cs @@ -9,39 +9,22 @@ namespace IceSSL { - using System; - using System.Diagnostics; using System.Collections.Generic; - using System.Net; - using System.Globalization; - sealed class EndpointI : IceInternal.IPEndpointI, IceInternal.WSEndpointDelegate + sealed class EndpointI : IceInternal.EndpointI { - internal EndpointI(Instance instance, string ho, int po, EndPoint sourceAddr, int ti, string conId, bool co) : - base(instance, ho, po, sourceAddr, conId) + internal EndpointI(Instance instance, IceInternal.EndpointI del) { _instance = instance; - _timeout = ti; - _compress = co; + _delegate = del; } - internal EndpointI(Instance instance) : - base(instance) + public override void streamWriteImpl(Ice.OutputStream os) { - _instance = instance; - _timeout = instance.defaultTimeout(); - _compress = false; - } - - internal EndpointI(Instance instance, IceInternal.BasicStream s) : - base(instance, s) - { - _instance = instance; - _timeout = s.readInt(); - _compress = s.readBool(); + _delegate.streamWriteImpl(os); } - private sealed class InfoI : IceSSL.EndpointInfo + private sealed class InfoI : EndpointInfo { public InfoI(EndpointI e) { @@ -66,341 +49,245 @@ namespace IceSSL private EndpointI _endpoint; } - // - // Return the endpoint information. - // public override Ice.EndpointInfo getInfo() { InfoI info = new InfoI(this); - fillEndpointInfo(info); + info.underlying = _delegate.getInfo(); + info.compress = info.underlying.compress; + info.timeout = info.underlying.timeout; return info; } - private sealed class WSSInfoI : IceSSL.WSSEndpointInfo + public override short type() { - public WSSInfoI(EndpointI e) - { - _endpoint = e; - } - - override public short type() - { - return _endpoint.type(); - } - - override public bool datagram() - { - return _endpoint.datagram(); - } - - override public bool secure() - { - return _endpoint.secure(); - } - - private EndpointI _endpoint; + return _delegate.type(); } - // - // Return the endpoint information. - // - public Ice.EndpointInfo getWSInfo(string resource) + public override string protocol() { - WSSInfoI info = new WSSInfoI(this); - fillEndpointInfo(info); - info.resource = resource; - return info; + return _delegate.protocol(); } - // - // Return the timeout for the endpoint in milliseconds. 0 means - // non-blocking, -1 means no timeout. - // public override int timeout() { - return _timeout; + return _delegate.timeout(); } - // - // Return a new endpoint with a different timeout value, provided - // that timeouts are supported by the endpoint. Otherwise the same - // endpoint is returned. - // public override IceInternal.EndpointI timeout(int timeout) { - if(timeout == _timeout) + if(timeout == _delegate.timeout()) { return this; } else { - return new EndpointI(_instance, host_, port_, sourceAddr_, timeout, connectionId_, _compress); + return new EndpointI(_instance, _delegate.timeout(timeout)); } } - // - // Return true if the endpoints support bzip2 compress, or false - // otherwise. - // - public override bool compress() + public override string connectionId() { - return _compress; + return _delegate.connectionId(); } - // - // Return a new endpoint with a different compression value, - // provided that compression is supported by the - // endpoint. Otherwise the same endpoint is returned. - // - public override IceInternal.EndpointI compress(bool compress) + public override IceInternal.EndpointI connectionId(string connectionId) { - if(compress == _compress) + if(connectionId.Equals(_delegate.connectionId())) { return this; } else { - return new EndpointI(_instance, host_, port_, sourceAddr_, _timeout, connectionId_, compress); + return new EndpointI(_instance, _delegate.connectionId(connectionId)); } } - // - // Return true if the endpoint is datagram-based. - // - public override bool datagram() + public override bool compress() { - return false; + return _delegate.compress(); } - // - // Return a server side transceiver for this endpoint, or null if a - // transceiver can only be created by an acceptor. - // - public override IceInternal.Transceiver transceiver() + public override IceInternal.EndpointI compress(bool compress) { - return null; + if(compress == _delegate.compress()) + { + return this; + } + else + { + return new EndpointI(_instance, _delegate.compress(compress)); + } } - // - // Return an acceptor for this endpoint, or null if no acceptor - // is available. - // - public override IceInternal.Acceptor acceptor(string adapterName) + public override bool datagram() { - return new AcceptorI(this, _instance, adapterName, host_, port_); + return _delegate.datagram(); } - public EndpointI endpoint(AcceptorI acceptor) + public override bool secure() { - return new EndpointI(_instance, host_, acceptor.effectivePort(), sourceAddr_, _timeout, connectionId_, - _compress); + return _delegate.secure(); } - public override string options() + public override IceInternal.Transceiver transceiver() { - // - // WARNING: Certain features, such as proxy validation in Glacier2, - // depend on the format of proxy strings. Changes to toString() and - // methods called to generate parts of the reference string could break - // these features. Please review for all features that depend on the - // format of proxyToString() before changing this and related code. - // - string s = base.options(); - - if(_timeout == -1) - { - s += " -t infinite"; - } - else - { - s += " -t " + _timeout; - } - - if(_compress) - { - s += " -z"; - } - - return s; + return null; } - // - // Compare endpoints for sorting purposes - // - public override int CompareTo(IceInternal.EndpointI obj) + private sealed class EndpointI_connectorsI : IceInternal.EndpointI_connectors { - if(!(obj is EndpointI)) + public EndpointI_connectorsI(Instance instance, string host, IceInternal.EndpointI_connectors cb) { - return type() < obj.type() ? -1 : 1; + _instance = instance; + _host = host; + _callback = cb; } - EndpointI p = (EndpointI)obj; - if(this == p) + public void connectors(List<IceInternal.Connector> connectors) { - return 0; - } - - if(_timeout < p._timeout) - { - return -1; - } - else if(p._timeout < _timeout) - { - return 1; + List<IceInternal.Connector> l = new List<IceInternal.Connector>(); + foreach(IceInternal.Connector c in connectors) + { + l.Add(new ConnectorI(_instance, c, _host)); + } + _callback.connectors(l); } - if(!_compress && p._compress) - { - return -1; - } - else if(!p._compress && _compress) + public void exception(Ice.LocalException ex) { - return 1; + _callback.exception(ex); } - return base.CompareTo(p); + private Instance _instance; + private string _host; + private IceInternal.EndpointI_connectors _callback; } - public override void streamWriteImpl(IceInternal.BasicStream s) + public override void connectors_async(Ice.EndpointSelectionType selType, + IceInternal.EndpointI_connectors callback) { - base.streamWriteImpl(s); - s.writeInt(_timeout); - s.writeBool(_compress); + string host = ""; + for(Ice.EndpointInfo p = _delegate.getInfo(); p != null; p = p.underlying) + { + if(p is Ice.IPEndpointInfo) + { + host = ((Ice.IPEndpointInfo)p).host; + break; + } + } + _delegate.connectors_async(selType, new EndpointI_connectorsI(_instance, host, callback)); } - public override void hashInit(ref int h) + public override IceInternal.Acceptor acceptor(string adapterName) { - base.hashInit(ref h); - IceInternal.HashUtil.hashAdd(ref h, _timeout); - IceInternal.HashUtil.hashAdd(ref h, _compress); + return new AcceptorI(this, _instance, _delegate.acceptor(adapterName), adapterName); } - public override void fillEndpointInfo(Ice.IPEndpointInfo info) + public EndpointI endpoint(IceInternal.EndpointI del) { - base.fillEndpointInfo(info); - info.timeout = _timeout; - info.compress = _compress; + return new EndpointI(_instance, del); } - protected override bool checkOption(string option, string argument, string endpoint) + public override List<IceInternal.EndpointI> expand() { - if(base.checkOption(option, argument, endpoint)) + List<IceInternal.EndpointI> l = new List<IceInternal.EndpointI>(); + foreach(IceInternal.EndpointI e in _delegate.expand()) { - return true; + l.Add(e == _delegate ? this : new EndpointI(_instance, e)); } + return l; + } - switch(option[1]) - { - case 't': + public override bool equivalent(IceInternal.EndpointI endpoint) + { + if(!(endpoint is EndpointI)) { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "no argument provided for -t option in endpoint " + endpoint; - throw e; - } - - if(argument.Equals("infinite")) - { - _timeout = -1; - } - else - { - try - { - _timeout = System.Int32.Parse(argument, CultureInfo.InvariantCulture); - if(_timeout < 1) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "invalid timeout value `" + argument + "' in endpoint " + endpoint; - throw e; - } - } - catch(System.FormatException ex) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(ex); - e.str = "invalid timeout value `" + argument + "' in endpoint " + endpoint; - throw e; - } - } - - return true; + return false; } + EndpointI endpointI = (EndpointI)endpoint; + return _delegate.equivalent(endpointI._delegate); + } - case 'z': - { - if(argument != null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "unexpected argument `" + argument + "' provided for -z option in " + endpoint; - throw e; - } + public override string options() + { + return _delegate.options(); + } - _compress = true; - return true; + // + // Compare endpoints for sorting purposes + // + public override int CompareTo(IceInternal.EndpointI obj) + { + if(!(obj is EndpointI)) + { + return type() < obj.type() ? -1 : 1; } - default: + EndpointI p = (EndpointI)obj; + if(this == p) { - return false; - } + return 0; } + + return _delegate.CompareTo(p._delegate); } - protected override IceInternal.Connector createConnector(EndPoint addr, IceInternal.NetworkProxy proxy) + public override int GetHashCode() { - return new ConnectorI(_instance, host_, addr, proxy, sourceAddr_, _timeout, connectionId_); + return _delegate.GetHashCode(); } - protected override IceInternal.IPEndpointI createEndpoint(string host, int port, string connectionId) + protected override bool checkOption(string option, string argument, string endpoint) { - return new EndpointI(_instance, host, port, sourceAddr_, _timeout, connectionId, _compress); + return false; } private Instance _instance; - private int _timeout; - private bool _compress; + private IceInternal.EndpointI _delegate; } internal sealed class EndpointFactoryI : IceInternal.EndpointFactory { - internal EndpointFactoryI(Instance instance) + internal EndpointFactoryI(Instance instance, IceInternal.EndpointFactory del) { _instance = instance; + _delegate = del; } public short type() { - return _instance.type(); + return _delegate.type(); } public string protocol() { - return _instance.protocol(); + return _delegate.protocol(); } public IceInternal.EndpointI create(List<string> args, bool oaEndpoint) { - IceInternal.IPEndpointI endpt = new EndpointI(_instance); - endpt.initWithOptions(args, oaEndpoint); - return endpt; + return new EndpointI(_instance, _delegate.create(args, oaEndpoint)); } - public IceInternal.EndpointI read(IceInternal.BasicStream s) + public IceInternal.EndpointI read(Ice.InputStream s) { - return new EndpointI(_instance, s); + return new EndpointI(_instance, _delegate.read(s)); } public void destroy() { + _delegate.destroy(); _instance = null; } - public IceInternal.EndpointFactory clone(IceInternal.ProtocolInstance instance) + public IceInternal.EndpointFactory clone(IceInternal.ProtocolInstance inst, + IceInternal.EndpointFactory del) { - return new EndpointFactoryI(new Instance(_instance.engine(), instance.type(), instance.protocol())); + Instance instance = new Instance(_instance.engine(), inst.type(), inst.protocol()); + return new EndpointFactoryI(instance, del != null ? del : _delegate.clone(instance, null)); } private Instance _instance; + private IceInternal.EndpointFactory _delegate; } } diff --git a/csharp/src/IceSSL/Instance.cs b/csharp/src/IceSSL/Instance.cs index 40b3b146b40..de4804443d2 100644 --- a/csharp/src/IceSSL/Instance.cs +++ b/csharp/src/IceSSL/Instance.cs @@ -9,16 +9,8 @@ namespace IceSSL { - using System; - using System.Collections; - using System.Collections.Generic; - using System.IO; - using System.Security; using System.Security.Authentication; - using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; - using System.Text; - using System.Globalization; internal class Instance : IceInternal.ProtocolInstance { @@ -68,9 +60,9 @@ namespace IceSSL _engine.traceStream(stream, connInfo); } - internal void verifyPeer(NativeConnectionInfo info, System.Net.Sockets.Socket fd, string address) + internal void verifyPeer(string address, NativeConnectionInfo info, string desc) { - _engine.verifyPeer(info, fd, address); + _engine.verifyPeer(address, info, desc); } private SSLEngine _engine; diff --git a/csharp/src/IceSSL/Makefile b/csharp/src/IceSSL/Makefile deleted file mode 100644 index 7ac75792be3..00000000000 --- a/csharp/src/IceSSL/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -PKG = IceSSL -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)/$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AcceptorI.cs \ - AssemblyInfo.cs \ - ConnectorI.cs \ - EndpointI.cs \ - Instance.cs \ - Plugin.cs \ - PluginI.cs \ - RFC2253.cs \ - SSLEngine.cs \ - TransceiverI.cs \ - TrustManager.cs \ - Util.cs - -SLICE_SRCS = $(SDIR)/ConnectionInfo.ice \ - $(SDIR)/EndpointInfo.ice - - -SDIR = $(slicedir)/IceSSL -GDIR = generated - -include $(top_srcdir)/config/Make.rules.cs - -MCSFLAGS := $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS := $(MCSFLAGS) -keyfile:$(KEYFILE) -MCSFLAGS := $(MCSFLAGS) /doc:$(assembliesdir)/$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS := $(SLICE2CSFLAGS) --ice -I$(slicedir) - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) $(call ref,Ice) $(subst /,$(DSEP),$^) - -install:: all - (cd $(assembliesdir); $(call installassembly,$(LIBNAME),$(PKG)); $(call installpolicy,$(POLICY)); \ - $(call installmdb,$(LIBNAME).mdb); \ - $(call installdata,$(PKG).xml,$(DESTDIR)$(install_assembliesdir))) - -ifeq ($(GACINSTALL),yes) -install:: all - $(call installdata,../../lib/pkgconfig/$(PKG).pc,$(DESTDIR)$(install_pkgconfigdir)) -endif - -clean:: - -rm -f $(assembliesdir)/$(PKG).xml diff --git a/csharp/src/IceSSL/Makefile.mak b/csharp/src/IceSSL/Makefile.mak deleted file mode 100644 index 8d2cb40cfff..00000000000 --- a/csharp/src/IceSSL/Makefile.mak +++ /dev/null @@ -1,66 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -PKG = IceSSL -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)\$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AcceptorI.cs \ - AssemblyInfo.cs \ - ConnectorI.cs \ - EndpointI.cs \ - Instance.cs \ - Plugin.cs \ - PluginI.cs \ - RFC2253.cs \ - SSLEngine.cs \ - TransceiverI.cs \ - TrustManager.cs \ - Util.cs - -GEN_SRCS = $(GDIR)\ConnectionInfo.cs\ - $(GDIR)\EndpointInfo.cs - - -SDIR = $(slicedir)\IceSSL -GDIR = generated - -!include $(top_srcdir)\config\Make.rules.mak.cs - -MCSFLAGS = $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS = $(MCSFLAGS) -keyfile:"$(KEYFILE)" -MCSFLAGS = $(MCSFLAGS) /doc:$(assembliesdir)\$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS = $(SLICE2CSFLAGS) --ice -I$(slicedir) - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) -r:$(refdir)\Ice.dll $(SRCS) $(GEN_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -!if "$(DEBUG)" == "yes" -clean:: - del /q $(assembliesdir)\$(PKG).pdb -!endif - -clean:: - del /q $(assembliesdir)\$(PKG).xml - -install:: all - copy $(assembliesdir)\$(LIBNAME) "$(install_assembliesdir)" - copy $(assembliesdir)\$(PKG).xml "$(install_assembliesdir)" -!if "$(generate_policies)" == "yes" - copy $(assembliesdir)\$(POLICY_TARGET) "$(install_assembliesdir)" -!endif -!if "$(DEBUG)" == "yes" - copy $(assembliesdir)\$(PKG).pdb "$(install_assembliesdir)" -!endif diff --git a/csharp/src/IceSSL/PluginI.cs b/csharp/src/IceSSL/PluginI.cs index abc9ef326d2..f4d205e4c83 100644 --- a/csharp/src/IceSSL/PluginI.cs +++ b/csharp/src/IceSSL/PluginI.cs @@ -41,12 +41,14 @@ namespace IceSSL _engine = new SSLEngine(facade); // - // Register the endpoint factory. We have to do this now, rather than - // in initialize, because the communicator may need to interpret - // proxies before the plug-in is fully initialized. + // SSL based on TCP // - EndpointFactoryI factory = new EndpointFactoryI(new Instance(_engine, IceSSL.EndpointType.value, "ssl")); - facade.addEndpointFactory(factory); + IceInternal.EndpointFactory tcp = facade.getEndpointFactory(Ice.TCPEndpointType.value); + if(tcp != null) + { + Instance instance = new Instance(_engine, Ice.SSLEndpointType.value, "ssl"); + facade.addEndpointFactory(new EndpointFactoryI(instance, tcp.clone(instance, null))); + } } public override void initialize() diff --git a/csharp/src/IceSSL/RFC2253.cs b/csharp/src/IceSSL/RFC2253.cs index ac0adaf64f4..ae81e35af75 100644 --- a/csharp/src/IceSSL/RFC2253.cs +++ b/csharp/src/IceSSL/RFC2253.cs @@ -13,14 +13,13 @@ namespace IceSSL { using System; - using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; class RFC2253 { - internal class ParseException : System.Exception + internal class ParseException : Exception { internal ParseException() { @@ -32,9 +31,9 @@ namespace IceSSL } internal string - ice_name() + ice_id() { - return "RFC2253::ParseException"; + return "::RFC2253::ParseException"; } internal string reason; @@ -276,11 +275,11 @@ namespace IceSSL // // First the OID case. // - if(Char.IsDigit(data[pos]) || + if(char.IsDigit(data[pos]) || (data.Length - pos >= 4 && (data.Substring(pos, 4).Equals("oid.") || data.Substring(pos, 4).Equals("OID.")))) { - if(!Char.IsDigit(data[pos])) + if(!char.IsDigit(data[pos])) { result += data.Substring(pos, 4); pos += 4; @@ -289,7 +288,7 @@ namespace IceSSL while(true) { // 1*DIGIT - while(pos < data.Length && Char.IsDigit(data[pos])) + while(pos < data.Length && char.IsDigit(data[pos])) { result += data[pos]; ++pos; @@ -300,7 +299,7 @@ namespace IceSSL result += data[pos]; ++pos; // 1*DIGIT must follow "." - if(pos < data.Length && !Char.IsDigit(data[pos])) + if(pos < data.Length && !char.IsDigit(data[pos])) { throw new ParseException("invalid attribute type (expected end of data)"); } @@ -311,7 +310,7 @@ namespace IceSSL } } } - else if(Char.IsUpper(data[pos]) || Char.IsLower(data[pos])) + else if(char.IsUpper(data[pos]) || char.IsLower(data[pos])) { // // The grammar is wrong in this case. It should be ALPHA @@ -322,9 +321,9 @@ namespace IceSSL ++pos; // 1* KEYCHAR while(pos < data.Length && - (Char.IsDigit(data[pos]) || - Char.IsUpper(data[pos]) || - Char.IsLower(data[pos]) || + (char.IsDigit(data[pos]) || + char.IsUpper(data[pos]) || + char.IsLower(data[pos]) || data[pos] == '-')) { result += data[pos]; diff --git a/csharp/src/IceSSL/SSLEngine.cs b/csharp/src/IceSSL/SSLEngine.cs index cdf214f9426..6e2fe6d954f 100644 --- a/csharp/src/IceSSL/SSLEngine.cs +++ b/csharp/src/IceSSL/SSLEngine.cs @@ -10,7 +10,6 @@ namespace IceSSL { using System; - using System.Collections; using System.Collections.Generic; using System.IO; using System.Security; @@ -31,18 +30,6 @@ namespace IceSSL _securityTraceCategory = "Security"; _initialized = false; _trustManager = new TrustManager(_communicator); - -#if !UNITY - _tls12Support = false; - try - { - Enum.Parse(typeof(System.Security.Authentication.SslProtocols), "Tls12"); - _tls12Support = true; - } - catch(Exception) - { - } -#endif } internal void initialize() @@ -79,71 +66,12 @@ namespace IceSSL } _useMachineContext = certStoreLocation == "LocalMachine"; -#if !UNITY - X509KeyStorageFlags keyStorageFlags; - if(_useMachineContext) - { - keyStorageFlags = X509KeyStorageFlags.MachineKeySet; - } - else - { - keyStorageFlags = X509KeyStorageFlags.UserKeySet; - } - - string keySet = properties.getProperty(prefix + "KeySet"); // Deprecated property - if(keySet.Length > 0) - { - if(keySet.Equals("DefaultKeySet")) - { - keyStorageFlags = X509KeyStorageFlags.DefaultKeySet; - } - else if(keySet.Equals("UserKeySet")) - { - keyStorageFlags = X509KeyStorageFlags.UserKeySet; - } - else if(keySet.Equals("MachineKeySet")) - { - keyStorageFlags = X509KeyStorageFlags.MachineKeySet; - } - else - { - _logger.warning("Invalid IceSSL.KeySet value `" + keySet + "' adjusted to `DefaultKeySet'"); - keyStorageFlags = X509KeyStorageFlags.DefaultKeySet; - } - } - - if(properties.getPropertyAsIntWithDefault(prefix + "PersistKeySet", 0) > 0) // Deprecated property - { - keyStorageFlags |= X509KeyStorageFlags.PersistKeySet; - } - - // - // Process IceSSL.ImportCert.* properties. - // - Dictionary<string, string> certs = properties.getPropertiesForPrefix(prefix + "ImportCert."); - foreach(KeyValuePair<string, string> entry in certs) - { - string name = entry.Key; - string val = entry.Value; - if(val.Length > 0) - { - importCertificate(name, val, keyStorageFlags); - } - } -#endif - // // Protocols selects which protocols to enable, by default we only enable TLS1.0 // TLS1.1 and TLS1.2 to avoid security issues with SSLv3 // _protocols = parseProtocols( - properties.getPropertyAsListWithDefault(prefix + "Protocols", -#if UNITY - new string[]{"TLS1_0"})); -#else - _tls12Support ? new string[]{"TLS1_0", "TLS1_1", "TLS1_2"} : - new string[]{"TLS1_0", "TLS1_1"})); -#endif + properties.getPropertyAsListWithDefault(prefix + "Protocols", new string[]{"TLS1_0", "TLS1_1", "TLS1_2"})); // // CheckCertName determines whether we compare the name in a peer's // certificate against its hostname. @@ -162,7 +90,6 @@ namespace IceSSL // _checkCRL = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0); -#if !UNITY // // Check for a certificate verifier. // @@ -433,8 +360,6 @@ namespace IceSSL } } } -#endif - _initialized = true; } @@ -540,16 +465,14 @@ namespace IceSSL s.Append("\nencrypted = " + (stream.IsEncrypted ? "yes" : "no")); s.Append("\nsigned = " + (stream.IsSigned ? "yes" : "no")); s.Append("\nmutually authenticated = " + (stream.IsMutuallyAuthenticated ? "yes" : "no")); -#if !UNITY s.Append("\nhash algorithm = " + stream.HashAlgorithm + "/" + stream.HashStrength); s.Append("\ncipher algorithm = " + stream.CipherAlgorithm + "/" + stream.CipherStrength); s.Append("\nkey exchange algorithm = " + stream.KeyExchangeAlgorithm + "/" + stream.KeyExchangeStrength); s.Append("\nprotocol = " + stream.SslProtocol); -#endif _logger.trace(_securityTraceCategory, s.ToString()); } - internal void verifyPeer(NativeConnectionInfo info, System.Net.Sockets.Socket fd, string address) + internal void verifyPeer(string address, NativeConnectionInfo info, string desc) { // // For an outgoing connection, we compare the proxy address (if any) against @@ -747,8 +670,7 @@ namespace IceSSL { string msg = (info.incoming ? "incoming" : "outgoing") + " connection rejected:\n" + "length of peer's certificate chain (" + info.nativeCerts.Length + ") exceeds maximum of " + - _verifyDepthMax + "\n" + - IceInternal.Network.fdToString(fd); + _verifyDepthMax + "\n" + desc; if(_securityTraceLevel >= 1) { _logger.trace(_securityTraceCategory, msg); @@ -758,10 +680,10 @@ namespace IceSSL throw ex; } - if(!_trustManager.verify(info)) + if(!_trustManager.verify(info, desc)) { string msg = (info.incoming ? "incoming" : "outgoing") + " connection rejected by trust manager\n" + - IceInternal.Network.fdToString(fd); + desc; if(_securityTraceLevel >= 1) { _logger.trace(_securityTraceCategory, msg); @@ -775,7 +697,7 @@ namespace IceSSL if(_verifier != null && !_verifier.verify(info)) { string msg = (info.incoming ? "incoming" : "outgoing") + - " connection rejected by certificate verifier\n" + IceInternal.Network.fdToString(fd); + " connection rejected by certificate verifier\n" + desc; if(_securityTraceLevel >= 1) { _logger.trace(_securityTraceCategory, msg); @@ -888,177 +810,6 @@ namespace IceSSL return false; } -#if !UNITY - private void importCertificate(string propName, string propValue, X509KeyStorageFlags keyStorageFlags) - { - // - // Expecting a property of the following form: - // - // IceSSL.ImportCert.<location>.<name>=<file>[;password] - // - const string prefix = "IceSSL.ImportCert."; - StoreLocation loc = 0; - StoreName name = 0; - string sname = null; - parseStore(propName, propName.Substring(prefix.Length), ref loc, ref name, ref sname); - - // - // Extract the filename and password. Either or both can be quoted. - // - string[] arr = splitString(propValue, ';'); - if(arr == null) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: unmatched quote in `" + propValue + "'"; - throw e; - } - if(arr.Length == 0) - { - return; - } - string file = arr[0]; - string passwordStr = null; - if(arr.Length > 1) - { - passwordStr = arr[1]; - } - - // - // Open the X509 certificate store. - // - X509Store store = null; - try - { - if(sname != null) - { - store = new X509Store(sname, loc); - } - else - { - store = new X509Store(name, loc); - } - store.Open(OpenFlags.ReadWrite); - } - catch(Exception ex) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); - e.reason = "IceSSL: failure while opening store specified by " + propName; - throw e; - } - - if(!checkPath(ref file)) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: certificate file not found:\n" + file; - throw e; - } - - SecureString password = null; - if(passwordStr != null) - { - password = createSecureString(passwordStr); - } - else if(_passwordCallback != null) - { - password = _passwordCallback.getImportPassword(file); - } - - // - // Add the certificate to the store. - // - try - { - X509Certificate2 cert; - if(password != null) - { - cert = new X509Certificate2(file, password, keyStorageFlags); - } - else - { - cert = new X509Certificate2(file, "", keyStorageFlags); - } - store.Add(cert); - } - catch(Exception ex) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); - e.reason = "IceSSL: failure while adding certificate file:\n" + file; - throw e; - } - finally - { - store.Close(); - } - } -#endif - - // - // Split strings using a delimiter. Quotes are supported. - // Returns null for an unmatched quote. - // - private static string[] splitString(string str, char delim) - { - ArrayList l = new ArrayList(); - char[] arr = new char[str.Length]; - int pos = 0; - - while(pos < str.Length) - { - int n = 0; - char quoteChar = '\0'; - if(str[pos] == '"' || str[pos] == '\'') - { - quoteChar = str[pos]; - ++pos; - } - bool trim = true; - while(pos < str.Length) - { - if(quoteChar != '\0' && str[pos] == '\\' && pos + 1 < str.Length && str[pos + 1] == quoteChar) - { - ++pos; - } - else if(quoteChar != '\0' && str[pos] == quoteChar) - { - trim = false; - ++pos; - quoteChar = '\0'; - break; - } - else if(str[pos] == delim) - { - if(quoteChar == '\0') - { - ++pos; - break; - } - } - if(pos < str.Length) - { - arr[n++] = str[pos++]; - } - } - if(quoteChar != '\0') - { - return null; // Unmatched quote. - } - if(n > 0) - { - string s = new string(arr, 0, n); - if(trim) - { - s = s.Trim(); - } - if(s.Length > 0) - { - l.Add(s); - } - } - } - - return (string[])l.ToArray(typeof(string)); - } - private SslProtocols parseProtocols(string[] arr) { SslProtocols result = SslProtocols.Default; @@ -1121,7 +872,6 @@ namespace IceSSL return result; } -#if !UNITY private static X509Certificate2Collection findCertificates(string prop, StoreLocation storeLocation, string name, string value) { @@ -1323,7 +1073,6 @@ namespace IceSSL } return result; } -#endif private static bool decodeASN1Length(byte[] data, int start, out int len, out int next) { @@ -1377,8 +1126,5 @@ namespace IceSSL private CertificateVerifier _verifier; private PasswordCallback _passwordCallback; private TrustManager _trustManager; -#if !UNITY - private bool _tls12Support; -#endif } } diff --git a/csharp/src/IceSSL/TransceiverI.cs b/csharp/src/IceSSL/TransceiverI.cs index d2be48ba807..33617e15168 100644 --- a/csharp/src/IceSSL/TransceiverI.cs +++ b/csharp/src/IceSSL/TransceiverI.cs @@ -10,59 +10,69 @@ namespace IceSSL { using System; - using System.ComponentModel; using System.Diagnostics; using System.Collections.Generic; using System.IO; - using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; - using System.Threading; using System.Text; - sealed class TransceiverI : IceInternal.Transceiver, IceInternal.WSTransceiverDelegate + sealed class TransceiverI : IceInternal.Transceiver { public Socket fd() { - return _stream.fd(); + return _delegate.fd(); } public int initialize(IceInternal.Buffer readBuffer, IceInternal.Buffer writeBuffer, ref bool hasMoreData) { - int status = _stream.connect(readBuffer, writeBuffer, ref hasMoreData); - if(status != IceInternal.SocketOperation.None) + if(!_isConnected) { - return status; + int status = _delegate.initialize(readBuffer, writeBuffer, ref hasMoreData); + if(status != IceInternal.SocketOperation.None) + { + return status; + } + _isConnected = true; } - _stream.setBlock(true); // SSL requires a blocking socket + IceInternal.Network.setBlock(fd(), true); // SSL requires a blocking socket + + // + // For timeouts to work properly, we need to receive/send + // the data in several chunks. Otherwise, we would only be + // notified when all the data is received/written. The + // connection timeout could easily be triggered when + // receiging/sending large messages. + // + _maxSendPacketSize = Math.Max(512, IceInternal.Network.getSendBufferSize(fd())); + _maxRecvPacketSize = Math.Max(512, IceInternal.Network.getRecvBufferSize(fd())); if(_sslStream == null) { - NetworkStream ns = new NetworkStream(_stream.fd(), false); - _sslStream = new SslStream(ns, false, new RemoteCertificateValidationCallback(validationCallback), - new LocalCertificateSelectionCallback(selectCertificate)); + _sslStream = new SslStream(new NetworkStream(_delegate.fd(), false), + false, + new RemoteCertificateValidationCallback(validationCallback), + new LocalCertificateSelectionCallback(selectCertificate)); return IceInternal.SocketOperation.Connect; } Debug.Assert(_sslStream.IsAuthenticated); _authenticated = true; - _instance.verifyPeer((NativeConnectionInfo)getInfo(), _stream.fd(), _host); + _instance.verifyPeer(_host, (NativeConnectionInfo)getInfo(), ToString()); if(_instance.securityTraceLevel() >= 1) { - _instance.traceStream(_sslStream, _stream.ToString()); + _instance.traceStream(_sslStream, ToString()); } return IceInternal.SocketOperation.None; } public int closing(bool initiator, Ice.LocalException ex) { - // If we are initiating the connection closure, wait for the peer - // to close the TCP/IP connection. Otherwise, close immediately. - return initiator ? IceInternal.SocketOperation.Read : IceInternal.SocketOperation.None; + return _delegate.closing(initiator, ex); } public void close() @@ -73,7 +83,7 @@ namespace IceSSL _sslStream = null; } - _stream.close(); + _delegate.close(); } public IceInternal.EndpointI bind() @@ -84,7 +94,7 @@ namespace IceSSL public void destroy() { - _stream.destroy(); + _delegate.destroy(); } public int write(IceInternal.Buffer buf) @@ -105,14 +115,14 @@ namespace IceSSL public bool startRead(IceInternal.Buffer buf, IceInternal.AsyncCallback callback, object state) { - if(!_stream.isConnected()) + if(!_isConnected) { - return _stream.startRead(buf, callback, state); + return _delegate.startRead(buf, callback, state); } Debug.Assert(_sslStream != null && _sslStream.IsAuthenticated); - int packetSz = _stream.getRecvPacketSize(buf.b.remaining()); + int packetSz = getRecvPacketSize(buf.b.remaining()); try { _readCallback = callback; @@ -143,9 +153,9 @@ namespace IceSSL public void finishRead(IceInternal.Buffer buf) { - if(!_stream.isConnected()) + if(!_isConnected) { - _stream.finishRead(buf); + _delegate.finishRead(buf); return; } else if(_sslStream == null) // Transceiver was closed @@ -193,29 +203,28 @@ namespace IceSSL } } - public bool startWrite(IceInternal.Buffer buf, IceInternal.AsyncCallback callback, object state, - out bool completed) + public bool startWrite(IceInternal.Buffer buf, IceInternal.AsyncCallback cb, object state, out bool completed) { - if(!_stream.isConnected()) + if(!_isConnected) { - return _stream.startWrite(buf, callback, state, out completed); + return _delegate.startWrite(buf, cb, state, out completed); } Debug.Assert(_sslStream != null); if(!_authenticated) { completed = false; - return startAuthenticate(callback, state); + return startAuthenticate(cb, state); } // // We limit the packet size for beingWrite to ensure connection timeouts are based // on a fixed packet size. // - int packetSize = _stream.getSendPacketSize(buf.b.remaining()); + int packetSize = getSendPacketSize(buf.b.remaining()); try { - _writeCallback = callback; + _writeCallback = cb; _writeResult = _sslStream.BeginWrite(buf.b.rawBytes(), buf.b.position(), packetSize, writeCompleted, state); completed = packetSize == buf.b.remaining(); @@ -245,14 +254,14 @@ namespace IceSSL public void finishWrite(IceInternal.Buffer buf) { - if(!_stream.isConnected()) + if(!_isConnected) { - _stream.finishWrite(buf); + _delegate.finishWrite(buf); return; } else if(_sslStream == null) // Transceiver was closed { - if(_stream.getSendPacketSize(buf.b.remaining()) == buf.b.remaining()) // Sent last packet + if(getSendPacketSize(buf.b.remaining()) == buf.b.remaining()) // Sent last packet { buf.b.position(buf.b.limit()); // Assume all the data was sent for at-most-once semantics. } @@ -266,7 +275,7 @@ namespace IceSSL } Debug.Assert(_writeResult != null); - int sent = _stream.getSendPacketSize(buf.b.remaining()); + int sent = getSendPacketSize(buf.b.remaining()); try { _sslStream.EndWrite(_writeResult); @@ -297,50 +306,72 @@ namespace IceSSL public string protocol() { - return _instance.protocol(); + return _delegate.protocol(); } public Ice.ConnectionInfo getInfo() { NativeConnectionInfo info = new NativeConnectionInfo(); - info.nativeCerts = fillConnectionInfo(info); - return info; - } + info.underlying = _delegate.getInfo(); + info.incoming = _incoming; + info.adapterName = _adapterName; + if(_sslStream != null) + { + info.cipher = _sslStream.CipherAlgorithm.ToString(); + if(_chain.ChainElements != null && _chain.ChainElements.Count > 0) + { + info.nativeCerts = new X509Certificate2[_chain.ChainElements.Count]; + for(int i = 0; i < _chain.ChainElements.Count; ++i) + { + info.nativeCerts[i] = _chain.ChainElements[i].Certificate; + } + } - public Ice.ConnectionInfo getWSInfo(Dictionary<string, string> headers) - { - WSSNativeConnectionInfo info = new WSSNativeConnectionInfo(); - info.nativeCerts = fillConnectionInfo(info); - info.headers = headers; + List<string> certs = new List<string>(); + if(info.nativeCerts != null) + { + foreach(X509Certificate2 cert in info.nativeCerts) + { + StringBuilder s = new StringBuilder(); + s.Append("-----BEGIN CERTIFICATE-----\n"); + s.Append(Convert.ToBase64String(cert.Export(X509ContentType.Cert))); + s.Append("\n-----END CERTIFICATE-----"); + certs.Add(s.ToString()); + } + } + info.certs = certs.ToArray(); + info.verified = _verified; + } return info; } public void checkSendSize(IceInternal.Buffer buf) { + _delegate.checkSendSize(buf); } public void setBufferSize(int rcvSize, int sndSize) { - _stream.setBufferSize(rcvSize, sndSize); + _delegate.setBufferSize(rcvSize, sndSize); } public override string ToString() { - return _stream.ToString(); + return _delegate.ToString(); } public string toDetailedString() { - return ToString(); + return _delegate.toDetailedString(); } // // Only for use by ConnectorI, AcceptorI. // - internal TransceiverI(Instance instance, IceInternal.StreamSocket stream, string hostOrAdapterName, bool incoming) + internal TransceiverI(Instance instance, IceInternal.Transceiver del, string hostOrAdapterName, bool incoming) { _instance = instance; - _stream = stream; + _delegate = del; _incoming = incoming; if(_incoming) { @@ -350,6 +381,7 @@ namespace IceSSL { _host = hostOrAdapterName; } + _sslStream = null; _verifyPeer = _instance.properties().getPropertyAsIntWithDefault("IceSSL.VerifyPeer", 2); @@ -364,12 +396,10 @@ namespace IceSSL X509Certificate2Collection caCerts = _instance.engine().caCerts(); if(caCerts != null) { -#if !UNITY // // We need to set this flag to be able to use a certificate authority from the extra store. // _chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; -#endif foreach(X509Certificate2 cert in caCerts) { _chain.ChainPolicy.ExtraStore.Add(cert); @@ -377,61 +407,6 @@ namespace IceSSL } } - private X509Certificate2[] fillConnectionInfo(ConnectionInfo info) - { - X509Certificate2[] nativeCerts = null; - if(_stream.fd() != null) - { - IPEndPoint localEndpoint = (IPEndPoint)IceInternal.Network.getLocalAddress(_stream.fd()); - info.localAddress = localEndpoint.Address.ToString(); - info.localPort = localEndpoint.Port; - IPEndPoint remoteEndpoint = (IPEndPoint)IceInternal.Network.getRemoteAddress(_stream.fd()); - if(remoteEndpoint != null) - { - info.remoteAddress = remoteEndpoint.Address.ToString(); - info.remotePort = remoteEndpoint.Port; - } - info.rcvSize = IceInternal.Network.getRecvBufferSize(_stream.fd()); - info.sndSize = IceInternal.Network.getSendBufferSize(_stream.fd()); - } - if(_sslStream != null) - { -#if UNITY - info.cipher = ""; -#else - info.cipher = _sslStream.CipherAlgorithm.ToString(); - if(_chain.ChainElements != null && _chain.ChainElements.Count > 0) - { - nativeCerts = new X509Certificate2[_chain.ChainElements.Count]; - for(int i = 0; i < _chain.ChainElements.Count; ++i) - { - nativeCerts[i] = _chain.ChainElements[i].Certificate; - } - } -#endif - - List<string> certs = new List<string>(); -#if !UNITY - if(nativeCerts != null) - { - foreach(X509Certificate2 cert in nativeCerts) - { - StringBuilder s = new StringBuilder(); - s.Append("-----BEGIN CERTIFICATE-----\n"); - s.Append(Convert.ToBase64String(cert.Export(X509ContentType.Cert))); - s.Append("\n-----END CERTIFICATE-----"); - certs.Add(s.ToString()); - } - } -#endif - info.certs = certs.ToArray(); - info.verified = _verified; - } - info.adapterName = _adapterName; - info.incoming = _incoming; - return nativeCerts; - } - private bool startAuthenticate(IceInternal.AsyncCallback callback, object state) { try @@ -451,9 +426,6 @@ namespace IceSSL } else { -#if UNITY - throw new Ice.FeatureNotSupportedException("ssl server socket"); -#else // // Server authentication. // @@ -472,7 +444,6 @@ namespace IceSSL _instance.checkCRL() > 0, writeCompleted, state); -#endif } } catch(IOException ex) @@ -487,14 +458,12 @@ namespace IceSSL } throw new Ice.SocketException(ex); } -#if !UNITY catch(AuthenticationException ex) { Ice.SecurityException e = new Ice.SecurityException(ex); e.reason = ex.Message; throw e; } -#endif catch(Exception ex) { throw new Ice.SyscallException(ex); @@ -531,26 +500,20 @@ namespace IceSSL } throw new Ice.SocketException(ex); } -#if !UNITY catch(AuthenticationException ex) { Ice.SecurityException e = new Ice.SecurityException(ex); e.reason = ex.Message; throw e; } -#endif catch(Exception ex) { throw new Ice.SyscallException(ex); } } - private X509Certificate selectCertificate( - object sender, - string targetHost, - X509CertificateCollection certs, - X509Certificate remoteCertificate, - string[] acceptableIssuers) + private X509Certificate selectCertificate(object sender, string targetHost, X509CertificateCollection certs, + X509Certificate remoteCertificate, string[] acceptableIssuers) { if(certs == null || certs.Count == 0) { @@ -580,7 +543,6 @@ namespace IceSSL private bool validationCallback(object sender, X509Certificate certificate, X509Chain chainEngine, SslPolicyErrors policyErrors) { -#if !UNITY string message = ""; int errors = (int)policyErrors; if(certificate != null) @@ -758,7 +720,6 @@ namespace IceSSL _instance.logger().trace(_instance.securityTraceCategory(), "SSL certificate validation status:" + message); } -#endif return true; } @@ -778,13 +739,24 @@ namespace IceSSL } } + private int getSendPacketSize(int length) + { + return _maxSendPacketSize > 0 ? Math.Min(length, _maxSendPacketSize) : length; + } + + public int getRecvPacketSize(int length) + { + return _maxRecvPacketSize > 0 ? Math.Min(length, _maxRecvPacketSize) : length; + } + private Instance _instance; - private IceInternal.StreamSocket _stream; + private IceInternal.Transceiver _delegate; private string _host = ""; private string _adapterName = ""; private bool _incoming; private SslStream _sslStream; private int _verifyPeer; + private bool _isConnected; private bool _authenticated; private IAsyncResult _writeResult; private IAsyncResult _readResult; @@ -792,5 +764,7 @@ namespace IceSSL private IceInternal.AsyncCallback _writeCallback; private X509Chain _chain; private bool _verified; + private int _maxSendPacketSize; + private int _maxRecvPacketSize; } } diff --git a/csharp/src/IceSSL/TrustManager.cs b/csharp/src/IceSSL/TrustManager.cs index 121fb719714..98697dd0942 100644 --- a/csharp/src/IceSSL/TrustManager.cs +++ b/csharp/src/IceSSL/TrustManager.cs @@ -9,7 +9,6 @@ namespace IceSSL { - using System; using System.Collections.Generic; using System.Diagnostics; using System.Security.Cryptography.X509Certificates; @@ -20,18 +19,18 @@ namespace IceSSL internal TrustManager(Ice.Communicator communicator) { Debug.Assert(communicator != null); - communicator_ = communicator; + _communicator = communicator; Ice.Properties properties = communicator.getProperties(); - traceLevel_ = properties.getPropertyAsInt("IceSSL.Trace.Security"); + _traceLevel = properties.getPropertyAsInt("IceSSL.Trace.Security"); string key = null; try { key = "IceSSL.TrustOnly"; - parse(properties.getProperty(key), rejectAll_, acceptAll_); + parse(properties.getProperty(key), _rejectAll, _acceptAll); key = "IceSSL.TrustOnly.Client"; - parse(properties.getProperty(key), rejectClient_, acceptClient_); + parse(properties.getProperty(key), _rejectClient, _acceptClient); key = "IceSSL.TrustOnly.Server"; - parse(properties.getProperty(key), rejectAllServer_, acceptAllServer_); + parse(properties.getProperty(key), _rejectAllServer, _acceptAllServer); Dictionary<string, string> dict = properties.getPropertiesForPrefix("IceSSL.TrustOnly.Server."); foreach(KeyValuePair<string, string> entry in dict) { @@ -42,11 +41,11 @@ namespace IceSSL parse(entry.Value, reject, accept); if(reject.Count > 0) { - rejectServer_[name] = reject; + _rejectServer[name] = reject; } if(accept.Count > 0) { - acceptServer_[name] = accept; + _acceptServer[name] = accept; } } } @@ -58,25 +57,25 @@ namespace IceSSL } } - internal bool verify(NativeConnectionInfo info) + internal bool verify(NativeConnectionInfo info, string desc) { List<List<List<RFC2253.RDNPair>>> reject = new List<List<List<RFC2253.RDNPair>>>(), accept = new List<List<List<RFC2253.RDNPair>>>(); - if(rejectAll_.Count != 0) + if(_rejectAll.Count != 0) { - reject.Add(rejectAll_); + reject.Add(_rejectAll); } if(info.incoming) { - if(rejectAllServer_.Count != 0) + if(_rejectAllServer.Count != 0) { - reject.Add(rejectAllServer_); + reject.Add(_rejectAllServer); } if(info.adapterName.Length > 0) { List<List<RFC2253.RDNPair>> p = null; - if(rejectServer_.TryGetValue(info.adapterName, out p)) + if(_rejectServer.TryGetValue(info.adapterName, out p)) { reject.Add(p); } @@ -84,26 +83,26 @@ namespace IceSSL } else { - if(rejectClient_.Count != 0) + if(_rejectClient.Count != 0) { - reject.Add(rejectClient_); + reject.Add(_rejectClient); } } - if(acceptAll_.Count != 0) + if(_acceptAll.Count != 0) { - accept.Add(acceptAll_); + accept.Add(_acceptAll); } if(info.incoming) { - if(acceptAllServer_.Count != 0) + if(_acceptAllServer.Count != 0) { - accept.Add(acceptAllServer_); + accept.Add(_acceptAllServer); } if(info.adapterName.Length > 0) { List<List<RFC2253.RDNPair>> p = null; - if(acceptServer_.TryGetValue(info.adapterName, out p)) + if(_acceptServer.TryGetValue(info.adapterName, out p)) { accept.Add(p); } @@ -111,9 +110,9 @@ namespace IceSSL } else { - if(acceptClient_.Count != 0) + if(_acceptClient.Count != 0) { - accept.Add(acceptClient_); + accept.Add(_acceptClient); } } @@ -130,9 +129,6 @@ namespace IceSSL // if(info.nativeCerts != null && info.nativeCerts.Length > 0) { -#if UNITY - throw new Ice.FeatureNotSupportedException("certificate subjectName not available"); -#else X500DistinguishedName subjectDN = info.nativeCerts[0].SubjectName; string subjectName = subjectDN.Name; Debug.Assert(subjectName != null); @@ -141,22 +137,17 @@ namespace IceSSL // // Decompose the subject DN into the RDNs. // - if(traceLevel_ > 0) + if(_traceLevel > 0) { if(info.incoming) { - communicator_.getLogger().trace("Security", "trust manager evaluating client:\n" + - "subject = " + subjectName + "\n" + - "adapter = " + info.adapterName + "\n" + - "local addr = " + info.localAddress + ":" + info.localPort + "\n" + - "remote addr = " + info.remoteAddress + ":" + info.remotePort); + _communicator.getLogger().trace("Security", "trust manager evaluating client:\n" + + "subject = " + subjectName + "\n" + "adapter = " + info.adapterName + "\n" + desc); } else { - communicator_.getLogger().trace("Security", "trust manager evaluating server:\n" + - "subject = " + subjectName + "\n" + - "local addr = " + info.localAddress + ":" + info.localPort + "\n" + - "remote addr = " + info.remoteAddress + ":" + info.remotePort); + _communicator.getLogger().trace("Security", "trust manager evaluating server:\n" + + "subject = " + subjectName + "\n" + desc); } } @@ -179,11 +170,11 @@ namespace IceSSL // foreach(List<List<RFC2253.RDNPair>> matchSet in reject) { - if(traceLevel_ > 0) + if(_traceLevel > 0) { StringBuilder s = new StringBuilder("trust manager rejecting PDNs:\n"); stringify(matchSet, s); - communicator_.getLogger().trace("Security", s.ToString()); + _communicator.getLogger().trace("Security", s.ToString()); } if(match(matchSet, dn)) { @@ -196,11 +187,11 @@ namespace IceSSL // foreach(List<List<RFC2253.RDNPair>> matchSet in accept) { - if(traceLevel_ > 0) + if(_traceLevel > 0) { StringBuilder s = new StringBuilder("trust manager accepting PDNs:\n"); stringify(matchSet, s); - communicator_.getLogger().trace("Security", s.ToString()); + _communicator.getLogger().trace("Security", s.ToString()); } if(match(matchSet, dn)) { @@ -210,7 +201,7 @@ namespace IceSSL } catch(RFC2253.ParseException e) { - communicator_.getLogger().warning( + _communicator.getLogger().warning( "IceSSL: unable to parse certificate DN `" + subjectName + "'\nreason: " + e.reason); } @@ -218,7 +209,6 @@ namespace IceSSL // At this point we accept the connection if there are no explicit accept rules. // return accept.Count == 0; -#endif } return false; @@ -325,19 +315,19 @@ namespace IceSSL } } - private Ice.Communicator communicator_; - private int traceLevel_; + private Ice.Communicator _communicator; + private int _traceLevel; - private List<List<RFC2253.RDNPair>> rejectAll_ = new List<List<RFC2253.RDNPair>>(); - private List<List<RFC2253.RDNPair>> rejectClient_ = new List<List<RFC2253.RDNPair>>(); - private List<List<RFC2253.RDNPair>> rejectAllServer_ = new List<List<RFC2253.RDNPair>>(); - private Dictionary<string, List<List<RFC2253.RDNPair>>> rejectServer_ = + private List<List<RFC2253.RDNPair>> _rejectAll = new List<List<RFC2253.RDNPair>>(); + private List<List<RFC2253.RDNPair>> _rejectClient = new List<List<RFC2253.RDNPair>>(); + private List<List<RFC2253.RDNPair>> _rejectAllServer = new List<List<RFC2253.RDNPair>>(); + private Dictionary<string, List<List<RFC2253.RDNPair>>> _rejectServer = new Dictionary<string, List<List<RFC2253.RDNPair>>>(); - private List<List<RFC2253.RDNPair>> acceptAll_ = new List<List<RFC2253.RDNPair>>(); - private List<List<RFC2253.RDNPair>> acceptClient_ = new List<List<RFC2253.RDNPair>>(); - private List<List<RFC2253.RDNPair>> acceptAllServer_ = new List<List<RFC2253.RDNPair>>(); - private Dictionary<string, List<List<RFC2253.RDNPair>>> acceptServer_ = + private List<List<RFC2253.RDNPair>> _acceptAll = new List<List<RFC2253.RDNPair>>(); + private List<List<RFC2253.RDNPair>> _acceptClient = new List<List<RFC2253.RDNPair>>(); + private List<List<RFC2253.RDNPair>> _acceptAllServer = new List<List<RFC2253.RDNPair>>(); + private Dictionary<string, List<List<RFC2253.RDNPair>>> _acceptServer = new Dictionary<string, List<List<RFC2253.RDNPair>>>(); } } diff --git a/csharp/src/IceSSL/Util.cs b/csharp/src/IceSSL/Util.cs index bbc34d98b9a..242c596febb 100644 --- a/csharp/src/IceSSL/Util.cs +++ b/csharp/src/IceSSL/Util.cs @@ -25,21 +25,7 @@ namespace IceSSL /// supply a certificate. The peer's certificate (if any) is the /// first one in the chain. /// </summary> - public System.Security.Cryptography.X509Certificates.X509Certificate2[] nativeCerts; - } - - /// <summary> - /// This class provides information about a connection to applications - /// that require information about a peer. - /// </summary> - public sealed class WSSNativeConnectionInfo : WSSConnectionInfo - { - /// <summary> - /// The certificate chain. This may be null if the peer did not - /// supply a certificate. The peer's certificate (if any) is the - /// first one in the chain. - /// </summary> - public System.Security.Cryptography.X509Certificates.X509Certificate2[] nativeCerts; + public X509Certificate2[] nativeCerts; } public sealed class Util diff --git a/csharp/src/IceSSL/generated/.gitignore b/csharp/src/IceSSL/generated/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/csharp/src/IceSSL/generated/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/csharp/src/IceSSL/msbuild/icessl.csproj b/csharp/src/IceSSL/msbuild/icessl.csproj new file mode 100644 index 00000000000..7a82fcc0bd6 --- /dev/null +++ b/csharp/src/IceSSL/msbuild/icessl.csproj @@ -0,0 +1,94 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{B763DADE-440B-46BC-9CC0-BF0CF9D43182}</ProjectGuid> + <OutputType>Library</OutputType> + <AssemblyName>IceSSL</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\Assemblies\IceSSL.XML</DocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\AcceptorI.cs"> + <Link>AcceptorI.cs</Link> + </Compile> + <Compile Include="..\AssemblyInfo.cs"> + <Link>AssemblyInfo.cs</Link> + </Compile> + <Compile Include="..\ConnectorI.cs"> + <Link>ConnectorI.cs</Link> + </Compile> + <Compile Include="..\EndpointI.cs"> + <Link>EndpointI.cs</Link> + </Compile> + <Compile Include="..\Instance.cs"> + <Link>Instance.cs</Link> + </Compile> + <Compile Include="..\Plugin.cs"> + <Link>Plugin.cs</Link> + </Compile> + <Compile Include="..\PluginI.cs"> + <Link>PluginI.cs</Link> + </Compile> + <Compile Include="..\RFC2253.cs"> + <Link>RFC2253.cs</Link> + </Compile> + <Compile Include="..\SSLEngine.cs"> + <Link>SSLEngine.cs</Link> + </Compile> + <Compile Include="..\TransceiverI.cs"> + <Link>TransceiverI.cs</Link> + </Compile> + <Compile Include="..\TrustManager.cs"> + <Link>TrustManager.cs</Link> + </Compile> + <Compile Include="..\Util.cs"> + <Link>Util.cs</Link> + </Compile> + <Compile Include="generated\ConnectionInfo.cs" /> + <Compile Include="generated\EndpointInfo.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\slice\IceSSL\ConnectionInfo.ice"> + <Link>ConnectionInfo.ice</Link> + </None> + <None Include="..\..\..\..\slice\IceSSL\EndpointInfo.ice"> + <Link>EndpointInfo.ice</Link> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\Ice\msbuild\ice.csproj"> + <Project>{7cb4715e-dd8b-48f8-b478-27b8bd4008c7}</Project> + <Name>ice</Name> + <Private>False</Private> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\config\ice.sign.targets" /> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/IceStorm/.depend.mak b/csharp/src/IceStorm/.depend.mak deleted file mode 100644 index de028ef4015..00000000000 --- a/csharp/src/IceStorm/.depend.mak +++ /dev/null @@ -1,13 +0,0 @@ - -IceStorm.cs: \ - "$(slicedir)\IceStorm\IceStorm.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" \ - "$(slicedir)/IceStorm/Metrics.ice" \ - "$(slicedir)/Ice/Metrics.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Metrics.cs: \ - "$(slicedir)\IceStorm\Metrics.ice" \ - "$(slicedir)/Ice/Metrics.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" diff --git a/csharp/src/IceStorm/AssemblyInfo.cs b/csharp/src/IceStorm/AssemblyInfo.cs index 4da6c5a2e32..70add6b12e8 100644 --- a/csharp/src/IceStorm/AssemblyInfo.cs +++ b/csharp/src/IceStorm/AssemblyInfo.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Ice")] [assembly: AssemblyCopyright("© 2003-2016 ZeroC, Inc.")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("3.6.3")] +[assembly: AssemblyVersion("3.7.54")] [assembly: AssemblyDelaySign(false)] [assembly: ComVisible(false)] diff --git a/csharp/src/IceStorm/Makefile b/csharp/src/IceStorm/Makefile deleted file mode 100644 index 15df4046e95..00000000000 --- a/csharp/src/IceStorm/Makefile +++ /dev/null @@ -1,47 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -PKG = IceStorm -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)/$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs - -SLICE_SRCS = $(SDIR)/IceStorm.ice \ - $(SDIR)/Metrics.ice - -SDIR = $(slicedir)/IceStorm -GDIR = generated - -include $(top_srcdir)/config/Make.rules.cs - -MCSFLAGS := $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS := $(MCSFLAGS) -keyfile:$(KEYFILE) -MCSFLAGS := $(MCSFLAGS) /doc:$(assembliesdir)/$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS := $(SLICE2CSFLAGS) -I$(slicedir) --ice - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) $(MCSFLAGS) $(call ref,Ice) $(subst /,$(DSEP),$^) - -install:: all - (cd $(assembliesdir); $(call installassembly,$(LIBNAME),$(PKG)); $(call installpolicy,$(POLICY)); \ - $(call installmdb,$(LIBNAME).mdb); \ - $(call installdata,$(PKG).xml,$(DESTDIR)$(install_assembliesdir))) - -ifeq ($(GACINSTALL),yes) -install:: all - $(call installdata,../../lib/pkgconfig/$(PKG).pc,$(DESTDIR)$(install_pkgconfigdir)) -endif - -clean:: - -rm -f $(assembliesdir)/$(PKG).xml diff --git a/csharp/src/IceStorm/Makefile.mak b/csharp/src/IceStorm/Makefile.mak deleted file mode 100644 index f91ebbb17f0..00000000000 --- a/csharp/src/IceStorm/Makefile.mak +++ /dev/null @@ -1,54 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -PKG = IceStorm -LIBNAME = $(PKG).dll -TARGETS = $(assembliesdir)\$(LIBNAME) -POLICY_TARGET = $(POLICY).dll - -SRCS = AssemblyInfo.cs - -GEN_SRCS = $(GDIR)\IceStorm.cs \ - $(GDIR)\Metrics.cs - -SDIR = $(slicedir)\IceStorm -GDIR = generated - -!include $(top_srcdir)\config\Make.rules.mak.cs - -MCSFLAGS = $(MCSFLAGS) -target:library -out:$(TARGETS) -warnaserror- -MCSFLAGS = $(MCSFLAGS) -keyfile:"$(KEYFILE)" -MCSFLAGS = $(MCSFLAGS) /doc:$(assembliesdir)\$(PKG).xml /nowarn:1591 - -SLICE2CSFLAGS = $(SLICE2CSFLAGS) -I$(slicedir) --ice - -$(TARGETS):: $(SRCS) $(GEN_SRCS) - $(MCS) /baseaddress:0x21000000 $(MCSFLAGS) -r:$(refdir)\Ice.dll $(SRCS) $(GEN_SRCS) - @if defined SIGN_CERTIFICATE echo ^ ^ ^ Signing $@ && \ - signtool sign /f "$(SIGN_CERTIFICATE)" /p $(SIGN_PASSWORD) /t $(SIGN_TIMESTAMPSERVER) $@ - -!if "$(DEBUG)" == "yes" -clean:: - del /q $(assembliesdir)\$(PKG).pdb -!endif - -clean:: - del /q $(assembliesdir)\$(PKG).xml - -install:: all - copy $(assembliesdir)\$(LIBNAME) "$(install_assembliesdir)" - copy $(assembliesdir)\$(PKG).xml "$(install_assembliesdir)" -!if "$(generate_policies)" == "yes" - copy $(assembliesdir)\$(POLICY_TARGET) "$(install_assembliesdir)" -!endif -!if "$(DEBUG)" == "yes" - copy $(assembliesdir)\$(PKG).pdb "$(install_assembliesdir)" -!endif diff --git a/csharp/src/IceStorm/generated/.gitignore b/csharp/src/IceStorm/generated/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/csharp/src/IceStorm/generated/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/csharp/src/IceStorm/msbuild/icestorm.csproj b/csharp/src/IceStorm/msbuild/icestorm.csproj new file mode 100644 index 00000000000..a3ac58fb7a0 --- /dev/null +++ b/csharp/src/IceStorm/msbuild/icestorm.csproj @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderCsharpProps>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.props</IceBuilderCsharpProps> + <IceBuilderCsharpTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.CSharp.targets</IceBuilderCsharpTargets> + </PropertyGroup> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <ProjectGuid>{A77D65F6-31CF-4BFD-A7DF-E7F509B98573}</ProjectGuid> + <OutputType>Library</OutputType> + <AssemblyName>IceStorm</AssemblyName> + <ProjectTypeGuids>{3C53C28F-DC44-46B0-8B85-0C96B85B2042};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <DocumentationFile>..\..\..\Assemblies\IceStorm.XML</DocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\msbuild\ice.common.props" /> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\AssemblyInfo.cs"> + <Link>AssemblyInfo.cs</Link> + </Compile> + <Compile Include="generated\IceStorm.cs" /> + <Compile Include="generated\Metrics.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="..\..\..\..\slice\IceStorm\IceStorm.ice"> + <Link>IceStorm.ice</Link> + </None> + <None Include="..\..\..\..\slice\IceStorm\Metrics.ice"> + <Link>Metrics.ice</Link> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\Ice\msbuild\ice.csproj"> + <Project>{7cb4715e-dd8b-48f8-b478-27b8bd4008c7}</Project> + <Name>ice</Name> + <Private>False</Private> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(IceBuilderCsharpProps)" Condition="Exists('$(IceBuilderCsharpProps)')" /> + <PropertyGroup Label="IceBuilder"> + <IceBuilderIncludeDirectories>$(IceHome)\slice</IceBuilderIncludeDirectories> + </PropertyGroup> + <Import Project="$(IceBuilderCsharpTargets)" Condition="Exists('$(IceBuilderCsharpTargets)')" /> + <Import Project="$(MSBuildThisFileDirectory)..\..\..\..\config\ice.sign.targets" /> + <Target Name="EnsureIceBuilderImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project requires the Ice Builder for Visual Studio extension. Use "Tools &gt; Extensions and Updates" to install it. For more information, see https://visualstudiogallery.msdn.microsoft.com/1a64e701-63f2-4740-8004-290e6c682ce0.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('$(IceBuilderCSharpProps)')" Text="$(ErrorText)" /> + </Target> +</Project>
\ No newline at end of file diff --git a/csharp/src/Makefile b/csharp/src/Makefile deleted file mode 100644 index 237c96fd60c..00000000000 --- a/csharp/src/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = .. - -include $(top_srcdir)/config/Make.rules.cs - -SUBDIRS = Ice IceStorm Glacier2 IcePatch2 IceGrid IceBox IceDiscovery IceLocatorDiscovery - -$(EVERYTHING):: - @for subdir in $(SUBDIRS); \ - do \ - echo "making $@ in $$subdir"; \ - ( cd $$subdir && $(MAKE) $@ ) || exit 1; \ - done diff --git a/csharp/src/Makefile.mak b/csharp/src/Makefile.mak deleted file mode 100644 index 37fefbd77d2..00000000000 --- a/csharp/src/Makefile.mak +++ /dev/null @@ -1,27 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = .. - -!include $(top_srcdir)\config\Make.rules.mak.cs - -SUBDIRS = Ice \ - IceStorm \ - Glacier2 \ - IcePatch2 \ - IceGrid \ - IceBox \ - IceSSL \ - IceDiscovery \ - IceLocatorDiscovery - -$(EVERYTHING):: - @for %i in ( $(SUBDIRS) ) do \ - @echo "making $@ in %i" && \ - cmd /c "cd %i && $(MAKE) -nologo -f Makefile.mak $@" || exit 1 |