How to Dot Net

How to tips and tricks for Microsoft Visual Studio .net

Tuesday, May 15, 2018

Validate South African ID Number

The South African ID Number is a unique number given to every person who is a South African citizen, or who has been granted permanent South African residence. Use this site to find out how the number is made up.

The South African ID Number can be validated using the Luhn algorithm.

I use the following code to validate South African ID Numbers in my applications:

vb.net

Public Shared Function RSA_ID_Number(ByVal id_no As String) As Boolean
        Dim is_valid As Boolean = False

        Try
            If id_no.Length = 13 Then
                Dim intcheck_a As Integer = 0
                Dim strCheck_b As String = ""
                Dim intcheck_b As Integer = 0
                Dim intCheck_c As Integer = 0
                Dim check_calc_result As Integer = 0
                Dim check_digit As Integer = id_no.Substring(12, 1)

                ' Step 1
                For i = 0 To id_no.Length - 1
                    Select Case i
                        Case 0, 2, 4, 6, 8, 10
                            intcheck_a += Convert.ToInt64(id_no.Substring(i, 1))
                        Case 1, 3, 5, 7, 9, 11
                            strCheck_b &= id_no.Substring(i, 1)
                    End Select
                Next

                ' Step 2
                intcheck_b = Convert.ToInt64(strCheck_b) * 2
                strCheck_b = intcheck_b.ToString()

                ' Step 3
                intcheck_b = 0
                For i As Integer = 0 To strCheck_b.Length - 1
                    intcheck_b += Convert.ToInt64(strCheck_b.Substring(i, 1))
                Next

                ' Step 4
                intCheck_c = intcheck_a + intcheck_b

                check_calc_result = 10 - intCheck_c.ToString.Substring(intCheck_c.ToString.Length - 1, 1)

                is_valid = check_calc_result = check_digit
            End If

        Catch ex As Exception : Throw

        End Try

        Return is_valid
    End Function

Tuesday, November 3, 2015

IIf in javascript/jQuery


The conditional operator(c#/java/javascript) or IIf(vb), also called an inline if statement, is very useful.

I have used IIF in my vb and c# exploits very often. I wrote a post about the conditional operator for c# here, and it has proven to be very popular.

To use the conditional operator in javasctipt or jQuery is just as simple as using it in c# or vb.

The syntax is: (condition ? first_expression : second_expression);

A simple example is to set a variable based on the condition of another variable:

      var animal = 'cat';
      var species = (animal == 'cat' ? 'feline' : 'canine');

This snippet checks the variable animal to see if it is set to 'cat'. If the condition is true, species is set to 'feline'. If not, species is set to 'canine'.

Another way to use it would be to set the class of a web page element using the jQuery addClass method:

($("#contactnumber").hasClass("requiredElement") ? "" : $("#contactnumber").addClass("requiredElement"));

This snippet checks the element with an id of contactnumber to see if it has the class requiredElement assigned to it. If it does, then nothing is changed, otherwise the class requiredElement is added to the element.

Please let me know in the comments, if this helped.


Happy coding.

Thursday, May 7, 2015

Microsoft Exchange Web Services – Sending an E-Mail


Before you start find out that comes before this by checking out this post first:
Microsoft Exchange Web Services – First things first


One of the more obvious things that you might want to do with EWS is send an e-mail.

  Dim subject As String = "Your subject"  
  Dim html_Content As String = "<div style=""font-family:Arial;font-size:10pt;color:black"">Insert your html content for your e-mail here</div>"  
  Dim _SendTo As String = "email@address.com"  
   
  Dim replyMessage As New Microsoft.Exchange.WebServices.Data.EmailMessage(_service)  
  replyMessage.Subject = subject  
  replyMessage.Body = html_Content  
  replyMessage.ToRecipients.Add(_SendTo)  
   
  replyMessage.SendAndSaveCopy()  
   

This code snippet will send an e-mail to the address that you specify. Remember to use the code in the post referenced at the top of this post.

More posts about Exchange Web Services will follow.

Please let me know if you found this info helpful.

Tuesday, May 5, 2015

Microsoft Exchange Web Services – First things first



Microsoft Exchange Web Services (EWS) allows you to manage your Microsoft Exchange account using built in web services on the Exchange server.
Some of the things EWS allows you to do:

  1. Read mail in any of the folders that your account has access to
  2. Send e-mails from your account
  3. Manage appointments
  4. Move e-mails from one folder to another
The first thing I can recommend is to download and install the Microsoft Exchange Web Services API.

Version 2.2 of the API can be found here:
https://www.microsoft.com/en-us/download/details.aspx?id=42951

Use the following link to find out where your Exchange Web Services are installed, so that you can use the URL as the _service.Url in the code below:
http://blogs.msdn.com/b/deva/archive/2011/12/02/how-to-get-the-ews-endpoint-url-from-outlook-2007-2010.aspx

Once you have the API installed, and you know what the services URL is, you can start a new Visual Studio project, and add Microsoft.Exchange.WebServices.dll as a reference to the project.

In my installation's case it is located in C:\Program Files\Microsoft\Exchange\Web Services\2.2.


You are now ready to get going:

      Private _service As Microsoft.Exchange.WebServices.Data.ExchangeService = New Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP1)  
      Private _serviceCredentials = New Microsoft.Exchange.WebServices.Data.WebCredentials("exchangeUserId", "exchangePassword", "optionalDomainName")  
   
      Private Sub Initiate_EWS_Service()  
           _service.Credentials = _serviceCredentials  
           _service.Url = New Uri("https://exchangeWebServiceURL")  
      End Sub  
   
      Initiate_EWS_Service()  
   

This little bit of code will connect to your Exchange Server and authenticate your supplied credentials. You can use _service to interact with the exchange server account, and perform the functions I mentioned at the beginning of this post.

More posts about Exchange Web Services will follow.


Please let me know if you found this info helpful.

Tuesday, July 16, 2013

Object doesn't support property or method 'querySelectorAll' - IE9

I have recently been plagued by an error that I found very difficult to fix.

Object doesn't support property or method 'querySelectorAll'

This error only occurs when using IE9!

There are lots of explanations all over the place on how to fix the problem. Our main problem is that we don’t even use the JavaScript querySelectorAll function, but I suspect that one of the 3rd party add-ons (Component One) that we use does.

Many solutions just tell you to add to the top of your page, and that will sort things out for you.

What a joke!!! Unfortunately, it is not that simple!

There is more to it, to make it work.

Visual Studio 2010 adds the following to .aspx and .htm pages when you create them:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

This is what works!

There are other versions of the tag that also seem to have worked in my testing:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

We had ours set to the following, and it caused the error to come up:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

That may have possibly come from a previous version of Visual Studio, and when users weren’t using IE9, everything was fine, but as soon as an IE9 user accessed our problem site, the error occurred.


As always… Let me know if this helped you or not.

Friday, June 14, 2013

Wait for jQuery ajax functions to complete

This is something that kept me busy for a little while. There weren't many explanations that helped me to see how this works, but I managed to get something that worked for me.

I needed to return a json string from a handler and then check that it existed. My problem is that because jQuery is asynchronous, my validation code always fired before the string was returned from the .ajax function call had completed. This mean't that I couldn't check that my order contains the required currency data.

The key is to use $.when...then(function...

$.when will allow the code to complete the function calling the $ajax code, before continuing with the specified function.

This is how I got it working...

var CurrentOrderCurrencyRows_json;

function GetCurrencyRows() {
    var OrderId = 25;
   var ReturnValue = "";

  $.when(ReturnCurrencyRows(OrderId)).then(function () {
    ReturnValue = ValidateCurrencyRowsExist("There are no currency data rows!")

    // Do what you want with ReturnValue
  });

  

}


function ReturnCurrencyRows(OrderId) {
  var BaseURL = "http://localhost/testapp/handlerFolder/";
  var url = BaseURL + "ReturnOrderCurrencyRows_json.ashx?id=" + OrderId;

  if (url != "") {
    return $.ajax({
      type: "GET",
      url: url,
      data: "",
      dataType: "json",
      success: function (data, status) {
        CurrentOrderCurrencyRows_json = data;
      },
      error: function (data, status) {
        alert('Error: ' + status);
      }
    });
  }
}

function ValidateCurrencyRowsExist(ReturnErrorMessage) {
  if (CurrentOrderCurrencyRows_json != undefined) {
    return "";
  }
  else {
    return ReturnErrorMessage;
  }
}

Note: The above code will not work unless you call the $.ajax function specifying "return" 

Good luck, and as always... Feedback is very very welcome.

Friday, April 19, 2013

jQuery ajax().load caches url

In my mind, the jQuery ajax().load functionality is possibly one of the best things about jQuery.

I ran into a problem that drove me nuts for a little while...

I have a div:

<div id="divStatus"></div>

I wanted to load some html into it each time I show a popup that contains it, like this:

  // Page Variables
  var ParsedURL;
  var port;
  var BaseUrl = "";

  $(function () {
    var url = document.URL;
    ParsedURL = parseUri(url);

    port = ParsedURL.port;
    if (port != "") {
      port = ":" + port;
    }

    ShowStatusesDDL();
    ReadAndDisplayCookieData();
  });

  function ShowStatusesDDL() {
    // Build the Base URL
    BaseUrl = ParsedURL.protocol + "://" + ParsedURL.host + port + ParsedURL.directory;
  
    // Add the rest of the text to the url for the BuildStatusDropDownList Handler
    var LoadUrl = BaseUrl + "WebHandlers/BuildStatusDropDownList.ashx?t=" + ParsedURL.queryKey["t"] + "&id=" + ParsedURL.queryKey["id"];

    $('#divStatus').load(LoadUrl);
  } 
The problem with this code, is that every time the .load method runs, the url is the same. The .load method caches the url, and if it isn't different each time the .load method runs, it will return the cached return values.

To fix this you need to make the url unique every time it runs, like this:
  // Page Variables
  var ParsedURL;
  var port;
  var BaseUrl = "";

  $(function () {
    var url = document.URL;
    ParsedURL = parseUri(url);

    port = ParsedURL.port;
    if (port != "") {
      port = ":" + port;
    }

    ShowStatusesDDL();
    ReadAndDisplayCookieData();
  });

  function ShowStatusesDDL() {
    // Build the Base URL
    BaseUrl = ParsedURL.protocol + "://" + ParsedURL.host + port + ParsedURL.directory;

    // Build a Globally Unique Identifier to add to the url to make it unique every time it is loaded -
    // This is because jQuery.load caches the url and won't re-load it each time unless the url is different
    var RandomGuid = guid();

    // Add the rest of the text to the url for the BuildStatusDropDownList Handler
    var LoadUrl = BaseUrl + "WebHandlers/BuildStatusDropDownList.ashx?t=" + ParsedURL.queryKey["t"] + "&id=" + ParsedURL.queryKey["id"] + "&guid=" + RandomGuid;

    $('#divStatus').load(LoadUrl);
  } 

  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
  }
Pretty basic, but if you don't know about the .load method caching, it will confise the hell out of you.