Sunday, October 21, 2012

JavaScript SecondIndexOf or (x)indexOf

The JavaScript indexOf() and lastIndexOf() methods return the position of the first and last occurrence of a specified value in a string

You can learn more about them here

These can be very usefull, but what if you want the Second indexOf() to get the second occurrence of a specified value in a string. There is no standard JavaScript method for this, so I made my own one;

 function SecondIndexOf(Val, Str)  
   var Fst = Str.indexOf(Val);  
   var Snd = Str.indexOf(Val, Fst+1)  
   return Snd  

But why stop there, what if you want the third or fourth indexOf()
The following function lets you specify which occurrence of the specified value to find in the string;

 function xIndexOf(Val, Str, x)  
   if (x <= (Str.split(Val).length - 1)) {  
     Ot = Str.indexOf(Val);  
     if (x > 1) { for (var i = 1; i < x; i++) { var Ot = Str.indexOf(Val, Ot + 1) } }  
     return Ot;  
   } else { alert(Val + " Occurs less than " + x + " times"); return 0 }  

Here is an egsample of how you can use this;

   var PicPath = "/somedirectory/pics/";  
   var AppPath = picpath.substring(0, xIndexOf('/', PicPath, 2) + 1);  

Let me know if you found this usefull, or can recommend any enchancments.

Sunday, October 7, 2012

Visual Studio Tips & Tricks to Streamline Development

Here are a few of my favorite Visual Studio tips & tricks that I use to streamline my development;

Record and play temporary macro

Press Ctrl+Shift+R to record a new temporary macro, then press Ctrl+Shift+R to stop recording.
Ctrl+Shift+P will play the recorded macro.

Previous cursor positions

Ctrl+- (i.e. Ctrl and Hyphen)  cycles you through the code positions that you have visited.
Use Ctrl+Shift+- to navigate in the opposite direction.

Matching brace/comment/region/quote

Ctrl+] takes you to the matching brace. It also takes you to the matching comment, region or quote depending on where your cursor is.

Intellisense suggestions

Press Ctrl+Shift+Space to bring up the intellisense suggestions.

Line numbering

To enable/disable Line number go to Tools|Options|Text Editor|All Languages|General|Line numbers.

If you want to set this option for only one language, then choose the appropriate language instead of All Languages.

Code Snippets

There are Code Snippets for most methods that get used often. To try this, type “for”, and then hit you tab key twice. You can also do this with your “If” and “try” Statements. You can also add your own Code Snippets if there are chunks of code that you often use and don’t want to type in full each time.

Go to  to learn more about this.

Sunday, September 16, 2012

JavaScript Error – Submit is not a Function

If you get the JavaScript error “Submit is not a Function” then you are probably trying to call the Form’s Submit() Method, but you also have a button whitch is called Submit. This results in a conflict in the JavaScript becuse the Submit Method is already bound to the button.

The Solution is simply to change the name of the button so that name=”newname” (or what ever you prefer).

Sunday, September 9, 2012

C# accessing or copying files over a network that requires authentication

I was working on a project with the requirement that I copy files over a network connection that needed username and password  authentication. The big problem that I found was that the .NET framework did not natively expose the win32 API needed to do this, so I had to write my own wrapper using P/Invoke.

You can learn more about P/Invoke on MSDN or check out the wiki for tons of great resources.

Here is the class
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.ComponentModel;  
 using System.Runtime.InteropServices;  
 using System.Security.Principal;  
 namespace MyAppName  
 Public class SoddingNetworkAuth : IDisposable  
         [DllImport("advapi32.dll", SetLastError=true)]  
 Private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);  
     [DllImport("kernel32", SetLastError = true )]  
 Privatestaticexternbool CloseHandle(IntPtr hObject);  
 Private IntPtr userHandle = IntPtr.Zero;  
 Private WindowsImpersonationContext impersonationContext;  
 Public SoddingNetworkAuth(string user, string domain, string password)  
 if ( ! string.IsNullOrEmpty( user ) )  
 // Call LogonUser to get a token for the user  
 Bool loggedOn = LogonUser( user, domain, password,  
                 9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,  
                 3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,  
 Out userHandle );  
 if ( !loggedOn )  
 throw new Win32Exception( Marshal.GetLastWin32Error() );  
 // Begin impersonating the user  
 impersonationContext = WindowsIdentity.Impersonate( userHandle );  
 Public void Dispose()  
 if ( userHandle != IntPtr.Zero )  
 CloseHandle(userHandle );  
 if ( impersonationContext != null )  

Then you consume the class as follows
 using (new SoddingNetworkAuth(@"UserName", @"ServerName", @"Password"))  
      //Do something  

It’s that easy!

Let me know if this class helped or even if I just got you pointed in the right direction to solve your own unique problem.

Saturday, September 1, 2012

A New Job and A New Focus

I would like to start by apologizing for not posting on this blog for such a long time, I have just started a new job in a new city and I’ve been hellishly busy as a result.

The New Job

This all happened because I was getting complacent at my old job, having been there for 13 years, and was not growing as a developer. At the same time, I was suddenly inundated with recruiters desperate for a senior software developer. At first I was just going to interviews to find out what was available and how it compared, but I soon realized that I had fallen behind on the technology that people are using for software development. 

As a self taught developer, I have been wanting a mentor to help me grow my skills to become a better developer for a long time. I was also a jack of all trades in my old job; handling SEO, documentation, support, and project management over and above software development. So when I found a great development orientated company that didn’t care about my lack of qualification, and people that I really clicked with, I decided to jump at the opportunity.

The new job was in another city, but I have family there so, at the risk of sounding like a Will Smith song, I packed my bags and moved in with my Aunt and Uncle in Durban, and that's the story of how my life got turned upside down, and I became a senior developer at my new job.

The New Focus

What this all means for you dear reader, is that I will be changing the focus of this blog to deal primarily with C# and ASP.NET development. I will still leave my old SEO post up, but I really can be bother with trying to keep up will all of Google’s changes and new Metrics.

I would also like to take this opportunity to encourage you to take a look at your career and ask yourself if you have gotten stuck in a rut because you are just too comfortable. Are you still learning and growing, or have you allowed yourself to get into a dull routine?

Monday, July 23, 2012

C# Get Primary ID Key on SQL Insert


How do I get the primary ID key on SQL Insert in C#

If you need to get the auto-generated Primary Key of a newly added record when inserting into SQL server, it can be a nightmare. Some people try to use timestamps and unique data to look up the record in a new query, but you don’t need to do all that.

Update: I have different post for how to Get the Primary Key on insert using Entity Framework. Click here


Lucky for us there is a wonderful SQL tool called scope_identity()

You can Google it if you want all the gory details. More importantly, here is a basic code example to get you going.

Code Sample;

1:        Int32 newProdID = 0;  
2:        string strSQL = "Insert into Table (Field1, Field2) values (@Field1, @Field2); "  
3:        strSQL += "SELECT CAST(scope_identity() AS int)";  
4:        SqlConnection conn = new SqlConnection(sConn);  
5:        try  
6:        {  
7:          conn.Open();  
8:          using (SqlCommand comd = new SqlCommand(strSQL, conn))  
9:          {  
10:            comd.Parameters.Add("@Field1", SqlDbType.VarChar);  
11:            comd.Parameters["@Field1"].Value = "some data";  
12:            comd.Parameters.Add("@Field2", SqlDbType.VarChar);  
13:            comd.Parameters["@Field2"].Value = "some data";  
14:            newProdID = (Int32)comd.ExecuteScalar();  
15:          }  
16:          conn.Close();  
17:        }  
18:        catch (Exception err)  
19:        { }  

If you want to streamline your work you can update your database in a method and return the Primary Key ID as an integer.

Code Block formated by

Sunday, May 13, 2012

Facebook Marketing Fail - A mini case study

Hi guys, I just witnessed a massive marketing failure this last week on facebook (ok… I kinda, sorta, am partly to blame), and I’m going to tell you how it went down.

Facebook Blowup

So my favourite local meat deli decided that they needed to do some facebook marketing, and set up a group on facebook, and they even managed to get 680 members in the group. That’s pretty amazing for a local deli.

The problem was that they started sending marketing messages directly to all 680 members. While most of us are happy to get a bit of marketing in our news feed(Especially if it’s for a great bargain) nobody like getting spam direct into their inbox. What makes it worse, is that whenever somebody replies to this message, the reply goes to all 680 members also.

Now add in mobile devices with facebook plug-ins that let you know every time you get a direct message and things start getting heated. 

Then on Thursday, it all came tumbling down. 


Some random guy with only goodness in his heart, decided to point out the pink elephant in the room.
Yes, that's me... and no, I did not plan this.

One reply led to another, and then another, and on it went from 2:00pm until about 5:00pm, every 5 or 10 minutes my cell phone would beep with another irate or confused reply. Towards the end, some people were getting really mad and using explicit language, as you can see from the screen shot below.

I really did not mean for this to happen, and apologise profusely to the company and the users. In my defence, I was not the first user to reply.

Yes, Marketing your brand on facebook is a great idea.

But, and this is important, you have to know how to do it properly, or you could end up with a PR nightmare. There are a lot of companies out there who have leant the hard way that marketing in social media is a highly specialised skill and doing it wrong can cause irreparable damage.

If you want to be the Social Media specialist at your company, or want to market your own brand but don’t have the funding to hire a specialist, then check out Facebook Marketing For Smart People.

Thursday, April 19, 2012

Slideshow with multiple hyperlinks links per slide

Have you seen those websites with the cool slideshows that have items on each slide which link to other pages?

Well, one of my customers had seen this, and that’s what they wanted, only they wanted to have 3 different links on each slide.

There are a lot of WordPress plugins that provide this sort of feature, but not with the degree of control that I wanted.

The solution that I found was to use my favourite slideshow tool (jQuery cycle)  and add image maps to each slide.

This means that I can manage what parts of each slide are links and I can have as many links as I want per slide.

You can learn more about the map tag and image maps on this page :

And you can get jQuery cycle from :

Wednesday, April 4, 2012

jQuery cycle not crossfading in WordPress

If your jQuery cycle is not cross fading or is choppy and you are using it in WordPress or the content section of your CMS then this post is for you...

The Problem

If you put your slideshow in the content of a page, you need to be aware that the standard WYSIWYG editor places tags in the code when presenting the page, but then hides then when you use the HTML view. 

As a result, what looks like this in the editor;

Is actually this when the pages is viewed;

This of course messes things up a bit in the in the jQuery Cycle Plugin’s presentation, and instead of a smooth crossfade from slide to slide,  the slides fade out to nothing, waits for a while, and then your next slide fades in.

The Fix

I’m sure you can tweak the WYSIWYG editor to fix this, but I found it easier to just remove all spaces between the elements in the slide show like this;

PS: jQuery cycle is my favourite slideshow tool, check it out here

Thursday, March 29, 2012

Create .sln file for ASP.NET

How to create a .sln file for an existing ASP.NET application

  • From the Visual Studio menu choose "File | New | Project..."
  • From the resulting dialog, under "Other Project Types" choose "Visual Studio Solutions" and create a blank solution.
  • Then from the Visual Studio menu choose "File | Add | Existing Web Site" and point it to your web site to add it to your new solution.

It’s that simple