Mobile vs. Desktop CSS switch for Web app with Server Side rendering

When modern web application is built using Server Side Rendering (SSR) or Static Site Generator (SSG) technology it is hard to decide which version, Mobile or Desktop, should be served.

If you are not planning to have separate domains or subdomains for mobile-first and desktop-first versions of your Web App, here is a useful trick:

  // In main App or Layout component add following:

  const isMobile = useMediaQuery({ maxWidth: 767 }); // From any library

  useEffect(() => {
    if (isMobile) {
      document.body.classList.remove('onDesktop');
      document.body.classList.add('onMobile');
    } else {
      document.body.classList.remove('onMobile');
      document.body.classList.add('onDesktop');
    }
  }, [isMobile]);

This is sample for React library, but can be easily implemented for any other frontend framework.

The idea is simple: to have .onMobile or .onDesktop CSS class modifier for the <body> tag

In that case mobile specific styles are .onMobile .abc {...} and desktop CSS is .onDesktop .abc {...}

Happy hacking 🙂

Print all properties of JavaScript object

Printing out variables using console.log(variable) is a common way to debug Web Applications. But for object variables looking thru a tree of properties, prototype, and so on is quite annoying…

Here is a simple React Component for outputting a JavaScript object as a HTML <ul> list. Internal properties of object type are also printed as sublists:

export const ListObjectProps = (props) => {
  const { object } = props;

  function renderObjectProps() {
    const result = [];
    for (const property in object) {
      if (typeof object[property] === 'object') {
        result.push(
          <li key={property}>
            {property}:
            <ListObjectProps object={object[property]} />
          </li>
        );
      } else {
        result.push(<li key={property}>{`${property}: ${object[property]}`}</li>);
      }
    }
    return result;
  }

  return <ul>{renderObjectProps()}</ul>;
};

To print the object properties use following JSX code:

  <ListObjectProps object={anyJavaScriptObject} />

Destructuring and access “props” in the same time

Modern ES6 syntax of destructuring becomes popular between JavaScript developers:

const { a, b = defaultValue, c } = props;

React developers also start using this technique, especially for functional components:

const component = ({ index, data = 0, onClick }) => {
...
}

But a new problem (beside unreadable code…) appears:

How to access props.children and other sub-properties that were not extracted?

The solution is simple, use …spread JavaScript syntax!

const component = ({ index, data = 0, onClick, ...props }) => {
...
  <li key={index} onClick={onClick.bind(data)}>
    {props.children}
  </li>
...
}

This is the shortest single line solutions to unpack properties and access the rest of object’s data at the same time!

Anyway, you can always roll back to readable JS code, just add a single line:

const component = (props) => {
  const { index, data = 0, onClick } = props; 
...
  <li key={index} onClick={() => onClick(data)}>
    {props.children}
  </li>
...
}

List of Categories and List of Tags for WordPress website

There is no standard way to list non-empty categories or output the list of all tags in WordPress.

Here are code of two useful “shortcodes”:

/**
 * Generates list of categories. Set $atts('counts' => true) to show number of items in every category 
 */
function html_list_categories( $atts ) { 
	$terms = get_terms( 'category', array('hide_empty' => true) );
	if ( !$terms ) return '';

	if ( isset($atts['counts']) ) $showCounts = $atts['counts']; else $showCounts = false;

	$li_items = '';
	foreach( $terms as $t ) {
		$li_items .= "\t" . '<li class="cat-item"><a href="' . get_term_link($t) . '"'; 		  
			if ( $t->description != '') $li_items .= ' title="' . $t->description  . '"'; // add title if description is set		  
		$li_items .= '>'. $t->name . "</a>";
			if ( $showCounts ) $li_items .= " (" . $t->count . ")</li>"; // add count if required
		$li_items .= "\n";
	};

	return "\n<ul class=\"cat-list\">\r\n{$li_items}</ul>\n";
};
add_shortcode( 'list_categories', 'html_list_categories' ); 

/**
 * Generates list of tags. Set $atts('counts' => true) to show number of items for every tag
 */
function html_list_tags( $atts ) { 
	$terms = get_terms( 'post_tag', array('hide_empty' => false) );
	if ( !$terms ) return '';
  
	if ( isset($atts['counts']) ) $showCounts = $atts['counts']; else $showCounts = false;

	$li_items = '';
	foreach($terms as $t) {
		$li_items .= "\t" . '<li class="tag-item"><a href="' . get_term_link($t) . '"'; 		  
			if ( $t->description != '') $li_items .= ' title="' . $t->description  . '"'; // add title if description is set		  
		$li_items .= '>'. $t->name . "</a>";
			if ( $showCounts ) $li_items .= " (" . $t->count . ")</li>"; // add count if required
		$li_items .= "\n";
	};
	
	return "\n<ul class=\"tag-list\">\n{$li_items}</ul>\n";
}
add_shortcode( 'list_tags', 'html_list_tags' );

You can add this code directly into your WordPress theme (function.php or header.php file). But we strongly advice to use one of “code plugins”: Code Snippets, PHP Snippets, etc.

To output Category or Tag lists use “shortcode” in your post or page:

[list_categories]

[list_tags counts="true"]

You can style lists in your own way using CSS classes:

.cat-list {
...
}
.cat-item {
...
}
.tag-list {
...
}
.tag-item {
...
}

How to play system sounds in C#

.NET Framework allows playing system sounds using a simple code:

SystemSounds.[Type].Play(); 

But the SystemSounds class supports only 5 types of sound notifications: Asterisk, Beep, Exclamation, Hand, Question.

There is no easy way to play other standard sounds like LowBatteryAlarm, DeviceConnect, DeviceDisconnect, MailBeep, and others from the Windows Sound Scheme.

We in BgRnD are using following function in our C# projects:

public void PlaySystemSound(string RegistryName)
{
    string fileName = "";

    RegistryKey key = Registry.CurrentUser.OpenSubKey(String.Format(@"AppEvents\Schemes\Apps\.Default\{0}\.Current", RegistryName), false);
    try
    {
        fileName = (string)key.GetValue("", fileName);
    }
    finally
    {
        key.Close();
    }

    if (!File.Exists(fileName)) return;

    SoundPlayer player = new SoundPlayer(fileName);
    try
    {
        player.Play();
    }
    finally
    {
        player.Dispose();
    }
}

The function plays the sound resource specified by the RegistryName parameter. The set of possible names you can find in the System Registry at HKEY_CURRENT_USER\AppEvents\Schemes\Apps\.Default path.

Windows Sounds in the System Registry
Screenshot of Registry Editor to understand where to take Registry Names of system sounds.

You can freely use (copy and paste) this function into any of your projects.

If you still have any programming questions about playing the Windows sound notifications, feel free to ask.

Great tool to generate WMI queries

If you are planning to work with System.Management Namespace in the .NET framework, especially with ManagementObjectSearcher, ManagementObjectCollection, and ManagementObject classes, to perform different Windows Management Instrumentation (WMI) queries, take a look on WMI Code Creator tool by Microsoft.

Without this free utility, you’ll spending lots of time to test your WMI queries via console or other debugging methodology.

Using the WMI Query Builder you can browse WMI namespaces, execute methods and receive WMI events. Also you can automatically generate a working source code to perform WMI queries, either C# or Visual Basic.

Moreover, you can modify and run these management scripts by pressing a single button! Visual Studio is not required for that 🙂

Hack to Extend the Website content

In this article you’ll find some useful web-mastering tips and tricks. You can use this technique to make own web-site template engine or to extend the website functionality without ruining the old code as it was discussed in the previous article.

Define the new content as a variable. The previous and the next decorators could be dynamic arrays:

$sidebar_before[] = '<h2>Sidebar</h2>';
$sidebar_before[] = 'print_adsense';
$sidebar = <<<END
<p>
Some aside content here...
</p>
END;
$sidebar_after[] = 'block-links.inc';
$sidebar_after[] = '<h3>Advertisement<h3>';
$sidebar_after[] = 'print_adsense';

To call custom functions, include files or just print some html code before and after the main content, the PHP code in your website template should be something like this:

if (isset($sidebar_visible) && $sidebar_visible) {

	echo "\t\t\t<!-- Sidebar -->\n";
	echo "\t\t\t<div id=\"sidebar\" class="$css_class">\n\n";
	
	// Print content before the Sidebar
	if (isset($sidebar_before))
		foreach ($sidebar_before as $s) {
			if (function_exists($s)) call_user_func($s); 
			elseif (is_file($s)) include($s);
			else echo $s;
			echo "\n\n";
		}	

	// Print the Sidebar
	if (isset($sidebar)) echo $sidebar."\n\n";
	
	// Print content after the Sidebar
	if (isset($sidebar_after))
		foreach ($sidebar_after as $s) {
			if (function_exists($s)) call_user_func($s); 
			elseif (is_file($s)) include($s);
			else echo $s;
			echo "\n\n";
		}	
	
	echo "\t\t\t</div>\n";
	echo "\t\t\t<!-- /Sidebar -->\n\n";
} 

If you have any questions relative this article or know some other useful web-master hacks write a comment or contact our team directly.

How to be good in web-mastering?

If you are a website developer you are familiar with ready-to-use web templates, programming frameworks, and content management systems (CMS). Such solutions “out of the box” make the web-mastering a convenient and simple process.

But very often there is a task to add custom scripts to a web-site bypassing CMS or other non-standard way. Especially if you do not have full access to the source code of the system. The task becomes very difficult if the website is built using an outdated code or an abandoned framework.

The best principle in software development is the same as for medicine:

Primum non nocere (Do not harm)

Therefore, the best way is to make your own code independent of the environment. Then add small and simple (in one line) injections to the working code base. In the embedded code, check the existence of your own variables, try to call only the standard language functions.

Choose the proper method to change the website context. You should select from simple to complex:

  • printing new html blocks as a text
  • call custom function that generates new content
  • include the script files directly
  • add own framework scripts into every old files

And never do the following:

  • edit old/cms code directly
  • rewrite all code using other programming language
  • re-create website using some modern CMS

Happy webmastering 🙂

Power of Backward Loops

Loops aka cycles (while, for, do until, etc) are common in programming. Actually they are a language level implementation of the iterator pattern.

Those who learned programming in the college/university, remember lots of tasks for sorting an array or traverse a double-linked list in both directions. But in practice, very few people apply the backward loops.

There are a number of tasks where the reverse iteration automatically solves a bunch of problems, for example:

If you need to release all elements of array/collection/list, it is much easier to start from the end and delete the last element each time, rather then go from the beginning, save the length of the container, make the reference for every deleting object, and so on.

Compare this:

var len = someCollection.length();
for (i = 0, i < len, i++) {
    var element = someCollection[i];
    someCollection.delete(i);
    delete element;
}

with that:

var i = someCollection.length();
while (i--) {
    delete someCollection[i];
}

So the backward loop is not only for students, the backward traverse rules in many cases 🙂

Avoid same IDs for HTML elements

Many back-end developers don’t care about clearance of HTML code. They think it is a front-end developers job…

Yes, but no 🙂 Developers should create a bulletproof code on both sides.

Very often, calling the PHP code, that generates some HTML template, for the second time creates two sets of HTML elements with the same IDs. This is wrong!

Here is a workaround to avoid same IDs for HTML elements using a global variable:

<?php
global $some_global_variable;
if (isset($some_global_variable)) $some_global_variable += 1; else $some_global_variable = 0;   

$form_id = '';
if ($some_global_variable > 0) $form_id = $some_global_variable;
?>

This is an example of HTML template for this hack:

<form role="search" method="get" id="searchForm<?php echo $form_id ?>" class="searchForm" action="/search/">
    <input type="text" id="searchText<?php echo $form_id ?>" name="search" value="" />
    <input type="submit" id="searchButton<?php echo $form_id ?>" value="" />
</form>

Try to be a good programmer every-time and everywhere!