Archive for 'Coding'

.NET – ToString() vs Convert.ToString()

Calling ToString() on an object almost seems like second nature, however it can cause errors if the object is null.

Calling ToString() on a null object causes the following error

Object reference not set to an instance of an object

The easiest method around this is to use the Convert.ToString() method instead. This casts the object first before trying to convert to a string.

1
2
3
var something = null;
something.ToString(); // Error
Convert.ToString(something); // Success

Debugging A .NET Service With “Attach To Process” In Visual Studio

The tricky thing about building a Windows service is the debugging.   You cant just hit F5 and debug the app from there,  you need to “Attach” to the process.

Thankfully its not very difficult, although some of the guides out there aren’t very clear on this , so follow the following steps and you’ll be debugging in no time.

Continue reading “Debugging A .NET Service With “Attach To Process” In Visual Studio” »

Get Logged In User With ASP.Net

Using the following three ways we can get the User Name using C#

1
2
System.Security.Principal.WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
string strName = p.Identity.Name;

1
string strName = HttpContext.Current.User.Identity.Name.ToString();

1
2
string strName = Request.ServerVariables["AUTH_USER"]; //Finding with name
string strName = Request.ServerVariables[5]; //Finding with index

In Above 3 Cases returning string contains DomainName\WinNTLoggedUserName

(for Ex: Microsoft\Bill.Gates. Here Microsoft is domain Bill.Gates is Logger User Name )

Using string operations seperate the DomainName and UserName.

C# .Net – Save Text Box Content To TXT File

A simple way to store the contents of a text box control to a local .txt file

1
2
3
4
5
6
7
8
//Use StreamWriter class.
StreamWriter sw = new StreamWriter("E:\\test.txt");
 
//Use write method to write the text
sw.Write(textBox1.Text);
 
//always close your stream
sw.Close();

Powershell Method – No Screen Output

Do you ever notice that after you run a method in Powershell you often get some screen output that you didn’t want?

Example, calling a StringBuilder’s .Append() method to simply add more text to the string will echo details of the current capacity and remaining capacity of the StringBuilder object to the screen, which ruins your console look if your carefully laying it out

eg.

1
$StringBuilderObject.Append($alert.Name)

Will output capacity and remaining space information relating to the StringBuilder object to the screen.

To fix this, add [Void] before the beginning the the line, so it looks like this:

1
[Void]$StringBuilderObject.Append($alert.Name)

Rotating URL Script – Dashboard Display

** Edit – Iv written a new tool that handles this job better than the script does, you can find it here: http://gazeek.com/software/dashboard-rotator-utility/ **

Iv been looking for a tool that will display web pages for a period of time and then cycle through to the next page,  performing a loop for usage on large LCD TV screen at work,  this is to be used to display IT Service performance information and status reports.

I was unable to find one that did what I wanted,  bar 1, although it suffered from a problem where after a few hours Internet Explorer would start to die, and it had to be restarted.

I decided to write my own script, and so here it is. Continue reading “Rotating URL Script – Dashboard Display” »

T-SQL Setting Date Format

Occasionally you need to run a DATEDIFF or DATEADD against some dates that are in a reverse format, ie Day:Month:Year instead of Month:Day:Year, theres a simple way to set this in your query without having to string handle it all, using the SET DATEFORMAT parameter.

1
2
SET DATEFORMAT dmy
SELECT DATEDIFF(MINUTE,'29-01-2010 09:13:18','29-01-2010 09:18:18')

Copy your servers PHP.INI

Occasionally you may need to override your hosts or servers PHP.INI config file.  If you do, you’ll want a copy of the original PHP.INI as a basis for your modifications.
You can make a copy of it to your new directory by running a PHP script with the following

1
< ?php system("cp /usr/local/php5/lib/php.ini /home/your-new-path/php.ini"); ?>

Ping Host From VB.Net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
' --- ping the ip adress in the string s_ipaddr, and get
'     the response time in the int32 n_response

 
Imports system.net.networkinformation
Dim ping As New System.Net.NetworkInformation.Ping
Dim reply As System.Net.NetworkInformation.PingReply
reply = ping.Send(s_ipaddr)
If reply.Status = IPStatus.Success Then
' --- handle reachable here
MsgBox("ping time " &amp; reply.RoundtripTime)
Else
' --- handle non reachable here
End If

Pinger! – The Mass Host Ping Tool

PLEASE NOTE:
Pinger! Has Found A New Home At TheMonitoringGuy.com,
Please Visit  http://themonitoringguy.com/software/pinger-mass-host-ping-tool/ To Download The Latest Version Of Pinger!

Pinger! is a tiny ping utility (13KB) that is used to quickly ping a large list of hosts and save the resulting successful and failure host lists into a text file.

Why?

When developing scripts and applications that will touch a large number of hosts,  if many of those hosts are offline or no longer exist, the timeouts involved with this can slow down execution time and dramatically slow down your script or application.

In my case, I was presented with a list of 600+ servers that needed to have the exact same script run against them, a successful server took only several milliseconds to finish,  a failed host took around 4 seconds to time out, clearly I needed to find out which servers were alive and which weren’t and further again I needed to list the successful servers in a clean text file, 1 host per line, so I could import this into my application as an array.

And hence Pinger! was born :)

Usage

Very simple, Pinger.exe when run looks for hosts.txt in the same directory. Simply enter in your list of host names in this text file,  one per line and Pinger! will run over them 1 by 1 and output the results.
Simply extract the .zip containing Pinger.exe and hosts.txt to the same directory and open Pinger.exe.

Output

2 files are outputted.  these are:

  • success.txt – The list of successfully pinged hosts, in per line format
  • failure.txt – The list of hosts that failed to ping, in line by line format.

Download Pinger Here!

T-SQL Copy Table To Another Database

Occasionally, you might do something stupid like run a SQL script on the wrong database, or setup your application to configure its table structure on the master DB.

When you do, here’s an easy way to copy the tables to another database (on the same server)

1
2
SELECT * INTO target_db.target_table_name
FROM source_db.source_table_name

SQL Replace Nulls With Blank String

Simple way to replace NULL values in your queries with blank strings by using the IsNull function.

This will allow for problem free string creation etc.

1
2
3
SELECT IsNull(ColumnName, '') 
As NewColumnName 
FROM TableName

More information can be found here: http://msdn.microsoft.com/en-us/library/ms184325.aspx

VBScript To Pull Events From Event Log And Email To Yourself – Past 24 Hours

So, you want to see what events have occured on a server in the past 24 hours. Maybe you have a problematic server, throwing errors but your event log is so massive , its hard to sort through.

This script will sift through your entire event log, searching for any events in the past 24 hours that match your event code, it will save the results to a .TXT file , and then email them to you. v.handy

Continue reading “VBScript To Pull Events From Event Log And Email To Yourself – Past 24 Hours” »

VB.Net Forms Confirmation Box

How to create a simple confirmation box in a VB.Net WinForms application.    This will pop up a typical “Do You Wish To Continue ? ” Box , to which each button has a different action.

Continue reading “VB.Net Forms Confirmation Box” »

Kill All Processes Of Certain Application In Unix/Linux

This is a very helpful command I use regularly.

If your like me, you open several instances of applications like “VI” and leave them in the background, most of the time without meaning to.  Eventually you run a “PS -U” to view all your processes running and realize that theres 10 copies of the application running in the background which you havnt closed. Heres a command to quickly clear that up. Continue reading “Kill All Processes Of Certain Application In Unix/Linux” »

Embedding XHTML Compliant Flash Files

All to often people all over the web use non-xhtml embedding on their sites.
Use the following code to embed fully XHTML 1.0 compliant flash objects. Continue reading “Embedding XHTML Compliant Flash Files” »

Importing VBS Files In Your VBScript Project

If you have certain functions you use over and over , why not compile them all into a single library file , and simply “Import” them into your new projects, like a real object oriented language does?.

If your one of those people that has a script to do everything , you may find the need to organise your functions and files necessary. You can use this method to store configuration options too.

Here’s how.

Continue reading “Importing VBS Files In Your VBScript Project” »

How To Convert Custom Date Format In VB.Net

Problem:

I want to convert my custom 12 hour date and time string into a proper 24 hour DateTime format. Continue reading “How To Convert Custom Date Format In VB.Net” »

Introduction To Powershell (Move Over Bash)

For years UNIX/Linux administrators have looked down on the windows environment,one of the main reasons being that windows did not have a nice CLI. UNIX has always had sh, bash, ksh which are great shells. Microsoft has now introduced Windows PowerShell (Codename MONAD) a very powerful .NET based shell. A shell is a great tool for system administrators to automate tasks. Continue reading “Introduction To Powershell (Move Over Bash)” »

SMF Dynamic Meta Tags

So you need Dynamic Meta Description and Keywords In Your SMF Forum? Hoping To Boost Your Google Ranks? Here’s How. Continue reading “SMF Dynamic Meta Tags” »