So You Only Want Intercom Chat On Certain Pages In WordPress? Here’s How!

So I had a client want to use Intercom. Great! So I went to Intercom and signed up for an account, then went to our WordPress instance and downloaded the Intercom for WordPress plugin. Everybody wins! Until…I get the requirement after the fact that the client does not want the chat pop up on every page…but only on certain pages. However, the out of the box Intercom for WordPress plugin is only built to be supported for all pages and not some. What to do…what to do…let’s figure it out.

First, login into your WordPress (.org version) as an admin and uninstall the Intercom for WordPress plugin. Next install the Head, Footer and Post Injections Plugin:

Once installed, go to the Head, Footer and Post Injections plugin settings and insert the following script injection into the Desktop and Mobile (Check the Mobile checkbox) BEFORE THE CLOSING TAG (FOOTER). 

<script>
var ref1= window.location.pathname;
var search1 = "/pagepath1/";
var search2 = "/pagepath2/"; 
if (ref1.indexOf(search1) > -1 || ref1.indexOf(search2) > -1)
  window.intercomSettings = {
    app_id: "YourIntercomID"
  };
</script>
<script>(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/nna8fbly';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()</script>

Save the plugin settings. This JavaScript will check on the specified page paths and only execute turning on Intercom for the specific page paths. Hope this helps!

Solved: Issue with SharePoint Rest API Document Upload – Solving the case of the single apostrophe/quote in the URL POST

So I ran across an interesting mystery a while back that I thought I would share the fix for once I had time to document it. I have a client that uses an embeddable SharePoint page within CRM to allow document uploads right from the front entity screens without having to deviate to another screen and for the most part things have been going well. Until…the mystery began.

The problem: In some sporadic cases when uploading documents via POST to the REST API users would encounter an issue with the dynamically generated URLs from SharePoint that contain single apostrophes or quotes in the library name that would be used in the POST URL.

Errors may look like:

{"error":{code":"-1,Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":en-US","value":"The expression\"web/getfolderbyserverrelativeurl('yourfolder/O'Lastname, Firstname - 23424ID')/files/add(overwrite=true,url='filename.pdf')\" is not valid."}}}

The odd part about that? If you browse the library on its own, it’s fine! However, trying to post to the REST API with an improperly escape quote is not. So let’s fix that.

The solution: It’s all in how you build the URL with properly escaped characters.

Snippet in question:

    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer) {

        // Get the file name from the file input control on the page.
        var parts = fileInput[0].value.split('\\');
        var fileName = parts[parts.length - 1];

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
                "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                "/add(overwrite=true, url='{2}')",
                serverUrl, serverRelativeUrlToFolder, fileName);

        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });

Fixed snippet:

    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer) {

        // Get the file name from the file input control on the page.
        var parts = fileInput[0].value.split('\\');
        var fileName = parts[parts.length - 1];

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
                "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                "/add(overwrite=true, url='{2}')",
                serverUrl, serverRelativeUrlToFolder.replace(/\%27/g,"''"), fileName);

        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });

Conclusion? With the replace regex fix in place it will now take every occurance (and not just the first, thanks regex) of a single quote that come as a part of the folder directory and properly escape them when I want to post a file back with the API.

Key change:

serverRelativeUrlToFolder.replace(/\%27/g,"''")

Everybody wins now, espcially the people out there with apostrophes in there names and folder names with titles that still need the quotes in them! Hope this helps.

References:

Check For Internet Explorer (IE) Compatibility Mode

Create a JavaScript file called iecheck.js and paste the following in the snippet:

function trueOrFalse() {
 return true;
}

function IeVersion() {
 // Set defaults
 var value = {
 IsIE: false,
 TrueVersion: 0,
 ActingVersion: 0,
 CompatibilityMode: false
 };

// Try to find the Trident version number
 var trident = navigator.userAgent.match(/Trident\/(\d+)/);
 if (trident) {
 value.IsIE = true;
 //Convert from the Trident version number to the IE version number
 value.TrueVersion = parseInt(trident[1], 10) + 4;
 }

// Try to find the MSIE number
 var msie = navigator.userAgent.match(/MSIE (\d+)/);
 if (msie) {
 value.IsIE = true;
 // Find the IE version number from the user agent string
 value.ActingVersion = parseInt(msie[1]);
 } else {
 // Must be IE 11 in "edge" mode
 value.ActingVersion = value.TrueVersion;
 }

// If we have both a Trident and MSIE version number, see if they're different
 if (value.IsIE &amp;&amp; value.TrueVersion &gt; 0 &amp;&amp; value.ActingVersion &gt; 0) {
 // In compatibility mode if the trident number doesn't match up with the MSIE number
 value.CompatibilityMode = value.TrueVersion != value.ActingVersion;
 }
 return value;
}

Once you have the JavaScript file then open your page where you are going to check for compatibility for and place a reference to the iecheck.js file in the head tag.

<script src="iecheck.js" type="text/javascript"></script>

After that you have multiple options on how to use the script.

For example, if you would like to check for compatibility and redirect then paste the following snippet inside of the body of your html:

<script type="text/javascript">
// 0 = not in compatibility view, 1 = in compatibility view
var ie = IeVersion();
if ((ie.CompatibilityMode == "0") && (ie.IsIE == "1")) {
window.location = "redirecttosomewhere.html"
}
else {
// do nothing, is in compatibility view
}
</script>

Another example would be if you just want to see the results on the page; just place this snippet inside of the body of your html:


<script type="text/javascript">
// <![CDATA[
var ie = IeVersion();
document.write("IsIE: " + ie.IsIE + "</br>");
document.write("TrueVersion: " + ie.TrueVersion + "</br>");
document.write("ActingVersion: " + ie.ActingVersion + "</br>");
document.write("CompatibilityMode: " + ie.CompatibilityMode + "</br>");
// ]]>
</script>

Hope this helps. Questions are always welcome.

JavaScript HTML Redirect To Another URL

There may be cases where you don’t have as free of access to the meta information or web.config to set redirects in place. You can also do this with JavaScript!

Here’s the snippet (place this in between script tags in the body or applicable section in the body that allows HTML):

<script type="text/javascript">
    window.location.replace("http://www.yourexamplesite.com/some-other-page.html");
</script>

Hope that helps.

Use No Captcha reCaptcha In ASP.Net Web Application Form Page With C#, JSON and JavaScript

Users are getting more and more tired of interpreting images with random numbers or letters that take 2-3 tries to get. Google has a new release of the reCaptcha to include a  “No Captcha” feature. You can read about that more here. Here are the steps that I took to include this newer version into a ASP.Net web application.

  • Obtain a google account and sign up for reCaptcha 
  • Create a Visual Studio C# based web forms application and create a page where you will have your reCaptcha to live
  • Download Json via NuGet (instructions are here)
  • Once you have reCaptcha information be sure to insert the following in the head section of your web page:
 
<script src="https://www.google.com/recaptcha/api.js" type="text/javascript"></script> 
  • Then place in your web page where you want the reCaptcha to live. Remember to replace “yoursitekey” with the Google reCaptcha site key:
<div class="g-recaptcha" data-sitekey="yoursitekey"></div>

 

  • Create a class in your web application called ReCaptchaClass (credit for class and credit for proxy) and put the following code into the class. Remember to replace “yoursecretkeygoeshere” with the Google reCaptcha secret key:
using Newtonsoft.Json;
    public class ReCaptchaClass
    {
        public static string Validate(string EncodedResponse)
        {
            var client = new System.Net.WebClient();
            IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy;
            defaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
            client.Proxy = defaultWebProxy;
            string PrivateKey = "yoursecretkeygoeshere";
            var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&amp;response={1}", PrivateKey, EncodedResponse));
            var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(GoogleReply);
            return captchaResponse.Success;
        }
        [JsonProperty("success")]
        public string Success
        {
            get { return m_Success; }
            set { m_Success = value; }
        }

        private string m_Success;
        [JsonProperty("error-codes")]
        public List ErrorCodes
        {
            get { return m_ErrorCodes; }
            set { m_ErrorCodes = value; }
        }
        private List m_ErrorCodes;
    }
  • Once the class is created place the following snippet in the code behind of your page (likely in a button click event of some kind):
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "True" ? true : false);

if (IsCaptchaValid) {
    //Valid Request
}

That’s it! Easy enough, right? I hope it helps. Questions are always welcome.

How To Detect The Edge Browser And Redirect To Another Page In JavaScript

There will likely be cases where you have sites that were built for IE but are not caught up to Edge yet. What do you do in the interim? One idea that I applied on a legacy site was to inform take the Edge user to a specific page. You can always do a multitude of things when dealing with how to address the user (alerts, redirects, updates to labels on pages, etc.). I just want to show an easy way to detect and redirect.

The first thing you need to know is the Edge Browser’s User Agent String:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.9600

You can take advantage of the navigator.userAgent property in JavaScript and do a quick check of it. In this example I check for “Edge” and redirect if it is contained in the string.

Place the following in a script tag inside of the head section of your html:

<script type="text/javascript">
var ver = navigator.userAgent;
if (ver.indexOf('Edge') !== -1)
{
window.location = "https://www.afakewebsite.com/edgemessage.html";
}
else
{
// Not Edge, do nothing
}
</script>

Hope it helps.

Write a JavaScript/HTML Form Submit Post From C# APSX Code Behind

There may be a case where you are taking information from a form and need to post it to a web site somewhere else. One quick method of performing that post is to execute it from the code behind using C# (via context.response) and JavaScript. This is a scaled down example of a case where I was submitting a POST from the code behind of a web part control:

A couple things to note:

  • You can add as many fields as you wish to post, I am only using two
  • You can use string.Format to get C# variables to put directly in the POST
protected string value1;
protected string value2;

value1 = "something";
value2 = "something else";

Context.Response.Write("&lt;form name='Form1' id='Form1' method='post' action='https://www.mywebsitetopostto.com/example'&gt;");
Context.Response.Write("&lt;input type='hidden' name='__VIEWSTATE' id='__VIEWSTATE' value='' /&gt;");
Context.Response.Write(string.Format("&lt;input type='hidden' name='txtValue1' id='txtValue1' runat='server' value='{0}' /&gt;", value1));
Context.Response.Write(string.Format("&lt;input type='hidden' name='txtValue2' id='txtValue2' runat='server' value='{0}' /&gt;", value2));
Context.Response.Write("&lt;/form&gt;");
Context.Response.Write("document.Form1.submit();");
Context.Response.Flush();
Context.Response.End();

Ideally you would use this in a case where you are posting content and the page you are posting to will process and serve something after the form that receives your post processes what you sent. Please do not use this snippet and blame me for a blank page 🙂