HTML, JavaScript, Troubleshooting, Web

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 && value.TrueVersion > 0 && value.ActingVersion > 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.

.Net, C#, HTML, Office, Programming, VB, Web

Exporting asp:GridView Results To A Microsoft Excel Spreadsheet in VB/C#

I have received this requirement on more than one occasion so I thought it would benefit others if I posted these snippets. So here we go, let’s export a gridview as an excel file.

For starters let’s add a couple controls to the front-end aspx page:

 
<asp:Button ID="btnExport" runat="server" Text="Export Results To Excel" /> &amp;nbsp;&amp;nbsp;<br /><br />

<asp:GridView ID="grdSearch" runat="server" CellPadding="3" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">
 <FooterStyle BackColor="White" ForeColor="#000066" />
 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
 <RowStyle ForeColor="#000066" />
 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
 <SortedAscendingCellStyle BackColor="#F1F1F1" />
 <SortedAscendingHeaderStyle BackColor="#007DBB" />
 <SortedDescendingCellStyle BackColor="#CAC9C9" />
 <SortedDescendingHeaderStyle BackColor="#00547E" />
 </asp:GridView>

I’m going to assume you know how to wire in your gridview to return results.

With that assumption in place here is the click event that performs the export (in VB):

You will need: Imports System.IO

Protected Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
        Try
            Response.Clear()
            Response.Buffer = True
            Response.ClearContent()
            Response.ClearHeaders()
            Response.Charset = ""
            Dim FileName As String = "filename" + DateTime.Now + ".xls"
            Dim strwritter As New StringWriter()
            Dim htmltextwrtter As New HtmlTextWriter(strwritter)
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.ContentType = "application/vnd.ms-excel"
            Response.AddHeader("Content-Disposition", Convert.ToString("attachment;filename=") &amp; FileName)
            grdSearch.GridLines = GridLines.Both
            grdSearch.HeaderStyle.Font.Bold = True
            grdSearch.RenderControl(htmltextwrtter)
            Response.Write(strwritter.ToString())
            Response.[End]()
        Catch ex As Exception
            ' Do something important here if you expect strange results
        End Try
    End Sub

Now in C#:

You will need: using System.IO;

try {
	Response.Clear();
	Response.Buffer = true;
	Response.ClearContent();
	Response.ClearHeaders();
	Response.Charset = "";
	string FileName = "filename" + DateTime.Now + ".xls";
	StringWriter strwritter = new StringWriter();
	HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
	Response.Cache.SetCacheability(HttpCacheability.NoCache);
	Response.ContentType = "application/vnd.ms-excel";
	Response.AddHeader("Content-Disposition", Convert.ToString("attachment;filename=") + FileName);
	grdSearch.GridLines = GridLines.Both;
	grdSearch.HeaderStyle.Font.Bold = true;
	grdSearch.RenderControl(htmltextwrtter);
	Response.Write(strwritter.ToString());
	Response.End();
} catch (Exception ex) {
	// Do something important here if you expect strange results
}

I realize you may not need some of the formatting that I used in this example so remove the Gridview related property assignments in the export snippet. Also, depending on how you format your gridview on the aspx page will dictate some of the formatting you have on the spreadsheet. Hope this helps, questions are welcome.

HTML, JavaScript, Web

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.

C#, HTML, JavaScript, JSON, Programming, Web

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.