Change highlight color Autocomplete Material UI ReactJS

Create the below styles in your ReactJS component:

const styles = (theme) => ({
  ////....
  option: {
    // Hover
 with light-grey
    '&[data-focus="true"]': {
      backgroundColor: '#F8F8F8',
      borderColor: 'transparent',
    },
    // Selected
 has dark-grey
    '&[aria-selected="true"]': {
      backgroundColor: theme.palette.grey.A200,
      borderColor: 'transparent',
    },
  },
});

You can choose the colors based on your preference on selected and for mouse-over for backgroundColor property.

Add the following property in your AutoComplete component

classes={{
	  option: classes.option
	}}

as shown below:

<Autocomplete
	id="combo-box-1"
	options={myvalues}
	getOptionLabel={(option) => option.value}
	size="small"
	className={classes.formControlAutopopulate}
	classes={{
	  option: classes.option
	}}
	value={myvalues.find((x) => x.id === this.state.ID)}
	disabled={this.props.isLocked}
	onChange={this.handleSelected}
	renderInput={(params) => (
	  <TextField
		{...params}
		variant="outlined"
		placeholder="Please Select Value"
		fullWidth
	  />
	)}
/>

Borders not shown in Firefox with border-collapse on material table

I came across this issue that all Material Table used in the ReactJS Application are not showing bottom border in the th row in the Firefox browser. This issue is not reproducible in Chrome.

So, I found css hack where you can simply change the position attribute specifically for the Firefox browser in the default MuiTableCell-head class. This class is applied at the cell level by Material-table.

@-moz-document url-prefix() {
  .MuiTableCell-head {
    position: static !important;
  }
}

The above code will remove the default sticky value for position which causes the issue with border-collapse in the .MuiTable-root class. You can also remove the border-collapse in a similar fashion but do test that it’s not breaking anything else.

The component which has the Material-table code should import the above css to take effect. This hack might also work generally for html table if you’re facing a similar issue without Material-table.

Find duplicates in Excel

One of the most common scenarios of data cleansing is finding duplicates in Excel. Below are the steps:

Select the data range in Excel in which you want to find the duplicate values.

Under Home Tab, select Conditional Formatting->Duplicate Values:

Click OK and observe the highlighted cells with duplicate values.

You can now filter the data based on color to quickly check the duplicate values. Short-cut to filter is select the header of the column or columns and then Alt+D+F+F on keyboard.

Update Child Components from Parent ReactJS

One common challenge in ReactJS is updating Child Components from Parent Component in a form. I faced this scenario recently where after a series of GET calls where the order is decided by the browser threads, data is not always available in the same order.

If you need to set some permissions based on an API GET call and then enable/disable a child component, you can use the following ReactJS lifecycle method:

//Parent Component
shouldComponentUpdate(nextProps, nextState) {
    if (nextState.formReady) {
      return true;
    } else {
      return false;
    }
  }

Set the flag formReady in the series of successive GET calls to true, where you’re sure will be the last call on your Parent form.

//Parent Component GET call inside axios success.
this.setState(
{
  formReady: true,
},() => console.log(this.state.formReady);
);

The shouldComponentUpdate lifecycle method will check for the boolean value and will re-render or refresh the entire form including Child Components.

However, do refer to the documentation before using this method to decide if this suits your needs.

Upload word document to .Net core WebAPI

We’ll be working with a .docm template in Word 2016 which contains a textbox. This control is given a name using the Content Control Properties.

This is available under Developer Menu in MS Word, then click on Properties.

Save this template as .docm

Create .Net Core WebAPI under .net core version 3.1 for this example. The sample code is as below. The library System.IO is used to access the value in the variable.

using System;
using System.IO;
using System.IO.Packaging;
using System.Xml;
using System.Xml.XPath;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace SampleApplicationUpload.Controllers
{
    public class UploadController : ControllerBase
    {
        [HttpPost]
        [Route("upload")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public IActionResult Upload()
        {
            string filename = string.Empty;
            string extension = string.Empty;
            string result = string.Empty;
            bool uploaded = false;
            string ModifiedBy = string.Empty;
            var request = HttpContext.Request;

            if (request.Form.Files.Count > 0)
            {
                filename = request.Form.Files[0].FileName;
                extension = filename.Substring(filename.LastIndexOf(".")).ToLower();
                if (!string.IsNullOrEmpty(extension) && extension.Equals(".docm"))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        request.Form.Files[0].CopyTo(memoryStream);
                        if (memoryStream.Length < 2097152)
                        {
                            result = UploadWorStream(memoryStream, extension, out ModifiedBy, out uploaded);
                        }
                        else
                        {
                            return BadRequest("File size too large");
                        }
                    }
                }
                else
                {
                    return BadRequest("File format not recognised. Upload .docm file only");
                }
            }           
            return Ok(result);
        }
        private string UploadWorStream(MemoryStream ms, string ext, out string ModifiedBy, out bool uploaded)
        {
            string contenttype = string.Empty;
            bool erroroccurs = false;
            ModifiedBy = string.Empty;
            var xmlDoc = new XmlDocument();
            uploaded = false;
            switch (ext)
            {
                case ".docm":
                    contenttype = "application/vnd.ms-word";
                    break;
                default:
                    erroroccurs = true;
                    break;
            }

            if (!erroroccurs)
            {
                if (contenttype != string.Empty)
                {
                    Stream fs = ms;
                    var br = new BinaryReader(fs);
                    string xmlDocRelType = "http://schemas.openxmlformats.org/officeDocument/" +
                                           "2006/relationships/customXml";
                    string officeDocRelType = "http://schemas.openxmlformats.org/" +
                                              "officeDocument/2006/relationships/officeDocument";
                    PackagePart xmlPart = default(PackagePart);
                    PackagePart documentPart = default(PackagePart);
                    Uri documentUri = default(Uri);
                    Uri xmlUri = default(Uri);
                    using (Package officePackage = Package.Open(fs, FileMode.Open, FileAccess.Read))
                    {
                        foreach (var relationship1 in officePackage.GetRelationshipsByType(officeDocRelType))
                        {
                            documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative),
                                                                       relationship1.TargetUri);
                            documentPart = officePackage.GetPart(documentUri);
                            break;
                        }

                        if (documentPart != null)
                            foreach (var relationship2 in documentPart.GetRelationshipsByType(xmlDocRelType))
                            {
                                xmlUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative),
                                                                      relationship2.TargetUri);
                            }
                        xmlPart = officePackage.GetPart(xmlUri);
                        Stream inputStream = xmlPart.GetStream(FileMode.Open, FileAccess.Read);
                        var ts = new StreamReader(inputStream);
                        xmlDoc.Load(ts);
                        ts.Close();
                        ts.Dispose();
                        officePackage.Close();
                    }

                    XPathNavigator xpnGet2 = xmlDoc.CreateNavigator();
                   // string txtSample = xpnGet2.Evaluate("string(//ROOT[1]/SampleDoc[1]/@txtSample)").ToString();
                    string txtSample = Convert.ToString(xpnGet2.Evaluate("string(//ROOT/SampleDoc/@txtSample)"));
                    if (txtSample.Length > 0)
                    {
                        return txtSample;
                    }
                    else {
                        return "Unable to read document";
                    }
                }
                else
                {
                    uploaded = false;
                    return "Error";
                }
            }
            else
            {
                uploaded = false;
                return "Error";
            }
        }
    }
}

Finally try to access the WebAPI using a Postman request and check the value while debugging the end-point.

curl --location --request POST 'https://localhost:<port>/upload' \
--form 'attachment
=@/C:/Users/username/Desktop/TestDocument.docm'

Preparing React Native App for Android Release on Mac

When your React Native Application is ready for release to the Android Platform, you need to perform the following steps to create the .aab file or Android App Bundle which contains your compiled code and resources and you can upload to the Play Store. The APK generation and signing is done by Google Play.

I’m using React Native 0.62.2 for this post in VS Code.

Open Terminal and check the Java Home Path:

/usr/libexec/java_home

cd to the path displayed as shown in the image.

Run the keytool command as shown using sudo to generate the keystore and alias as shown below:

sudo keytool -genkey -v -keystore some-helper-key.keystore -alias some-helper-key-alias -keyalg RSA -keysize 2048 -validity 10000

As shown in the screen-shot, answer the questions that pop and your keystore will be generated under the Java Home folder.

Copy that keystore file and paste it in your Android folder under app in your React Native Project.

Modify the android/gradle.properties file and add:

MYAPP_UPLOAD_STORE_FILE=some-helper-key.keystore
MYAPP_UPLOAD_KEY_ALIAS=some-helper-key-alias
MYAPP_UPLOAD_STORE_PASSWORD=***
MYAPP_UPLOAD_KEY_PASSWORD=***

You might not want to store the passwords directly in the above configuration and store them in the keychain Access App, then the last 2 password configs are not required.

Add the Release signingconfig section to the android/app/build.gradle file:

signingConfigs {
        debug {
            .....
        }
        release {
            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
                storeFile file(MYAPP_UPLOAD_STORE_FILE)
                storePassword MYAPP_UPLOAD_STORE_PASSWORD
                keyAlias MYAPP_UPLOAD_KEY_ALIAS
                keyPassword MYAPP_UPLOAD_KEY_PASSWORD
            }
        }
    }

cd to the Android folder and run:

./gradlew bundleRelease

The .aab file is generated as: android/app/build/outputs/bundle/release/app-release.aab

Now this is ready to be uploaded to the Play Store.

Issues Faced:

Resource and asset merger: Duplicate resources

The above error occurred for files under drawable folder, app.json, node_modules_reactnativevectoricons_glyphmaps_materialcommunityicons.json etc.

Go to android/app/src/main/res and delete all the directories starting with drawables and the above mentioned .json files. Do not delete the raw folder if it contains any resources.

If you want to directly test the Release version on your device, run the following command under Root folder of the Project:

react-native run-android --variant=release

You can install bundle tool on Mac:

brew install bundletool

To extract the APK directly from the .aab file, run the following commands:

bundletool build-apks --bundle=/MyApp/my_app.aab --output=/MyApp/my_app.apks

If you want to test it on a device, then also include the App signing information:

bundletool build-apks --bundle=/MyApp/apprelease.aab --output=/MyApp/my_app.apks
--ks=/MyApp/keystore.jks
--ks-pass=pass:***
--ks-key-alias=MyKeyAlias
--key-pass=pass:***

Please note that the .aab file should not contain hyphen else it’ll give file not found error.

If you want to generate a single Universal apks file, run the below command. Copy the .aab and .keystore files to the folder from where you’ll run bundle tool using terminal:

bundletool build-apks --bundle=MyApp.aab --output=MyApp.apks --mode=universal --ks=my-key.keystore --ks-pass=pass:**** --ks-key-alias=my-key-alias --key-pass=pass:****

Change the extension .apks to .zip and extract the universal.apk file. You can rename this file and transfer it to your Android device for installation.

You can also install the .apks directly to your connected device using bundle tool:

bundletool install-apks --apks=MyApp.apks

Create New Team Project TFS 2015

Most of the Admin features are available for TFS 2015 through the Browser Console. These can be managed using the URL:

http://servername:8080/tfs/_admin

If you need to create a new Team Project under an existing Collection, you need to be part of the Project Collection Administrators Group for that collection in TFS 2015.

The URL to access that is :

http://servername:8080/tfs/collectionname/_admin/_security/?_a=members

You can add Windows user or group or TFS group.

To create a New Team Project, go to the following URL:

http://servername:8080/tfs/collectionname/_admin

and click on New Team Project and fill out the required details and click on Create Project.

This will reflect in the Source Control Explorer in Visual Studio where you can then start creating branches.

Multiple Commands produce error React Native with XCode11

I had earlier installed react-native-vector-icons in my Project and used the below command to link it:

react-native link

The “multiple commands produce” error seems is caused by the new autolinking feature in React Native 0.60 or above – the line use_native_modules! in ios/Podfile means when you do pod install, any pods found in node_modules are automatically linked.

So when you do pod install, links to all font files are added to [CP] Copy Pods Resources. If you previously installed react-native-vector-icons manually by adding the font files to Copy Bundle Resources, you then get a fatal build error similar to this:

Build system information
error: Multiple commands produce '/Users/xxx/Library/Developer/Xcode/DerivedData/Project-dcurwlhxaqikupbgxeiimmauwnpw/Build/Products/Debug-iphonesimulator/MyApp.app/SimpleLineIcons.ttf':

To fix the problem, remove the font files from Copy Bundle Resources, so that they are only in [CP] Copy Pods Resources.

In your Xcode, Select your Project and go to Build Phases and remove the fonts shown below from Copy Bundle Resources:

Google AdMob with react-native-firebase

This post is to document the steps on how I integrated Google AdMob in my React Native Application and how the issues were resolved. My React Native version is 0.62.2.

I’m using react-native-firebase to integrate AdMob for displaying Advertisements. The steps to install react-native-firebase may be different for lower versions of react-native where manual install might be preferred for both iOS and Android builds.

Install the following packages:

npm install @react-native-firebase/app
nvm install @react-native-firebase/admob

Within the root of your React Native Project, add firebase.json file:

{
  "react-native": {
    "admob_android_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx",
    "admob_ios_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx"
  }
}

Before you build the App, you need to add the valid App Ids for both Android and iOS devices. The App Ids can be found in your Google AdMob account while registering the App for iOS/Android. You can create an account here.

Build the Android version with:

react-native run-android

For the iOS version, you need to run “pod install” first inside the iOS folder to install native modules: RNFBAdMob, RNFBApp, and RNVectorIcons and then run:

react-native run-ios

Even after adding the App Ids, my build was giving error for Android build as Execution failed for task ':app:mergeDexDebug' error.

To resolve this, I had to make changes to my build.gradle file under App Sub Folder under the Android folder.

defaultConfig {
        ....
        multiDexEnabled true
    }

dependencies {
    ...
    implementation 'com.android.support:multidex:1.0.3'
}

If your App is targeting children, make sure to set these configuration using setRequestConfiguration:

import admob, { MaxAdContentRating } from '@react-native-firebase/admob';

admob()
  .setRequestConfiguration({
    // Update all future requests suitable for parental guidance
    maxAdContentRating: MaxAdContentRating.PG,

    // Indicates that you want your content treated as child-directed for purposes of COPPA.
    tagForChildDirectedTreatment: true,

    // Indicates that you want the ad request to be handled in a
    // manner suitable for users under the age of consent.
    tagForUnderAgeOfConsent: true,
  })
  .then(() => {
    // Request config successfully set!
  });

There are different types of Ad Units, I’m using Banner Ads for my case. Also, note that you need to create an Ad Unit in Google AdMob account for the specific type of Ad e.g. Banner Ad and that Ad Unit Id is required to be used in your component. You should use the Test Id in your dev environment.

Below is the example Ad Component:

import React from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import { Colors } from 'react-native/Libraries/NewAppScreen';
import { BannerAd, BannerAdSize, TestIds } from '@react-native-firebase/admob';


const AdComp = (props) => {
    const adUnitId = __DEV__ ? TestIds.BANNER : Platform.OS === 'ios' ? 'ca-app-pub-xxxx/xxxx' : 'ca-app-pub-xxxx/xxxx';

    return(
        <View style={{height: '10%', paddingLeft: 20}}>
            <BannerAd 
            unitId={adUnitId}
            size={BannerAdSize.LARGE_BANNER}
            requestOptions={{
              requestNonPersonalizedAdsOnly: true,
            }} />
        </View>
    );
};

export default AdComp;

You May also face metro server related issues like 500 error for which you might need to restart the metro server which made it work.

If you face the error as:

Unable to load script from assets ‘index.android.bundle’

Follow the below steps:

  1. Go to your project directory and check if this folder exists android/app/src/main/assets

If it exists then delete two files viz index.android.bundle and index.android.bundle.meta

ii) If the folder assets doesn’t exist then create the assets directory there.

2. From your root project directory do

cd android
./gradlew clean

3. Finally, navigate back to the root directory and check

If there is only one file i.e. index.js then run following single command

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

If there are two files i.e index.android.js and index.ios.js then run this as a single command

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

How to give Use permissions for Build queues TFS 2015

If you have access to a Project Collection in TFS 2015 but still not able to queue builds, then you are required to be added to the Project Collection Build Administrators group.

The error message would be as below:

500: Access Denied: <username> needs Use permissions for queue <queuename> to perform this action.


To give access, when you’re in the Source Control Explorer in Visual Studio and connected to the required collection, click on the Team -> Team Project Collection settings -> Group Membership.

Under the Security Tab, add the User or group under the Project Collection Build Administrators group as shown below: