Remoting and WebServices.Net
THIS PAGE IS .NET 1 ONLY. See WCF
WebServices
- Sessions- must be explicitly added on both client and service
Server:[WebMethod(EnableSession=true)] public void NewGame()
Client:service1.CookieContainer = new System.Net.CookieContainer();
- Other WebMethod attributes: CacheDuration (cache it), TransactionOption (NB: if call other webmethods, transaction aren't passed over Soap, so multiple calls aren't Acid)
- Exceptions: any exceptions in a webmethod are passed as a SoapException
- Authentication: pass your windows auth by
server.Credentials = System.Net.CredentialCache.DefaultCredentials;
otherwiseserviceobj.Credentials = new NetworkCredential(username, password);
- Custom authentication: use SoapHeaders- create a custom class derived from SoapHeader, and make it a member of your WebService assembly; then decorate the WebMethod with the attribute specifying the member name
[WebMethod, SoapHeader("MyHeader",Direction=SoapHeaderDirection.InOut)]
- SOAP Extensions. You extend SoapExtension with overrides GetInitializer, Initialize, ChainStream, ProcessMessage (switch/case SoapMessageStage). Generally you're doing things (like encryption or value translations) in .AfterSerialize (sender- just before sent) and/or .BeforeDeserialize (receiver- as soon as received). You may also need a SoapExtensionAttribute class so it can be used.
- The serializer may not work out all derived types in a hierarchy, so add a [XmlInclude(typeof(MySpecificObj))] attribute
- You can customise the Soap format- SoapDocumentService(Use=SoapBindingUse.Encoded) or SoapRpcService (for class) or SoapDocumentMethod (for method). Literal is default, encoded and rpc have namespaces for each datatype. The literal and encoded (document style) also allow SoapParameterStyle.Bare and XmlElement attributes.
- To show an aspx if you browse to a webservice: wsdlHelpGenerator href="form.aspx" (NB: only works for subfolders- .Net 1.1 has error in root directory)
Remoting
- Marshal-by-value objects implement ISerializable
- Marshal-by-reference objects extend System.Marshal-ByRefObject and become proxies on the client
Have LifetimeLeases (clients can renew by getting the ILease from GetLifetimeService) - Server Activation - created by first method call (not on "new obj")
- WellKnownObjectMode.Singleton (shared):
ChannelServices.RegisterChannel(new TcpChannel(8020)); WellKnownServiceTypeEntry myservice = new WellKnownServiceTypeEntry(typeof(MyService),"TcpService", WellKnownObjectMode.Singleton); RemotingConfiguration.ApplicationName = " TcpService"; RemotingConfiguration.RegisterWellKnownServiceType(myservice);
- WellKnownObjectMode.SingleCall (created each call, stateless)
In xml: configuration/system.runtime.remoting/application/service/wellknown/@mode="SingleCall" @type=MyRemoteClass,RemoteAssembly
NB: most scalable, suitable for load-balancing - Can host in IIS (for SSL etc). Just put system.runtime.remoting into web.config (no channel- it's 80, no tcp obviously), and register objectUri with ".rem" extension.
- WellKnownObjectMode.Singleton (shared):
- Client Activation (created by "new")
- Versioning: The client specifies the version- server can't specify the version (as opposed to SOAs)
- Can't use IIS as a host - only SAOs
- XML config:
RemotingConfiguration.Configure("my.config"); //remember to do this!
- Channels:
HttpServerChannel channel=new HttpServerChannel(0); //0= available port (if already used-exception) ChannelServices.RegisterChannel(channel);
NB: clients don't specify port.
NB: http channels can be more secure than tcp if hosted in IIS - You can do remoting asynchronously:
// Create delegate to a method that is executed when async method done. AsyncCallback callBackDelegate = new AsyncCallback(CallBackMethod); // Create a delegate to the method that will be executed asynchronously MyAsyncDelegate startLongCallDelegate = new MyAsyncDelegate(obj.LongCall); // Begin the invocation of the asynchronous method. startLongCallDelegate.BeginInvoke(remoteMethod,nothing);
- Avoiding client copies
- Interface assembly. As interfaces don't have constructors, use Activator.GetObject (for server activated) or Activator.CreateInstance (for client-activated)
- Or use soapsuds.exe (for http channels) to generate a proxy (dll or source)
Serviced components (.Net COM+ apps)
- Derive from System.EnterpriseServices.ServicedComponent
- Decorate with attributes eg ObjectPoolingAttribute (default is false), ApplicationActivation (Library or Server- latter must be in GAC), TransactionsAttribute on class, AutoCompleteAttribute on a method (calls SetComplete/ SetAbort)
- Register manually with RegSvcs.exe (shows errors), or in code using RegistrationHelper class
- AccessControl integrates with COM+ security via attributes such as Application/ComponentAccessControl and SecurityRole
- Queued:
- Assembly- support queues: [assembly:ApplicationQueuing(Enabled=true,QueueListenerEnabled=true)]
- Class- show interface: [InterfaceQueuing(Enabled=true,Interface="IMyInterface")]
- No callbacks or app-specific errors, or return values
- Client uses Marshal.BindToMoniker:
IInterface i =(IInterface) Marshal.BindToMoniker(@"queue:/new:MyNameSpace.IMyInterface"); i.DoMyMethod(); Marshal.ReleaseComObject(i);
- DEBUGGING: attach to DllHost.exe
Windows Services
- System.ServiceProcess namespace has
- ServiceBase class (services, either Win32OwnProcess (single process) services or Win32ShareProcess (shared process) services).
VS: change Name and ServiceName properties and the Main sub
Override OnStart, OnStop etc + OnCustomCommand, OnPowerEvent (if Can* properties =true)
AutoLog=true + EventLog.WriteLog(mess) (false to send to custom event log) - ServiceInstaller and ServiceProcessInstaller classes to install
VS Designer: rightclick- Add Installer - ProjectInstaller class contains instances of both with [RunInstaller(true)] attribute (for Installutil.exe)
ServiceProcessInstaller.Account= LocalService, LocalSystem, NetworkService, or User - ServiceController class to start/stop/pause (rather than via Service Control Manager (SCM))
Should be a separate exe! Create a winform and drop ServiceController from toolbox (or Server Explorer- rightclick the service + "Add To Designer").
Check .Status = .Running before ops
.ExecuteCommand(int) /*between 128 and 256*/, GetServices()
- ServiceBase class (services, either Win32OwnProcess (single process) services or Win32ShareProcess (shared process) services).
- You can drag a performance counter from the Server Explorer - NB remove MachineName
WCF
- X509 Certificates
- How To Use Certificate Authentication and Message Security in WCF [CodePlex]
- MSDN: Working with certificates
- Certicates mmc: Start - Run - MMC - File - Add/Remove Snap-In - [Add] - Certificates - Computer Account - Local Computer.
- For test certificates: makecert. Eg
makecert -r -pe -n "CN=XYZ Company" -sky exchange -sr LocalMachine -ss my
(an exportable self signed certificate with a subject for the Trusted People store for LocalMachine - ASP access to certificates: Download WinHttpCertCfg and run it
winhttpcertcfg -g -c LOCAL_MACHINE\My -s "My Server Machine" -a "ASPNET"
(for XP; -a "NETWORK SERVICE" for Windows Server 2003) - Using Windows CERTSRV to request/issue client and server X.509 certificates [CodeProject, nicely illustrated]
- WCF binding for Ws-Security (message mode): system.serviceModel/bindings/wsHttpBinding/binding/security mode="Message"/message clientCredentialType="Certificate"
- behaviors/endpointBehaviors/behavior/clientCredentials/serviceCertificate/authentication certificateValidationMode="PeerOrChainTrust" allows a self signed certificate if it is in the Trusted People store.