Shared Web Worker with Dedicated Web Worker as failover – Lazy Load Example

I wanted to post something in Daniweb for a while but I didn't had anything new. Recently I decided to write a new implementation for websocket connections client side using Shared Web Workers. Shared Web Workers are supported today by most browsers for desktop but few for mobile devices , so it had to have a fallover mechanism to Dedicated Web Workers. I searched but I didn't found an example , so I am posting it here. Moreover since we will have a worker not in main thread it would be great to have the option for callback functions for other uses than WebSockets. I implemented these without any framework to keep it as simple as possible and here it is an example of this for something common and useful , lazy loading images . It needs to be modified if you are going to use it to be adjusted to your needs and to add error handling and arguments checking at least.

We are going to user five files in a folder. Two images: one imageExample.jpg that is going to be the image to lazy load and a transparent1x1.png that is a transparent image 1px x 1px that we will use as placeholder src for the image before is loaded.

Lets start with the index.php (I am using PHP here but you can use any language)

<?php
/*
getting the root URL of the project is beyond the scope of this ,
but here is a quick implementation  
 */
$v = $_SERVER["SERVER_PROTOCOL"] ; 
$v = mb_strtolower(mb_substr($v, 0 , mb_strrpos($v, "/")));
if(isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on")
{
    $v .= "s";
}
$root = $v."://".$_SERVER['HTTP_HOST']; 
$v = $_SERVER["PHP_SELF"];
$v = mb_substr($v, 0 , mb_strrpos($v, "/"));
$root .= $v;
?>
<html>
<head>
    <title>
        JavaScript Shared Web Worker with Dedicated Web Worker as failover 
        - Lazy Loading Images example
    </title>
    <style>
        /* IntersectionObserver works better with blocking elements to determine if are 
            intersected with the viewport */
        picture,img
        {
            display: inline-block;
            vertical-align: middle;
        }
    </style>
</head>
<body>
    <!-- all the img tags inside picture elements will be loaded with the 
        src of the noscript img tag when they appear on screen   -->
    <picture>
        <noscript>
            <img src="<?=$root?>/imageExample.jpg" alt="example image" width="800" height="500" />
        </noscript>
        <img src="<?=$root?>/transparent1x1.png" alt="example image" width="800" height="500" />
    </picture>
    <script type="text/javascript">
        /*
            load the example.js after DOMContentLoaded or if that doesn't fired on window.onload 
            and then call the init of the example object that instantiated there 
        */
        var _fncl=false;
        _fnc=function()
        {
            _fncl=true;
            var s = document.createElement("script");
            s.async=true;
            s.src="<?=$root?>/example.js?"+<?=date("U")?>;
            s.addEventListener("load", function(e)
            {
                    _.init("<?=$root?>");
            }, false);
            document.body.appendChild(s);
        };
        window.addEventListener("DOMContentLoaded", _fnc);
        window.onload=function(){if(!_fncl){_fnc();}};
    </script>  
</body>
</html>

As you can see it is very simple , now lets move to the main JavaScript file that will be loaded the example.js

/*
    this is an example of how the concept works it doesn't have error handling 
    or checking arguments for their correct type or even existence , 
    in real life projects those should implemented 
*/
const _ = new (function() // _ object holds the core functionalities  
{
    var _this = this; 
    var worker = null;
    var shared = false;
    var privateRoot = null;
    var index = 0; 
    var works = {}; 

    this.init = function(root)
    {
        privateRoot = root; 
        shared = !!window.SharedWorker; // if Shared Web Workers are supported
        //use Dedicated Web Worker when developing new methods 
        //  in order to view the errors in console 
        //shared = false;
        setWorker();
        app.init(); // ready to init the app object
    }

    this.root = function()
    {
        return privateRoot; 
    };

    this.getWorkKey = function()
    {
        index++;
        return "w"+index; 
    };

    /*
        request a work from the worker with callback function 
        dataObj is the object that will be send to the worker 
            , it must contains at least an action that will be a function of the worker 
            and any other data we might use there 
        fnc is the the callback function example: function(responseDataObj,argObj){} 
        argObj contains all other data we might need along with the response data   
    */
    this.work = function(dataObj,fnc,argsObj)
    {
        let wKey =  _this.getWorkKey();
        dataObj.wKey = wKey;
        works[wKey] = [fnc,argsObj];
        worker.postMessage(dataObj);
    };

    function setWorker()
    {
        if(shared)// instantiate the worker 
        {
            let w = new SharedWorker(_this.root()+"/worker.js");
            worker = w.port;
            worker.start();
        }
        else 
        {
            worker = new Worker(_this.root()+"/worker.js");
        }

        var handler = function(event)//handle incoming events from worker
        { 
            let data = event.data;
            if("n" in data && data.n == "u") // pong (ping response) that this page is still alive 
            {
                worker.postMessage({n:"y"});
            }
            else if("log" in data) // let the worker send messages to window console 
            {
                window.console.log(data.log);
                //worker.postMessage({n:"y"});
            }
            else if(data.wKey in works)
            {
                let arr = works[data.wKey]; // the array that is store in works object 
                // that has as first element the function and second the arguements object 
                arr[0](data,arr[1]); // call the callback function
                works[data.wKey] = null; 
                delete works[data.wKey]; // try to remove it from memory when gc will pass
            }
        };

        if(shared) // attach the handler to the worker 
        {
            worker.onmessage = (event) => {
                handler(event);
            };
        }
        else
        {
            worker.addEventListener('message', event => 
            {
                handler(event);
            });
        }
    }


})();


const app = new (function() //app object has specific code for this app 
{
    var _this = this; 
    this.lazyLoadObjerver = null;

    this.init = function()
    {
        setIntersectionObserver();
    };


    function setIntersectionObserver()
    {
        if ("IntersectionObserver" in window)
        {
            _this.lazyLoadObjerver = new IntersectionObserver(_this.lazyLoader);
        }
        _this.lazyLoad();
    }



    this.lazyLoad = function()
    {
        const els = document.getElementsByTagName("picture");
        for (const el of els)
        {
            if(_this.lazyLoadObjerver == null) // if the browser doesn't support IntersectionObserver
            {
                const src = el.querySelector("noscript").innerHTML
                    .match(/.*src=["']([^"]*)['"].*/)[1];// get src of the image
                el.querySelector("img").setAttribute("src",src);
            }
            else 
            {
                _this.lazyLoadObjerver.observe(el);
            }
        }
    };

    this.lazyLoader = function(entries, observer)
    {
        entries.forEach(function(entry) 
        {
            const el = entry.target;
            if (entry.isIntersecting) 
            {
                if(el.getAttribute("class") != "lz")
                {


                    const src = el.querySelector("noscript").innerHTML
                        .match(/.*src=["']([^"]*)['"].*/)[1];// get src of the image
                    // data object for the worker request
                    const dataObj = {action:"loadBlob",url:src};
                    // arguements object for the callback function
                    const argObj = {el:el}; 
                    // the callback function;
                    const fnc = function(data,arg){
                        const img = arg.el.querySelector("img");
                        arg.el.setAttribute("class","lz");
                        img.setAttribute("src",URL.createObjectURL(data.blob));
                    };
                    _.work(dataObj,fnc,argObj);

                }
            }
        });
    };

})();

And finally the worker.js file , it worth mentioning that if you are going to use Shared Web Workers I couldn't find any other way then a separate file.

(I am adding it as code snippet because without code snippet it doesn't allow me to post)

I hope to enjoy it , I added some comments inside the code but feel free to ask anything related. Also any other ideas would be welcomed

vb.net – how to delete columns by name in Excel

Hello,

i have an excel-file whith 2 sheets.
There are much columns, but I need only a few of them.
I want to delete some columns by name.

I found this code but, I dont know why it doesnt work!?!?
It tells me ".UsedRange" is wrong.

Can you help me, please?

(Reference "Microsoft Excel 16.0 Object Library" is already added in my project)

Option Strict On
Imports System.IO
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Excel As Microsoft.Office.Interop.Excel.Application
        Dim xlWB As Microsoft.Office.Interop.Excel.Workbook
        Dim xlWSTabelle1 As Excel.Worksheet = CType(CType(xlWB.Sheets("Tabelle1"), Excel.Worksheet), Excel.Worksheet)
        Dim xlWSTabelle2 As Excel.Worksheet = CType(CType(xlWB.Sheets("Tabelle2"), Excel.Worksheet), Excel.Worksheet)
        Dim Path = "D:\Test.xlsx"
        Excel = New Microsoft.Office.Interop.Excel.Application
        xlWB = Excel.Workbooks.Open(Path)

        Dim xlSheets As Object
        Dim xlSheetsArray(0 To 1) As Excel.Worksheet
        Dim k As Long
        Dim i As Long

        xlSheetsArray(0) = xlWSTabelle1
        xlSheetsArray(1) = xlWSTabelle2


        For Each xlSheets In xlSheetsArray

            With xlSheets

                k = .UsedRange.Columns.Count

                For i = k To 1 Step -1
                    Select Case LCase(.UsedRange.Cells(1, i).Value)

                        'Keep these columns
                        Case "#Num", "Product A", "Number 1" '...

                        Case Else

                            'Delete all others not listed above
                            .UsedRange.Columns(i).Delete()

                    End Select
                Next i

            End With

        Next xlSheets
    End Sub
End Class

Shift4Shop Review

Formerly 3dcart, Shift4Shop offers free, enterprise-grade ecommerce functionality to help you build your online store and start selling. You get nearly all the features to start and grow your online business, including powerful tools like a robust website builder, product and order management functionalities, customer marketing tools, and round-the-clock technical support. 

The biggest catch is that the free end-to-end ecommerce plan is only available to US merchants. Moreover, you have to use the in-house payment processor, Shift4 Payment, to get paid, which isn’t too bad as it’s one of the leading payment processing providers. Plus Shift4Shop doesn’t charge you any monthly fees to use its ecommerce platform.

Shift4Shop brand logo.

Shift4Shop Compared

Shift4Shop made it on my top list for the best value. While it’s a great option, the best ecommerce website builder is Shopify because of its robust features and tools that provide you with everything to build an online store. Get started with a three-day free trial today.

  • Shopify — Best all-around ecommerce website builder
  • Wix — Best for launching an online store in minutes
  • Hostinger — Best for simple online stores
  • BigCommerce — Best site builder for multichannel selling
  • Squarespace — Best for social
  • Square Online — Best for physical retailers
  • Weebly — Best for small sellers who don’t want to grow
  • Shift4Shop — Best value

See our top picks for the best ecommerce website builders.

About Shift4Shop

Shift4Shop is a comprehensive ecommerce website builder that caters to businesses of all sizes and industries. Using its innovative turnkey solution, you can easily build a secure website and leverage various customer marketing tools to boost sales. The company also offers a range of top-notch features, including social media marketing, SEO, and an extensive marketplace with third-party devs, affiliates, and experts.

A global leader in financial technology, Shift4 acquired 3dcart and rebranded it as Shift4Shop. Along with the powerful ecommerce solution, Shift4 also offers Shift4Shop users a seamless online payments platform that makes it easier for them to get paid.

Shift4Shop Health and Stability 

Shift4Shop is a private company with hundreds of employees and a stable customer base. And while it may be less popular than its counterparts like Shopify and Wix, you can be sure this company isn’t going anywhere.

One of the main reasons behind this is its parent company, Shift4 Payments. A publicly listed company with over $13.7 million in funding, Shift4 Payments has been doing consistently well in the market. 

Keeping all this in mind, I firmly believe Shift4Shop is an ecommerce website builder you can trust.

Shift4Shop Pricing

Shift4Shop’s unlimited, enterprise-grade plan costs an impressive $0. It includes the feature-packed ecommerce platform, an SSL certificate, a domain name, and a huge selection of customizable themes. However, you need to process a minimum of $500 per month with Shift4 Payments through your Shift4Shop store to waive the SaaS fee.

Get started with Shift4Shop for free.

Shift4Shop Pricing Structure 

Shift4Shop has conditional pricing, under which you won’t need to pay any charges if you meet their monthly minimum of ecommerce sales ($500 with Shift4 Payments). Otherwise, you need to pay a monthly SaaS fee. Shift4Shop hasn’t published information on its website about how much this costs, so you’ll have to contact its sales team for more information.

Shift4Shop Pricing Comparison

Compared to Shopify, Shift4Shop can be free (if you meet the stated requirements), but you must be based in the United States and agree to use Shift4 Payments to process payments. On the other hand, Shopify has no free plan, and you have to pay monthly or yearly to continue using it. 

Wix is another popular ecommerce web builder that offers a free plan and incredibly affordable paid plans. The biggest advantage of Wix over Shift4Shop is its predictability and affordability. Sure, Shift4Shop is free upfront, but if you don’t process at least $500 through Shift4 Payments, you’ll have to pay a monthly SaaS fee.

Shift4Shop Trials and Guarantees

Being a free ecommerce website builder, it makes sense that Shift4Shop doesn’t offer any free trial or refund guarantee. 

Shift4Shop Ecommerce Website Builder Review

Shift4Shop’s biggest advantage as an ecommerce website builder is the generous feature offering despite being free. You get an enterprise-level website builder, over hundred themes, tons of SEO tools, unlimited product listings, and more. 

The software is also customizable, where you can add products to your store, choose themes, and select payment methods. Even from the buyer’s perspective, the Shift4Shop storefront is easy to navigate, right from product browsing to checking out. 

As for the caveats, you should know the zero-cost version of Shift4Shop is only available to US customers, and you’ll need many add-ons to run your store effectively, among a few others.

See my top picks for the best ecommerce website builders to find the right fit for your needs.

What Makes Shift4Shop Ecommerce Website Great

A screenshot of Shift4Shop's ecommerce features and functionality.
Shift4Shop offers enterprise-grade ecommerce functionality and features for free.

Large selection of features: Shift4Shop has one of the most generous feature selections, despite the affordable price tag. Ecommerce tools include single-page checkouts, digital downloads, two-factor authentication, recurring orders, and unlimited product variations. 

You can also leverage the built-in marketing and SEO tools, discount codes and coupons, affiliate programs, loyalty reward programs, and back-in-stock alerts to drive sales. While the reporting and analytics aren’t as advanced as that of Shift4Shop’s competitors, they get the job done.

Higher level of customization: Shift4Shop makes creating a fully customizable and responsive website easier than ever. Thanks to its design software, you get access to its core template engine, where you can create your own themes, plus all Shift4Shop themes have Google AMP-enabled product pages, deferred JavaScript and CSS, and a conversion-optimized checkout, among other benefits, which is another plus. 

Let’s also not forget the flexible drag-and-drop HTML editor and the core theme editor that lets you customize your theme design to your needs, from colors to topography to buttons. Moreover, you can preview every change in real-time, which won’t be visible to your shoppers until you ‘Save’ them, confirming the changes.

Excellent management functionalities: Another benefit of Shift4Shop is its comprehensive management software that allows you to manage orders and products from a centralized place. You get a complete toolset comprising a convenient dashboard, new order notifications, status updates for customers, and advanced automation rules to better manage orders. Further, you can see your new inventory catalog by organizing each product into a list format. Other tools include bulk import and export, videos and dynamic zoom, detailed project reports, and unlimited categorization.

Reliable ecommerce hosting: Shift4Shop’s web hosting is an excellent addition to its ecommerce website builder platform, thanks to a 99.9% uptime guarantee and PCI certification and security. Other features include a free domain name with yearly renewals, monthly transparent upgrades, FTP access to files, daily backups, and a 256 Bit SSL certificate. 

Currently, Cloudflare powers all Shift4Shop online stores, which gives you the benefits of its global content delivery network, DDOS attack protection and mitigation, and faster loading speeds by extension.

Mobile-friendly: Shift4Shop makes your online stores mobile-responsive, meaning your website can adapt and adjust to different screen sizes and resolutions. This is necessary to provide shoppers with a seamless shopping experience, regardless of the device they use to visit your site. With an increasing number of people using mobiles for shopping, having a mobile-optimized store can work wonders to secure more sales.

Where Shift4Shop Ecommerce Website Builder Falls Short 

A screenshot from Shift4Shop warning to international merchants notifying them that the ecommerce plan is only available to United States merchants.
Shift4Shop’s end-to-end ecommerce plan is only available to United States merchants currently 

Unpredictable pricing: Shift4Shop markets itself as a free ecommerce website builder, but this can change quickly if you don’t meet the $500 monthly payment requirement. Moreover, its modules are expensive, and the free themes are limited. To design a stunning and optimized website, you may find yourself investing in paid themes. Additionally, the zero-cost version of the platform is only available to US users.

Poor customer support: Several customer reviews have found Shift4Shop’s customer support severely lacking, especially for users outside the United States. One user pointed out they didn’t receive a response for days, while another expressed disappointment with a customer service representative’s unhelpful and rude behavior.

Minimal reporting capabilities: Shift4Shop’s reporting capabilities are lacking. While it offers detailed profit reports, specialty customers and inventory reports, and rewards use, you’ll likely need additional reporting tools for more strategic operations reviews and decision-making.

Requires multiple add-ons: When building your online stores through Shift4Shop, be prepared to install multiple add-ons (similar to WordPress plugins) to maximize functionality. For example, if you want to add a shopping cart to your online store, you must install software to make this happen. Similarly, you’ll need to install a ‘Buy’ button on your website’s backend to allow shoppers to check out more conveniently. 

Don’t get me wrong—it’s great that Shift4Shop offers these capabilities, but installing too many add-ons can cause your website to run slower than usual or even crash entirely.

Shift4Shop Ecommerce Website Builder Compared

Where Shift4Shop makes a great choice, it does have a few hard-to-ignore caveats. Keeping this in mind, the best ecommerce website builder is Shopify simply because it offers everything you may need to build and run an ecommerce website—all in a single platform. 

  • Shopify — Best all-around ecommerce website builder
  • Wix — Best for launching an online store in minutes
  • Hostinger — Best for simple online stores
  • BigCommerce — Best site builder for multichannel selling
  • Squarespace — Best for social
  • Square Online — Best for physical retailers
  • Weebly — Best for small sellers who don’t want to grow
  • Shift4Shop — Best value

Shift4Shop Shopping Cart Software Review

A screenshot from Shift4Shop detailing the customizable features and settings for the cart and checkout process.
Shift4Shop offers tons of customization features for its checkout system.

Shift4Shop has one of the most customizable and flexible shopping cart solutions that lets you optimize your checkout to offer seamless, hassle-free experiences to shoppers. They can view, edit, and save carts to purchase later, helping drive sales.

Create single-page or multi-page checkouts, each personalized to your liking. The fact that you don’t need to pay any transaction fees is another cost-saving advantage. Shift4Shop will also auto-calculate shipping and taxes in your customer’s cart to avoid total surprises.

Aside from these, everything we broke down above for ecommerce website building is also relevant to shopping cart experiences.

Here’s a quick look at how Shift4Shop stacks against other shopping cart software solutions on the market:

  • Shopify — Best for one-click checkout
  • Ecwid — Best for high security
  • Shift4Shop — Best for customizable checkout
  • Shopaccino — Best for rewarding customers
  • OpenCart — Best free shopping cart software
  • X-Cart — Best for high-volume sales

Final Verdict

Keeping in mind the pros and cons, I believe Shift4Shop is an excellent choice for ecommerce website building and adding a shopping cart—provided you’re a US resident. Thanks to its excellent feature offering, customization capabilities, and management functionalities, it really stands out from its competitors. But if you’re an international user, you may want to check out other solutions like Shopify and Wix.

gRPC on the Client Side

Most inter-systems communication components that use REST serialize their payload in JSON. As of now, JSON lacks a widely-used schema validation standard: JSON Schema is not widespread. Standard schema validation allows delegating the validation to a third-party library and being done with it. Without one, we must fall back to manual validation in the code. Worse, we must keep the validation code in sync with the schema.

XML has schema validation out-of-the-box: an XML document can declare a grammar that it must conform to. SOAP, being based on XML, benefits from it, too.

Steel Threads Are a Technique That Will Make You a Better Engineer

Steel Threads are a powerful but obscure software design approach. Learning about Steel Threads will make you a better engineer. You can use them to avoid common problems like integration pain, and you can use them to cut through the complexity of system design.

So Obscure It Was Deleted From Wikipedia in 2013

How unknown are Steel Threads? The concept was deleted from Wikipedia in 2013 because “the idea is not notable within Software Engineering, and hasn’t received significant coverage from notable sources.” Let’s add to the coverage, and also talk through why it is such a useful approach.

Digital Standee

A digital standee is a digital signage display that is designed to look like a traditional standee or cutout display. Digital standees typically consist of a high-resolution LCD or LED screen mounted on a freestanding or wall-mounted frame. They are used for advertising or information display purposes in a variety of settings, such as malls, trade shows, movie theaters, retail stores, and airports.

Digital standees can display dynamic content such as videos, images, animations, and text messages. They can be controlled remotely through a content management system, allowing for easy updating and scheduling of content. Digital standees are often used as a modern alternative to traditional printed standees, as they provide more flexibility, interactivity, and cost-effectiveness.

Getting a Private SSL Certificate Free of Cost

You work for any software deployment project, you deploy code in multiple environments and test it.  You test the site with HTTP, not HTTPS. Why? you need an SSL certificate for it. Getting a certificate for a lower environment could be difficult considering the cost. There is a way by which you can get a wildcard certificate and configure it with your website.

You can implement a PKI solution by using the AD CS (Active Directory Certificate Service) Windows Server role.