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.

Adding Categories and Tags into WordPress Pages

Wordpress CMS is a very popular one, but some features and settings are strange.

The most common question people creating content for websites based on this CMS ask is the following:

Why WordPress Posts have Category and Tag settings but WordPress Pages have neither Categories nor Tags?

Here is a quick fix:

// Allow Categories and Tags in GUI of Page Editor 
function add_taxonomies_to_pages() {
	register_taxonomy_for_object_type('category', 'page');
	register_taxonomy_for_object_type('post_tag', 'page');
}
add_action('init', 'add_taxonomies_to_pages');

// Add Pages into Categories and Tags Archives 
function category_and_tag_archives($query) {
	// If you have custom post types add them into this array
	$my_post_array = array('post', 'page'); 

	if ($query->get('category_name') || $query->get('cat'))
		$query->set('post_type', $my_post_array);

	if ($query->get('tag'))
		$query->set('post_type', $my_post_array);
}
if (!is_admin()) {
	add_action('pre_get_posts', 'category_and_tag_archives');
}

You can add this code directly into your WordPress theme (function.php or header.php file).

But a safer way is to use one of plugins allowing to execute PHP code (Code Snippets, PHP Snippets, and so on). In this case WordPress Pages will still have Categories and Tags even if somebody changes (or updates) the theme of your site 🙂

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 🙂

Backup of Firewall settings is Important

If you use a web server (no matter with Linux, Unix or Windows) you should keep it safe. The firewall is the first place where you need to setup the system security.

It is necessary to restrict access to the server by specific protocols and ports. More precisely, on the server firewalls you need to close all ports and open only the most necessary ones 🙂

Linux kernel firewall works with iptables space. You can manually make entries in the iptables configs (different files in /etc/ or /etc/sysconfig/ depending on the Linux version). If you use some visual management panel (Webmin, WHM, CPanel, Plesk, etc.) tuning the Linux firewall become a pleasure.

But independently of managing methods, do not forget to make a regular copies of the firewall settings! Accidental clicking of some button in control panel can suspend all the rules and make your server vulnerable. Deleting or modification of the configuration file by some hacking scripts can do the same.

In general, for servers on the Linux system, the regular backup of the iptables config files is a must do task for webmaster. Backups for security settings are usually scheduled on Unix and Windows servers too.

Backup firewall settings regularly and keep your web-servers secure!