How to tips and tricks for Microsoft Visual Studio .net

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)

Word cannot register your account


I know that this isn't .net related, but I couldn't find much to help with this problem anywhere, and since I managed to solve it for myself, I thought I would post my solution here. I hope you don't mind.
If you receive the message "Word cannot register your account" when trying to register your account on Blogger.com, try the following…

I recently found something that may help with this problem. It is caused by your google account not allowing access to "less secure" applications. MS Word is one of them, and access is denied by default.

To allow less secure applications to sign in using your Google account, you need to change the access setting.

Follow the following link and select "Turn On": 

https://www.google.com/settings/security/lesssecureapps

This will allow you to log into blogger through MS Office, and to post to your blog.

Please let me know how it works out for you in the comments.

1. Log into the Blogger settings page for your account.
2. Send an "Author" invite to yourself at a different Google account to the one you used to log into Blogger with.
3. Follow the link sent to your 2nd Google account, and log into Blogger using the 2nd Google account. This will set your 2nd account up on your blog with "Author" privileges.
4. Go back to word and use your 2nd Google account credentials to register using word on Blogger.
This worked for me. I hope it does for everyone else with this problem.
I haven't tried it, but it may just work to see if you can change your main Google account to have author privileges in Blogger instead of or as well as having "Admin" privileges.