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.

Tuesday, January 8, 2013

How to learn to write software

Learning how to write software is one of those things that you have to do in such a way that it suits you.

Some people enjoy an environment in which there is a structured approach, and they have someone who has some form of curriculum that is followed, teach them. They are given the history of software development, the theory behind software development and some syntax to work with. They are told how that syntax fits together with other syntax and the reasoning behind why it is like that. Then they are given tasks to do to demonstrate their understanding.

Others like to learn how to write software on their own. That’s how I did it, and I would like to think that I’m not bad at what I do.

I’m not going to say that one method of learning how to write software is better than any other method, simply because I only really know about the method I used. I don’t have any fancy degrees or anything like that. What I do have is the knowledge that I have been employed for a long time by many different companies to write software that did what they needed and wanted. I’m definitely not the world’s best programmer, but I’m also not the worst.

I learned to write software by having a need to do something on a computer, and at the time, not knowing how to make it happen. So, the first step for me was to decide to do it myself.

I could have called a programmer in to do the work, but that would have cost money I didn’t have. Besides, I love computers, so development was kind of a natural way to go for me to go.

I didn’t start out programming totally green. I played with a Sinclair ZX Spectrum computer as a kid. It was the latest and greatest computer that I could get my hands on at the time. It plugged into a TV, didn’t have any way to store the programs that were typed in, unless you plugged a tape recorder into it to store it on cassette tape. It did have 16k of ram and could display 16 colours on the TV it was plugged into.

I started out buying books with the code that once typed into the computer and executed, would provide me with hours of gaming pleasure, but it used to take hours to enter the code into the computer before I could play the game. I saved the games onto cassette tape, and if I was lucky enough to have the saved game work the next time I tried to load it, I was able to play them again and again.

That’s was my first introduction to coding. The language was Basic. I didn’t really learn to programme through this experience, but I did get to understand how the code fitted together and that was a decent base to start on.

Many years later, I had the opportunity to work in a software development company as their technical manager, and since I had a basic understanding of how software was put together, I began to learn. We were using VB3 and VB4 at the time, and those were light years ahead of the old Spectrum Basic I first encountered, but I seemed to pick it up pretty easily.

I never actually wrote much code for that company, but I did do some. I still didn’t really know what I was doing as a developer until I left that company and began looking after my own client’s hardware and software needs. I had a client that needed a very custom application written. I quoted them, and when they accepted my quote, I had to find out how to actually write an application that did what they wanted, or find someone who would charge me to write it for me. I chose to write it because I couldn’t afford to pay someone else to do it for me.

Their requirement was pretty simple:

They needed to record the volume of liquid cosmetics that were filled into their containers for quality control needs. They wanted to record the volume by weight, therefore needed to be able to enter the specific gravity of the liquid going into the containers. Fortunately they provided me with the formula to work that out. Scales were connected to the computer and values came in from them, through serial cables, that the application had to record in a database, linking a product, batch and the values to each other.

There were some rules:

  1. Must be password protected.
  2. Must have a scale calibration module.
  3. Must store products for linking to container sizes and batch numbers.
  4. Must have various reports for auditing purposes.

I really didn’t know enough about coding at the beginning of the project to get it done. I had been paid and spent a deposit so had no choice but to deliver an application.

That’s where my learning how to write software really began.

I knew come basic syntax and how to use it, but didn’t really know how to write software, so I just started at the beginning. I knew that I had to provide access to a database for storage and decided to use SQL Server. I was writing in VB6, so found out how to use ADO to connect to SQL Server.

The first thing I did was design the user table and wrote the user login module. Once I had that done, I knew how to access, insert records, update records and delete in a SQL database. From there it was just a case of deciding what to do next and do it. If I didn’t know how to do what I wanted to do, I found out.

That’s how I learned how to write software. It probably wasn’t the best way to go about it, but it worked for me.

My advice to anyone wanting to learn how to write software, who doesn’t want to go the formal route, is to get hold of a computer that can run Visual Studio Express and to decide on a project, then to find out how to write code. Hopefully you have some knowledge about computers, but the most important thing Is to actually dive in and get dirty.

If you are thinking about learning to write software, you aren’t learning, you are thinking about learning.

Don’t think. Do!

How did you learn?

Monday, January 7, 2013

Copy or clone a DataTable and insert rows

From time to time you may have the need to make an exact duplicate of a DataTable. This is very easily done using the .clone() method.

The obvious place to start is to create a DataTable to use as the source...


    ' Create the Datatable
    Dim dtSource As New DataTable("Contacts")

    ' Create some columns for the table
    Dim colID As New DataColumn("id", Type.GetType("System.Int32"))
    Dim colFirstName As New DataColumn("FirstName", Type.GetType("System.String"))
    Dim colLastName As New DataColumn("LastName", Type.GetType("System.String"))

    ' Add the columns to the Datatable
    dtSource.Columns.Add(colID)
    dtSource.Columns.Add(colFirstName)
    dtSource.Columns.Add(colLastName)

    ' Create some rows to the DatatTable
    Dim row1 As DataRow = dtSource.NewRow()
    row1("id") = 1
    row1("FirstName") = "John"
    row1("LastName") = "Smith"

    Dim row2 As DataRow = dtSource.NewRow()
    row2("id") = 2
    row2("FirstName") = "James"
    row2("LastName") = "Bond"

    Dim row3 As DataRow = dtSource.NewRow()
    row3("id") = 3
    row3("FirstName") = "Jane"
    row3("LastName") = "Doe"

    ' Add the rows to the Data Table
    dtSource.Rows.Add(row1)
    dtSource.Rows.Add(row2)
    dtSource.Rows.Add(row3)

Now we have a DataTable with 3 columns and 3 rows called Contacts.

To make a copy of it we use the .Clone() Method...

    Dim dtTarget As DataTable = dtSource.Clone()

That's all there is to making an exact copy of the DataTable. One very important thing keep in mind is that the .Clone() method will only copy the structure and NOT the data or rows from the source DataTable.

If you want to import the rows from the source to the target DataTable, you must use the .ImportRow() method.

    For Each row As DataRow In dtSource.Rows
      dtTarget.ImportRow(row)
    Next

As always... Comments are welcome.


Monday, December 10, 2012

Pass Greater Than or Lesser Than in XML

If you have a need to pass a greater than (>) or lesser than (<) symbol to a SQL stored procedure using a XML string, then this may help you...

Most of the stored procs that I work with in my work environment require me to pass data in to them using XML. This is not by personal choice but it is required to keep to standards set a loooong time ago.

The stored proc builds a query based on the WhereClause that is passed within the XML string.

Passing a where clause that contains the greater than (>) or lesser than (<) symbols will cause an error in your query because they are reserved as building blocks of an XML string. I get around this by using substitution characters like this...


Dim StartDate As String = "2012-12-01"
Dim EndDate As String = "2012-12-07"

Dim XML As New StringBuilder("Exec sp_ReturnData '<Contact Debug=""1"">")
XML.Append("<Record WhereClause="" Where ActionDate [gt]= '" & StartDate & "' And ActionDate [lt]= '" & EndDate & "'"" />")
XML.Append("</Contact>'")

In my stored proc there is a variable declared as @WhereClause which contanes the "WhereClause" that I pass in through the XML.


I perform a character substitution on @WhereClause like this...

Set @WhereClause = Replace(@WhereClause,'[lt]','<')
Set @WhereClause = Replace(@WhereClause,'[gt]','>')

And then I set the sql command and add @WhereClause to it...

Set @SQL = 'SELECT FirstName, Surname From MyTable '
Set @SQL = @SQL + @WhereClause


You can pick your own characters to substitute. Just make sure they aren't characters that you might use elsewhere, or the wrong characters will be substituted.

Do you use a different method to do this? Let me know in the comments.

Monday, November 19, 2012

Building a development machine - Start to finish...

I was recently forced to re-load all of the required software on a new development machine.

No! I'm not stupid. I may be a little crazy, but that's debatable.

I was forced to load the machine because some wonderful people (read thieves) decided that my development laptop and all other computer equipment in my home, should be theirs.

It took 4 days for my office to buy me a new machine, and in those 4 days, I went a little nuts from boredom. No form of computer for more than a day, and I feel it big time.

Anyway... The new laptop arrived with Windows 7 installed.

The first step was to install Visual Studio 2010. That took what seemed to be a lifetime. Then I installed SP1, and that strangely enough took even longer to install.

SQL Server was next. 2008 R2 takes another life time to install and configure. I then had to copy the live DB to my laptop. It's a whole 28Gig!!! That took about 5 or 6 hours to copy, because low and behold, there happened to be network connectivity issues in the office on that particular day.

So now I had a machine that I could at least begin to work on.

Then I found out just how many other little, but essential pieces of software that I use on a daily basis to do seemingly simple things with...

Paint.Net for those little image creation and re-sizing, colour sampling and general editing of images.
Notepad2 or Notepad++ for simple or complex text editing.
Google Chrome and/or Firefox for consistency checking of web apps.
Any nice snipping tool for grabbing of sections of the screen.
Dropbox or Google Drive for cloud storage of almost anything you want to backup.
Acrobat Reader for opening PDF docs.

There are also those million and one little apps that I have written over the years that make my development life simpler.

All in all, I think it took me about 30 hours to get to a point where I could actually do some work. This also excludes re-writing those little apps, that I forgot to backup, that perform small but crucial tasks for me. I know my very big, huge (some very bad swear word here), mess up!

How about you... How long does it take you to get a new machine going to a point of being able to get some work done?


Tuesday, September 25, 2012

IIf in c#


Visual Basic and c# are very similar. That's my opinion, but in some small cases there is no similarity.


The VB IIf function is one example of which there is nothing that looks even slightly similar in c#.
The equivalent in c# is…

a == "1" ? true : false;

How to use this is pretty simple…
    bool ReturnedValue = a == "1" ? true : false;
or
    int ReturnedValue = a == "1" ? 5 : 10;
or
    string ReturnedValue = a == "canine" ? "dog" : "cat";

However you decide to use it, it looks a bit strange to a veteran VB user.
To make it more VB friendly I have these methods that look and function like the VB IIf function…


    private object IIf(bool Expression, object TruePart, object FalsePart)
    {
      object ReturnValue = Expression == true ? TruePart : FalsePart;

      return ReturnValue;
    }

    private string IIf(bool Expression, string TruePart, string FalsePart)
    {
      string ReturnValue = Expression == true ? TruePart : FalsePart;

      return ReturnValue;
    }

    private bool IIf(bool Expression, bool TruePart, bool FalsePart)
    {
      bool ReturnValue = Expression == true ? TruePart : FalsePart;

      return ReturnValue;
    }

    private int IIf(bool Expression, int TruePart, int FalsePart)
    {
      int ReturnValue = Expression == true ? TruePart : FalsePart;

      return ReturnValue;
    }

Use them like this…
    string ReturnedValue = IIf(aa == "canine", "dog", "cat");

Happy coding

Thursday, August 23, 2012

Create a DataTable easily

I have a need to create Data Tables for many reasons in my quest for complete projects. If you need to do it, and you, like me, find the whole thing of defining each column and type a big schlep, check this out.
    Public Shared Function BuildDataTable(ByVal TableName As String,
ByVal Parameters As List(Of TableParams)) As DataTable
      Dim dtReturn As New DataTable(TableName)

      Try
        For Each param As TableParams In Parameters
          dtReturn.Columns.Add(New DataColumn(param.ColumnName, param.ColumnType))
        Next

      Catch ex As Exception : Throw
        
      Finally

      End Try
      Return dtReturn
    End Function

    Public Class TableParams
        Public ColumnName As String
        Public ColumnType As Type

        Public Sub New(ByVal ColumnName As String, ByVal ColumnType As Type)
            Me.ColumnName = ColumnName
            Me.ColumnType = ColumnType
        End Sub
    End Class

Use the above Function like this…

Dim TableParams As New List(Of TableParams)
TableParams.Add(New TableParams("id", Type.GetType("System.Int32")))
TableParams.Add(New TableParams("CompanyName", Type.GetType("System.String")))
       TableParams.Add(New TableParams("EMail", Type.GetType("System.String")))
TableParams.Add(New TableParams("FirstName", Type.GetType("System.String")))
TableParams.Add(New TableParams("Surname", Type.GetType("System.String")))

Dim dtInviteList As DataTable = Common.BuildDataTable("ContactDetails", TableParams)