Technical Insights: Azure, .NET, Dynamics 365 & EV Charging Architecture

Category: Javascript

Javascript code

ASP.NET Calendar selected day on click method

I’ve a case where I have an ASP.NET calendar that has a page load method that automatically select a date when it’s loaded. I also have an event defined for Selected_Changed which will be triggered only when the user select any other date other than pre-selected date on the load

Private Sub ctlCalendar_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ctlCalendar.SelectionChanged
        If (Not String.IsNullOrEmpty(CalendarPreviousPage)) Then
            BaseCalendar.SelectedDate = ctlCalendar.SelectedDate
            Response.Redirect(CalendarPreviousPage)
        End If
    End Sub

But how do I wire up an event or when the selecteddate being clicked?You can use DayRender event and attach it to a javascript in this case I want to go back to previous page. BaseCalendar.Selected date can be any date where you want to set up/wire up the logic

 Private Sub ctlCalendar_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles ctlCalendar.DayRender
        Dim d As CalendarDay
        Dim c As TableCell
        d = e.Day
        c = e.Cell

        If (BaseCalendar.SelectedDate.Value = d.Date) Then
            c.Attributes.Add("OnClick", "history.go(-1)")
        End If

    End Sub

Numeric textbox with javascript and cross browser compatible

I need to make a text box that does not allow the user to type any numeric key at all

        


// function to only allow numeric key presses in a textbox
// this doesn't stop pasting of non numeric values
function fnNumeric_only(e) {
    // deal with unicode character sets
    var unicode = e.charCode ? e.charCode : e.keyCode;

    // if the key is backspace, tab, or numeric
    if (unicode == 8 || unicode == 9 || (unicode >= 48 && unicode <= 57) || (unicode == 46 || unicode == 44)) {
        // we allow the key press
        return true;
    }
    else {
        // otherwise we don't
        return false;
    }
}

At the sametime I also need to make the counter/tally changing by the time you start typing or deleting a character from the text box. Let’s make a scenario this way e.g 3.25 is the text in your textbox and basically what we want is when the user pressing backspace and stop in “.” character, you want your function to assume it as “3” instead of “0”, you can use this function


function parseLocalNum(num) {
    return +(num.replace(",", "."));
}

I’ve also added these two function for getting and setting value of an input (e.g textbox and label) which is cross browser compatible

function getControlValue(controlName) {
    var controlValue = "";
    var hasInnerText = (document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;

    if (hasInnerText) {
        controlValue = document.getElementById(controlName).innerText;
    } else {
        controlValue = document.getElementById(controlName).textContent;
    }

    return controlValue;
}

function setControlValue(controlName, value) {
    var controlValue = "";
    var hasInnerText = (document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;

    if (hasInnerText) {
        document.getElementById(controlName).innerText = value;
    } else {
    document.getElementById(controlName).textContent = value;
    }

    return controlValue;
}

How to use getControlValue or setControlValue

    setControlValue("ctl00_ContentPlaceHolder1_lblClaimedHours", totalClaimed.toFixed(1).toLocaleString())

an activex control on this page might be unsafe to interact with other parts of the page. do you want to allow this interaction?

I keep getting this message “an activex control on this page might be unsafe to interact with other parts of the page. do you want to allow this interaction” when I try to access a page that use Javascript to access ActiveX Code. I’ve spent quite sometime to get rid of this error message and I found out that

  1. The code need implement IObjectSafety Interface
  2. You need to digitally sign the code with valid certificate

Step 1 : Detail on how to implement IObjectSafety
-Create an interface file called as IObjectSafety.vb/IObjectSafety.cs

CSharp (IObjectSafety.cs) :

[ComImport()]
[Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IObjectSafety {
   [PreserveSig()]
   int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions);

   [PreserveSig()]
   int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions);
}
Imports System.Runtime.InteropServices

 _
 _
 _
Interface IObjectSafety
     _
    Function GetInterfaceSafetyOptions(ByRef riid As Guid, ByRef pdwSupportedOptions As Integer, ByRef pdwEnabledOptions As Integer) As Integer

     _
    Function SetInterfaceSafetyOptions(ByRef riid As Guid, ByVal dwOptionSetMask As Integer, ByVal dwEnabledOptions As Integer) As Integer
End Interface

in your ActiveX code you need to implement IObjectSafety

CSharp:


VB.NET:

 _
 _
 _
 _
Public NotInheritable Class ClientUtility
    Implements IObjectSafety


#Region "IObjectSafety Constants"

    Private Const INTERFACESAFE_FOR_UNTRUSTED_CALLER As Integer = &H1
    Private Const INTERFACESAFE_FOR_UNTRUSTED_DATA As Integer = &H2
    Private Const S_OK As Integer = 0

#End Region

#Region "IObjectSafety Methods"

    Public Function GetInterfaceSafetyOptions(ByRef riid As System.Guid, ByRef pdwSupportedOptions As Integer, ByRef pdwEnabledOptions As Integer) As Integer Implements IObjectSafety.GetInterfaceSafetyOptions
        pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER Or INTERFACESAFE_FOR_UNTRUSTED_DATA
        pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER Or INTERFACESAFE_FOR_UNTRUSTED_DATA
        Return S_OK
    End Function

    Public Function SetInterfaceSafetyOptions(ByRef riid As System.Guid, ByVal dwOptionSetMask As Integer, ByVal dwEnabledOptions As Integer) As Integer Implements IObjectSafety.SetInterfaceSafetyOptions
        Return S_OK
    End Function

#End Region

CSharp:

[ProgId("Fransiscus.Authentication.ClientUtility")]
[ClassInterface(ClassInterfaceType.AutoDual), ComSourceInterfaces("ControlEvents")]
[Guid("0577147B-6941-4f15-9EFB-2551FEB3D6CC")]
[ComVisible(true)]
public sealed class ClientUtility : IObjectSafety
{


    #region "IObjectSafety Constants"

    private const int INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x1;
    private const int INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x2;
    private const int S_OK = 0;

    #endregion

    #region "IObjectSafety Methods"

    public int GetInterfaceSafetyOptions(ref System.Guid riid, ref int pdwSupportedOptions, ref int pdwEnabledOptions)
    {
        pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
        pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
        return S_OK;
    }

    public int SetInterfaceSafetyOptions(ref System.Guid riid, int dwOptionSetMask, int dwEnabledOptions)
    {
        return S_OK;
    }
#endregion

}

Step 2:
You need to obtain certificate and sign it, You also need Windows Server 2008 SDK to sign your code using SignTool.exe (type Signtool SignWizard in command prompt to follow the wizard and sign your DLL)
For more detail please open verisign website (http://www.verisign.com/support/code-signing-support/code-signing/identity-authentication.html) or click here

key event handler that compatible with all browsers using javascript

This might be useful for web developer which wants to have one key event handler that compatible with all browsers.


document.onkeyup = KeyCheck;

function KeyCheck(e)
{
  //this is used for cross browser
  var KeyID = (window.event) ? event.keyCode : e.keyCode;

  switch(KeyID)
   {

   case 13:
    checkPostCodeSelection();
    break;
      }
}

AJAX Update Panel Timeout Issue

I have an asp.net page where the page will query the report from the database. To query the report itself might cause timeout exception on the page itself before the report result is being returned from database.

You need to do it in two steps, first you need to override the script timeout only for the pageitself. put this code in your code behind

    Dim pageTimeOut As Integer
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        pageTimeOut = Server.ScriptTimeout

        'this is in seconds
        Server.ScriptTimeout = 2500
End Sub

Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload

Server.ScriptTimeout = pageTimeOut

End Sub

The next step is required only if you use AJAX Update panel. Put this script on the aspx page


   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
        function (sender, args)
        {
             if (args.get_error() && args.get_error().name == 'Sys.WebForms.PageRequestManagerTimeoutException')
            {
                  // remember to set errorHandled = true to keep from getting a popup from the AJAX library itself
                 args.set_errorHandled(true);
             }
        });

Set Default value with clear text for input type=”password”

Normally we have two text boxes which is user name and password. On the first load of the page we want to set the default value of user name text box becoming ‘username’ and set the default value of password text box becoming ‘password’ not ‘*******’.

Well what most of us think that we can use javascript to change the type of the input box?well I’ve got this trick to have two textboxes in the same location and swap it with “OnFocus” event

  
            

    

Set the default value for username text box via code behind

      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            txtUserName.Attributes.Add("onfocus", "JavaScript:if(this.value=='username'){this.value=''};")
            txtUserName.Attributes.Add("onblur", "JavaScript:if(this.value==''){this.value='username'};")
            txtUserName.Attributes.Add("value", "username")

            txtPassword.Attributes.Add("onkeydown", _
                                            "javascript:if((event.which && event.which == 13) || " _
                                            + "(event.keyCode && event.keyCode == 13))" _
                                            + " {document.getElementById('" + btnLogin.ClientID + "').click(); " _
                                            + " return false; } else return true;")
        End Sub

XML http object cross browser

I believe this will be useful for everyone who wants to implement AJAX manually and make it compatible cross browser.



           // cross-browser method to retrieve an XMLHttp object for asynchronous requests & responses
            function GetHTTPRequest()
            {
                var http_request = false;

                if (window.XMLHttpRequest)
                {
                    // Mozilla, Safari,...
                    http_request = new XMLHttpRequest();

                    if (http_request.overrideMimeType)
                    {
                        http_request.overrideMimeType("text/xml");
                    }
                }
                else if (window.ActiveXObject)
                {
                    // IE
                    try
                    {
                        http_request = new ActiveXObject("Msxml2.XMLHTTP");
                    }
                    catch (e)
                    {
                        try
                        {
                            http_request = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        catch (e) {}
                    }
                }

                return http_request;
            }


Querystring in Javascript

This is a function to capture querystring in javascript. I used this javascript to control my menu dynamically.


function getQueryString(strParamName){
var strReturn = "";
var strHref = window.location.href;
if ( strHref.indexOf("?") > -1 ){
var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
var aQueryString = strQueryString.split("&");
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
var aParam = aQueryString[iParam].split("=");
strReturn = aParam[1];
break;
}
}
}
return unescape(strReturn);
}

Register Javascript to hide Div

Sometimes people add javascript into the aspx page instead of using code behind but there is a case when we need to add javascript in the runtime using code behind. This is the example where javascript is used to provide switching of visibility based on the table visibility status. I used this technique to hide another user control when user click expand button. Client ID is required to know the real ID of the user control after rendering. In here we also add onclick event to the image tag.

if (!this.Page.IsStartupScriptRegistered("tableScript"))
{
string script = @"function checkVisibility() "
+ @"{"
+ @"    var element = document.getElementById('" + this.OuterTableDetailSearch.ClientID + @"');"
+ @"    var elementBtn = document.getElementById('" + this.btnExp.ClientID + @"');"
+ @"    if (element.style['visibility'] == 'hidden')"
+ @"{"
+ @"element.style['visibility'] = 'visible';"
+ @"elementBtn.src = '/Images/button_expand.gif';"
+ @"}"
+ @"else"
+ @"{"
+ @"element.style['visibility'] = 'hidden';"
+ @"elementBtn.src = '/Images/image_casestudy_search.gif';"
+ @"}"
+ @"}";

this.Page.RegisterStartupScript("tableScript", script);
}

btnExp.Attributes.Add("OnClick",
               "javascript:checkVisibility()");

Page 2 of 2

Powered by WordPress & Theme by Anders Norén