Implementing Object Pooling with .NET Remoting – Part II

Implementing Object Pooling with .NET Remoting – Part II

he Pool Manager described in the first part of this article series had a couple of problems. The process of acquiring a pooled object was not transparent to the client, which couldn’t simply new the object (provided that the required type had been registered in the remote configuration file). The client had to contact the broker explicitly to acquire a reference to an object in the pool.

The second problem lies in the fact that objects returned by the broker are CAO types. This is far from optimal. The client must explicitly release the object when done with the object calling Dispose. If it fails to do so, the object is returned to the pool only when the object Lease time is expired.

Properly designed pooled objects don’t keep any client specific state across calls, thus for this reason it would be highly desirable to pass back to clients SAO SingleCall object types. This optimize the pool management, not letting the client hold a reference to a pooled object longer than necessary.

Activation Transparency and SingleCall Behavior via a Custom Channel Sink
Remoting behavior can be customized in two ways: defining a custom proxy or inserting a custom sink in the default sink chain. The custom proxy approach is not so compelling, since you cannot insert a custom proxy transparently (the client must explicitly create it) and anything you can do with a custom proxy can actually be done using a custom sink.

We will then opt for a custom sink to enable transparent activation and SingleCall behavior for our pooled objects. The solution we will come out with won’t work for Client Activated objects, but as I said, CAO are not a desirable option when working with pooled objects.

Anyway, note you still can get CAO behaving objects when accessing the Pool Manager explicitly.

Custom Sinks and Custom Sink Providers
Setting up a custom sink requires the development of two classes: the custom sink class itself and a custom sink provider class. The latter has to be registered into the remoting infrastructure. The sole role of the sink provider is to return to the remoting infrastructure an instance of its associated custom sink when required.

Here is a remote configuration file where a custom sink provider is registered before the formatter

 Modifying Messages   and Headers
In order to decide how to hook into the remoting infrastructure you have to know what and how a message body and a message header can be modified within a custom sink.

The message body holds information such as the target class and method and method’s parameter values. The header basically holds the URL remoting will use to identify the object on the server side.

The message format changes while traveling along the sinks. Before the formatter on the client side, or after the formatter on the serve side, the message is exposed to custom sinks as a .NET provided object implementing the IMessage interface. You can easily examine all the Message properties but, unfortunately, it comes out that only the method’s parameter values can be modified within a custom sink, other properties are read only.

The message is build by the Transparent proxy (an entity which can’t be overridden or customized) and the methods which would let us build a new message from scratch are defined as protected.

Of course we can do whatever we like with the message when it’s turned into its stream based form (after the formatter on the client side or before the formatter on the server side). Unfortunately in this case it’s much more difficult to modify it.

It is somehow feasible if the selected formatter is the SOAP one. If the selected channel formatter is the binary one this is practically impossible since the binary format is Microsoft proprietary.

With such limitations in mind, let’s concentrate on URL modification to trick client activation requests.

The idea is basically the following. If we put a custom sink on the server side after the formatter we can intercept the message and proceed as follow:

  • The required type is extracted from the message.

  • A check is made to see if the class is poolable (that is, if the Pooling attribute is attached to the class).

  • If it is, the Pool Manager is contacted via a shared method and asked to return an instance of the specified type from the pool.

  • A random URI (I use GUIDs) is defined and the acquired object instance is explicitly published via the RemotingServices.Marshal method using that URI.

  • The header URI property is modified to have the message request target the published object (the URI provided by the client could have been any dummy one since it’s overridden at this stage).

  • The request is forward to the next sink.

  • On return the object is disconnected from remoting (RemotingServices.Disconnect), thus providing SingleCall semantic.

Unfortunately this approach has a drawback. After .NET Framework SP2, the formatter itself checks if the specified object URI in the header is a valid one and raise an error if it’s not the case (this didn’t happen before SP2; this check was done later in the sink chain). For this reason I had to move the custom sink before the formatter. Unluckily doing this you need to modify slightly the technique described above.

Before the formatter the message is in its byte stream form, thus making hard to find out what object the client is trying to activate.

The easier way to pass this information is to define a standard for the URI format the client must specify to activate a pooled object. This format must contain the required class name and the assembly name where the class is defined.

The required format is:

,

In the custom sink the URI is read from the message header and the assembly and class name information are extracted from the URI string. From this point on, the steps are the same as described above.

In the step-by-step commented code listing below you can see the described technique in action:

Public Function ProcessMessage( _    ByVal sinkStack As IServerChannelSinkStack, _    ByVal requestMsg As IMessage, _    ByVal requestHeaders As ITransportHeaders, _    ByVal requestStream As Stream, _    ByRef responseMsg As IMessage, _    ByRef responseHeaders As ITransportHeaders, _    ByRef responseStream As Stream) As ServerProcessing _    Implements IServerChannelSink.ProcessMessage    Dim l_objmarshalbyref As MarshalByRefObject    Dim l_assembly, l_ClassName As String    'Acquires original URI    Dim originalURI As String = requestHeaders.Item("__RequestUri").ToString()        'Try to extract Assembly and Class Name    If IsPooledObjectURIFormat(originalURI, l_assembly, l_ClassName) = True Then

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap