c# – An elegant way to handle Event subscriptions?

If I have a class instance as Property, which has events and changes based on user input (for example, the user selects one from a list), I often find myself doing the following:

public MyClass MySelectedInstance
    get { return mySelectedInstance; }
        if (mySelectedInstance!= null) mySelectedInstance.myEventFired -= DoStuff;
        SetProperty<MyClass >(ref mySelectedInstance, value);
        if (mySelectedInstance!= null) mySelectedInstance.myEventFired += DoStuff;

As far as I understand, it is important to unsubscribe from events, so the GC can destroy objects. However, for single instance it is not the biggest of problems, but imagine MyClass contains a List of objects with events. Now every time the user would change selection, I have to go through the whole list and handle event subscriptions accordingly.

More often than not, if I find my code solutions not elegant enough, there is already a pattern out there to use. So the question is: How to do this kind of stuff?

woocommerce offtopic – Function to recalculate shipping costs on subscriptions after renewal with Automatewoo

I’ve got a funky plugin that was custom made that adds a new random product from a group that a customer subscribes to.

Problem is, that the shipping doesn’t change depending on which product is selected, it stays with whatever was chosen initially.

Rather than paying more money to redevelop something that might already exist, is there any code that will recalculate shipping costs based on the item in the subscription? I have automatewoo, so could use a custom function from that and run it after a subscription payment has completed, I just don’t know how to code it.

Any support appreciated!


icloud – Can’t delete payment method because active subscriptions but no active or hidden subscriptions

Stack Exchange Network

Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Object replication in Azure across subscriptions and accounts

I am trying to configure object replication for my blob storage container to another blob storage container in a different subscription that is in a different account. I can’t seem to figure out how to set that up so that I can see the destination subscription that is in a different account when configuring replication rules. Any ideas?

Easiest way to monetize your adult content:billing, subscriptions, video uploads | NewProxyLists

Adult web system 2.5 – Easy tube – The easiest way, how to publish materials!

Have you recorded a high quality video? Have you taken interesting pictures? Do you have enough adult material and would you like to sell it? Are you already familiar with web programming? Do you want to avoid implementing a payment gateway? Do you want to have a simple, well-arranged website and sell the materials easily? Without worries?

Click Here for more details: https://www.mydreams.cz/en/adulthosting-plans/adult-web-system.html

The “Adult web” service pack is exactly what you need. Within the package, you will receive a complete web solution where you can easily upload up to 4K (Ultra-HD) videos and album photos. We will customize the responsive template to make the web match your content. We will create a payment gateway and link it to the site. We will make you familiar with the terms and payments of the payment gateway.

MyDreams innovations s.r.o. is a company that has been operating in the field of hosting services since 2004. First as a self-employed person and now as a company. MyDreams team members are people with many years of experience in hosting, web design and web development.

Adult web system features:

  • You can upload videos on the web in Full-HD or Ultra-HD quality.
  • Full-HD stream and Ultra-HD download.
  • All uploaded videos are automatically converted to Full-HD quality web format.

Package Parameters:

  • Server with sufficient performance and space for your data
  • Unlimited traffic
  • Responsive graphic template
  • Your company logo
  • Ultra-HD download
  • Full-HD stream
  • Full videos
  • Trailers
  • Main trailer
  • Category
  • Models
  • Photogallery with albums
  • Paid Section gallery
  • Paid Section videos
  • Admin Section
  • Client Section
  • Tariff settings
  • Text settings
  • Setting SEO parameters
  • No-recruiting membership
  • Recruiting membership
  • Payment card – VISA and MasterCard
  • Bank transfer EUR, USD, CZK
  • Bitcoin payment
  • Ability to set publication restrictions to some countries
  • Admin interface in English or Czech

Package price:
The price of “Adult Web system” package consists of a one-time price and a year-long administration of the server.

One time:
20 000 CZK/930 USD
– Creating a graphic template. Establishment and connection to the payment gateway

  • Server with sufficient performance and unlimited data transmission
  • Server Administration
  • 500 USD Mastercard fee, or you can use the MyDreams ccBill subaccount without having to pay a MasterCard fee.
  • ccbill

References (Demo):
If you have any questions, you are free to CONTACT US! Based on the information, we will be able to propose a suitable server with sufficient performance.

Adult services are also just services. We will process your request professionally and discreetly.


Rxjs – How to rewrite nested subscriptions

I need an help to rewriting this subscription, it works but I don’t like how it looks like. I’m working in Angular and in Ngonit of my dashboard component I need to call two services. For doing it I need two parameters: idCompany and accountId. I memorize value in "idCompany" attribute from selectedCompany$ observable, after that I need to memorize value in "account" attribute from the account$ observable and after this I need to call two services:

getDashboardInfo that has accountId and idCompany as parameters, and
getAvailableSpace that has idCompany as parameter.

This is my function:

idCompany: number;
account: Account;
account$ = this.store.select(accountQuery.getAccount);
selectedCompany$ = this.store.select(companyQuery.getSelectedCompany);
space: number;

this.selectedCompanySubscription = this.selectedCompany$.subscribe(res => {
  if (res !== null && res !== undefined) {
    this.idCompany = res.id;
      map(account => {
        this.account = account;
        this.getDashboardInfo(this.account.id.toString(), this.idCompany.toString(), 'time');
        this.dashboardService.getAvailableSpace(this.idCompany).subscribe(space => {
          this.space = space.value;

WordPress Woocommerce add custom field(s) Simple Subscriptions

I am using WordPresss’ Woocommerce plugin and Woocommerce Subscription plugin and its working fine as per my expectations.

However, I have a one custom requirement from client. I want to add custom field(s) while creating a product in Variable Subscriptions and Simple Subscriptions.

I have added custom field(s) in Variable Subscriptions using below code and its working as per my expectations. Here is my code.


// Showing fields for variable subscriptions 
add_action('woocommerce_product_after_variable_attributes', 'show_WC_Product_Variable_Subscription_Variation_Custom_Fields', 10, 3);

// Saving fields for variable subscriptions 
add_action('woocommerce_save_product_variation', 'save_WC_Product_Variable_Subscription_Variation_Custom_Fields', 10, 2);

function show_WC_Product_Variable_Subscription_Variation_Custom_Fields($loop, $variation_data, $variation) {
            'id'            => "my_text_field{$loop}",
            'name'          => "my_text_field({$loop})",
            'value'         => get_post_meta($variation->ID, 'my_text_field', true),
            'label'         => __('Some label', 'woocommerce'),


function save_WC_Product_Variable_Subscription_Variation_Custom_Fields($variation_id, $loop) {

    if (empty($variation_id)) return;

    $text_field = $_POST('my_text_field')($loop);
    update_post_meta($variation_id, 'my_text_field', esc_attr($text_field));

And here is how it looks like now working fine.

enter image description here

As you can see in screenshot above, the last field labeled as “Some label” .. my custom field added.

However, I want to add this same field which I set Simple Subscription. Here I mean.

enter image description here

As you can see, I want that same custom fields to show and save here as well ..

I have researched but yet not able to find any hook.

Can someone guide me please how can I achieve this.


i18n l10n – How to make the language of the subscriptions be the currently language in Simplenews

I’m implementing simplenews on a Drupal 8 Website, and I currently came across a problem with the anonymous user subscriptions to the newsletters.

According to the documentation of simplenews, when someone subscribe anonymously to a Newsletter, the preferred language would be the interface language of the page, but the language setted to the subscriber is always being the default language of the website, I tried many configurations about language and have no success.

So, that is the problem, I want that when someone subscribe to the newsletter, the language setted for the subscriber be the interface language of the page, please tell if anybody knows a solution for this.

Thanks in advance.

8 – Commerce framework: How on earth do I offer recurring license subscriptions?

Commerce License is in alpha. That means it is not generally ready for production use.

Further, Commerce Recurring is in beta, but the module page itself notes, as of January 2021:

This module is not production ready! Expect pain.

Using these modules now will require writing custom code and debugging; there is no out-of-the-box easy solution at this time.

However, I needed a license solution today, so I decided to implement one in Commerce without using these modules. Here’s a rough sketch of how I did it. Note that I am renewing the subscriptions manually, which is prone to human error; the following flow only provides a UI for users to purchase and configure the period of their subscriptions.

However, this example will hopefully give you an idea of the large amount of work involved in getting subscriptions set up. It’s not easy; if you want something simpler but still not easy, and in which the subscriptions actually recur properly, you could look at Recurly or other SaaS.

  1. Add a role, Premium user. Give this role the additional permissions that users will purchase.
  2. Add a datetime field to the user account, Subscription expire date. Add another list text field to the user account, Subscription type.
  3. Add custom code to restrict permission for the Subscription expire date field to admins only.
  4. Configure your store + checkout flow in Commerce.
  5. Create a product type “My license.” Add product variations “One year autorenew,” “One month,” etc.
  6. Add an EventSubscriber to Commerce to automatically set the user account field Subscription expire date when the purchase is complete. Also, add a redirect to skip the cart because for individual users, having a cart makes no sense for licenses + I don’t want users to purchase multiple subscriptions.

Skipping carts requires this patch in composer.json:

    "drupal/commerce": {
        "allow order types to have no carts": "https://www.drupal.org/files/issues/2020-10-05/2810723-130.patch"

Even with all this effort, you will still have to renew the subscriptions manually. I did this by adding a view for the admin of “expiring subscriptions” and then using the token stored in the user account by Commerce Stripe to make the recurring payment.

Custom EventSubscriber

Notes about this code: It includes an additional field, a list text field on the user account to let the users change between different subscription types. This allows members to change from a monthly to an annual subscription, or vice versa.

It also assumes that “monthly” subscriptions are always 30 days.

First, services.yml:

    class: DrupalMYMODULEEventSubscriberMyModuleEventSubscriber
    arguments: ('@request_stack', '@logger.factory', '@datetime.time')
      - { name: 'event_subscriber' }

And here’s the Event Subscriber from mymodule/src/EventSubscriber/MyModuleEventSubscriber.php:


namespace DrupalMYMODULEEventSubscriber;

use DrupalComponentDatetimeTimeInterface;
use DrupalCoreLoggerLoggerChannelFactory;
use DrupaldatetimePluginFieldFieldTypeDateTimeItemInterface;
use Drupalstate_machineEventWorkflowTransitionEvent;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use Drupalcommerce_cartEventCartEntityAddEvent;
use Drupalcommerce_cartEventCartEvents;
use DrupalCoreUrl;
use SymfonyComponentHttpFoundationRedirectResponse;
use SymfonyComponentHttpFoundationRequestStack;
use SymfonyComponentHttpKernelKernelEvents;
use SymfonyComponentHttpKernelEventFilterResponseEvent;

 * Event Subscriber MyModuleEventSubscriber.
class MyModuleEventSubscriber implements EventSubscriberInterface {

   * The request stack.
   * @var SymfonyComponentHttpFoundationRequestStack
  protected $requestStack;

   * Logger factory.
   * @var DrupalCoreLoggerLoggerChannelFactory
  protected $loggerFactory;

   * The time service.
   * @var DrupalComponentDatetimeTimeInterface
  protected $time;

   * MyModuleEventSubscriber constructor.
   * @param SymfonyComponentHttpFoundationRequestStack $request_stack
   *   The request stack.
   * @param DrupalCoreLoggerLoggerChannelFactory $logger_factory
   *   The logger factory.
   * @param DrupalComponentDatetimeTimeInterface $time
   *   The time service.
  public function __construct(RequestStack $request_stack, LoggerChannelFactory $logger_factory, TimeInterface $time) {
    $this->requestStack = $request_stack;
    // Specify that logs should be for this module.
    $this->loggerFactory = $logger_factory->get('mymodule');
    $this->time = $time;

   * {@inheritdoc}
  public static function getSubscribedEvents() {
    $events = (
      'commerce_order.place.post_transition' => 'postPlaceTransition',
      'mymodule_order.fulfill.post_transition' => 'onFulfillTransition',
      CartEvents::CART_ENTITY_ADD => 'tryJumpToCheckout',
      KernelEvents::RESPONSE => ('checkRedirectIssued', -10),
    return $events;

   * Set fields and roles for user accounts that purchase subscriptions.
  public function postPlaceTransition(WorkflowTransitionEvent $event) {
    $order = $event->getEntity();

    $order_type = $order->bundle();

    if ($order_type === 'MYORDERTYPE') {
      $price_monthly = 500;
      $price_annual = 5000;
      $subscription_monthly = 'monthly';
      $subscription_annual = 'annual';
      $customer = $order->getCustomer();

      $total_price_array = $order->get('total_price')->getValue();
      $total_price = intval(round($total_price_array(0)('number')));
      $drupal_now_timestamp = $this->time->getCurrentTime();
      $days_in_month = 30;
      $seconds_in_month = 60 * 60 * 24 * $days_in_month;
      $seconds_in_year = 60 * 60 * 24 * 365;
      $subscription_end_timestamp = '';
      // If the user has already purchased, extend the subscription.
      if ($customer->hasRole('subscriber')) {
        $current_subscription_datetime = $customer->get('field_datetime_sub_end')->value;
        $current_subscription_datetime_object = DateTime::createFromFormat(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, $current_subscription_datetime);
        $current_subscription_timestamp = $current_subscription_datetime_object->getTimestamp();
        if ($total_price === $price_monthly) {
          $subscription_end_timestamp = $current_subscription_timestamp + $seconds_in_month;
          $customer->set('field_list_text_sub_period', $subscription_monthly);
        elseif ($total_price === $price_annual) {
          $subscription_end_timestamp = $current_subscription_timestamp + $seconds_in_year;
          $customer->set('field_list_text_sub_period', $subscription_annual);
        else {
          $this->loggerFactory->error('Total price was outside the assigned range for subscription. (has subscriber role)');
      // Set the date for a new subscription.
      else {
        // The user is henceforth a subscriber.

        if ($total_price === $price_monthly) {
          $subscription_end_timestamp = $drupal_now_timestamp + $seconds_in_month;
          $customer->set('field_list_text_sub_period', $subscription_monthly);
        elseif ($total_price === $price_annual) {
          $subscription_end_timestamp = $drupal_now_timestamp + $seconds_in_year;
          $customer->set('field_list_text_sub_period', $subscription_annual);
        else {
          $this->loggerFactory->notice('Total price was outside the assigned range for subscription. (no subscriber role)');
      $subscription_end_date_object = new DateTime();
      $subscription_end_date_value = $subscription_end_date_object->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
      $customer->set('field_datetime_sub_end', $subscription_end_date_value);


   * Tries to jump to checkout, skipping cart after adding certain items.
   * @param Drupalcommerce_cartEventCartEntityAddEvent $event
   *   The add to cart event.
  public function tryJumpToCheckout(CartEntityAddEvent $event) {
    // $purchased_entity = $event->getEntity();
    // if ($purchased_entity->bundle() === 'training_event') {
    $checkout_url = Url::fromRoute('commerce_checkout.form', (
      'commerce_order' => $event->getCart()->id(),
    $this->requestStack->getCurrentRequest()->attributes->set('mymodule_jump_to_checkout_url', $checkout_url);
    // Clear status message "Product added to your cart".
    // @todo fix deprecated code.
    // drupal_get_messages('status');.

   * Checks if a redirect url has been set.
   * Redirects to the provided url if there is one.
   * @param SymfonyComponentHttpKernelEventFilterResponseEvent $event
   *   The response event.
  public function checkRedirectIssued(FilterResponseEvent $event) {
    $request = $event->getRequest();
    $redirect_url = $request->attributes->get('mymodule_jump_to_checkout_url');
    if (isset($redirect_url)) {
      $event->setResponse(new RedirectResponse($redirect_url));


plugins – Woocommerce Subscriptions weekly billing issue: Customer is charged twice in first week

Expected behaviour:
Trying to have customers pay when they signup THEN align with the renewal day of Wednesday, obviously excluding the current billing cycle which they have already paid for.

Actual behaviour:
1.Customer signs up on e.g. Tuesday and pays full price
2.THEN our weekly billing day (Wednesday) is reached and they are charged again for the subsequent delivery. This means they are being charged twice before they even receive the product!!.