Friday, February 25, 2011

SQL: Dynamically List Tables in SQL

SQL Server 2005 or 2008:
SELECT * FROM information_schema.tables 
SQL Server 2000:
SELECT * FROM sysobjects WHERE xtype='U' 

Friday, February 18, 2011

SQL: Ping Test Stored Procedure

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_Ping]
@hostname varchar(255)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @cmd sysname
SET @cmd = 'ping -n 1 ' + @hostname
CREATE TABLE #tmp( Result VARCHAR(255) )
INSERT INTO #tmp EXEC xp_cmdshell @cmd
IF EXISTS(
SELECT * FROM #tmp
WHERE Result LIKE '%Reply%' )
PRINT 'REPLY'
ELSE
PRINT 'TIMEOUT'
DROP TABLE #tmp
END

Logparser: Converting EVT to EVTX

Getting "Task Aborted" errors?

wevtutil export-log application.evt application.evtx /lf

Wednesday, February 16, 2011

SQL: Group By Date, Show EventCount and ErrorCount

USE EventLogs
SELECT
CAST( FLOOR( CAST( a.TimeWritten AS FLOAT ) ) AS SMALLDATETIME ) AS 'Date',
COUNT( a.EventID ) AS 'EventCount',
(
SELECT COUNT( * )
FROM log_CCRVCU01 b
WHERE
CAST( FLOOR( CAST( a.TimeWritten AS FLOAT ) ) AS SMALLDATETIME )
= CAST( FLOOR( CAST( b.TimeWritten AS FLOAT ) ) AS SMALLDATETIME )
AND
b.EventType = 1
) AS 'ErrorCount'
FROM log_CCRVCU01 a
GROUP BY
CAST( FLOOR( CAST( a.TimeWritten AS FLOAT ) ) AS SMALLDATETIME )

Tuesday, February 15, 2011

LogParser: OMG, ignoreIdCols

Took me forever to find the solution:

Logparser to SQL, check!
Logparser to SQL with Identity column, FAIL!

use the switch -ignoreIdCols:ON

/sigh

Monday, February 14, 2011

SQL: If No Identity Column, Create It (stored procedure)

USE [EventLogs]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_CheckID]
@host varchar(35)

AS
BEGIN

SET NOCOUNT ON;

    EXEC(
'IF NOT EXISTS( ' +
' SELECT * FROM INFORMATION_SCHEMA.columns ' +
' WHERE table_name = ''log_' + @host + '''' +
' AND column_name = ''ID'') ' +
' BEGIN ' +
' ALTER TABLE log_' + @host + ' ADD ID INT IDENTITY ' +
' END '
)

END

Batch DateTime To SQL DateTime

Formatting DateTime in a batch file to fit into SQL DateTime colume:


@for /f "tokens=1-6 delims=0123456789 " %%i in ("%date%") do set StartDate=%%i%%j%%k%
@for /f "tokens=1-6 delims=%StartDate% " %%i in ("%date%") do (
set day=%%i
set month=%%j
set year=%%k
)

@for /f "tokens=1-6 delims=0123456789 " %%l in ("%time%") do set StartTime=%%l%%m
@for /f "tokens=1-6 delims=%StartTime% " %%l in ("%time%") do (
set hour=%%l
set min=%%m
)
@set now="%day%-%month%-%year% %hour%:%min%"

Batch: Change to Uppercase or Lowercase in Batch File

SNIPPET from ROB VANDERWOUDE's BATCH Collection


SETLOCAL ENABLEDELAYEDEXPANSION
SET String=Abc
SET String
CALL :UpCase String
SET String
CALL :LoCase String
SET String
ENDLOCAL
GOTO:EOF

:LoCase
:: Subroutine to convert a variable VALUE to all lower case.
:: The argument for this subroutine is the variable NAME.
SET %~1=!%1:A=a!
SET %~1=!%1:B=b!
SET %~1=!%1:C=c!
SET %~1=!%1:D=d!
SET %~1=!%1:E=e!
SET %~1=!%1:F=f!
SET %~1=!%1:G=g!
SET %~1=!%1:H=h!
SET %~1=!%1:I=i!
SET %~1=!%1:J=j!
SET %~1=!%1:K=k!
SET %~1=!%1:L=l!
SET %~1=!%1:M=m!
SET %~1=!%1:N=n!
SET %~1=!%1:O=o!
SET %~1=!%1:P=p!
SET %~1=!%1:Q=q!
SET %~1=!%1:R=r!
SET %~1=!%1:S=s!
SET %~1=!%1:T=t!
SET %~1=!%1:U=u!
SET %~1=!%1:V=v!
SET %~1=!%1:W=w!
SET %~1=!%1:X=x!
SET %~1=!%1:Y=y!
SET %~1=!%1:Z=z!
GOTO:EOF

:UpCase
:: Subroutine to convert a variable VALUE to all upper case.
:: The argument for this subroutine is the variable NAME.
SET %~1=!%1:a=A!
SET %~1=!%1:b=B!
SET %~1=!%1:c=C!
SET %~1=!%1:d=D!
SET %~1=!%1:e=E!
SET %~1=!%1:f=F!
SET %~1=!%1:g=G!
SET %~1=!%1:h=H!
SET %~1=!%1:i=I!
SET %~1=!%1:j=J!
SET %~1=!%1:k=K!
SET %~1=!%1:l=L!
SET %~1=!%1:m=M!
SET %~1=!%1:n=N!
SET %~1=!%1:o=O!
SET %~1=!%1:p=P!
SET %~1=!%1:q=Q!
SET %~1=!%1:r=R!
SET %~1=!%1:s=S!
SET %~1=!%1:t=T!
SET %~1=!%1:u=U!
SET %~1=!%1:v=V!
SET %~1=!%1:w=W!
SET %~1=!%1:x=X!
SET %~1=!%1:y=Y!
SET %~1=!%1:z=Z!
GOTO:EOF

Sunday, February 13, 2011

Vbscript: Parsing WorldofLogs.com - Part 2 Parsing Html Tables

sDir = "data\"

Set oRe = CreateObject("vbscript.regexp")
Set oFs = CreateObject( "Scripting.FileSystemObject" )
Set oFileOut = oFs.OpenTextFile("test1.csv",2,True)

If sDir <> "" Then
If oFs.FolderExists( sDir ) Then
Set oFolder = oFs.GetFolder( sDir )
Set oFiles = oFolder.Files
For Each oFile In oFiles
sNewColumns = Replace( oFile.Name, "-", "," )
sNewColumns = Replace( sNewColumns, ".txt", "" )
Set oFileIn = oFs.OpenTextFile( sDir & oFile.Name, 1 )
If oFileIn.AtEndOfStream Then
WScript.Echo "File contains no data: " & oFile.Name
sData = ""
Else
sData = oFileIn.ReadAll

With oRe
.IgnoreCase = True
.Global = True
.MultiLine = True

.Pattern = "<table class='playerRankMixed'>([\S\s]*?)</table>"
Test = oRe.Test( sData )
If Test Then
Set Matches = .Execute( sData )
sTable = Matches(0).SubMatches(0)

sTable = Replace(sTable,"<th","<td")
sTable = Replace(sTable,"</th>","</td>")
.Pattern = "<tr([\S\s]*?)</tr>"
Set Rows = .Execute(sTable)
'ReDim aRow(Rows.Count)
'i = 0
For Each Row In Rows
' aRow(i) = Row.Value
' i = i + 1
'Next
'For Each r In aRow

oFileOut.Write( sNewColumns )

.Pattern = "<td([\S\s]*?)</td>"
Set Cols = .Execute( Row.Value )'r)
For Each Col In Cols

' Remove Crap Html Code
.Pattern = "</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>"
sNoHtml = Trim( .Replace( Col.Value, "" ) )
oFileOut.Write( "," & sNoHtml )

Next
oFileOut.WriteLine()
Next
End If
End With
End If
WScript.Echo sNewColumns
' tenStop = tenStop + 1: If tenStop > 9 Then Wscript.Echo "Exit Early!": Wscript.Quit
Next
Else
WScript.Echo "Directory does not exist: " & sDir
End If
Else
WScript.Echo "No directory specified: " & sDir
End If
Set oFs = Nothing

WScript.Echo "Done!"
WScript.Quit

Vbscript: Downloading a Webpage to File

Took me an hour to find the cause of my pains. Thanks to Jon Bohagier @ bohack.com [article].

Error when saving a website: "Microsoft VBScript runtime error: Invalid procedure call or argument"
Issue = Unicode is evil
Solution = Convert to ascii



Dim FSO, dFile, sHTML

sHTML = Get_HTML ("http://www.google.com")

Set FSO = CreateObject("Scripting.FileSystemObject")
Set dFile = FSO.CreateTextFile("SaveFile.html", True)

dFile.Write UniToAsc(sHTML)
dFile.Close

Set dFile = Nothing
Set FSO = Nothing

Private Function Get_HTML (up_http)
 Dim xmlhttp
 Set xmlhttp = createobject("msxml2.xmlhttp.6.0")

 xmlhttp.open "get", up_http, False
 xmlhttp.send
 Get_HTML = xmlhttp.responsetext

 set xmlhttp = Nothing
End Function

Private Function UniToAsc(sString)
 Dim nLen, nPTR, sAsc
 nLen = Len(sString)

 For nPTR = 1 To nLen
  sAsc = sAsc & Chr(Asc(Mid(sString, nPTR, 1)))
 Next

 UniToAsc = sAsc
End Function

Vbscript: Parsing WorldofLogs.com - Part 1 Downloading HTML

**** WARNING: THIS PROCESS WILL TAKE 4+ HOURS ****

Downloading the files:

Dim Raids(2)
Raids(0) = "Blackwing_Descent"
Raids(1) = "Bastion_of_Twilight"
Raids(2) = "Throne_of_the_4_Winds"

Dim RaidType(3)
RaidType(0) = "10N"
RaidType(1) = "10H"
RaidType(2) = "25N"
RaidType(3) = "25H"

Dim Boss(2,5)
Boss(0,0) = "Magmaw"
Boss(0,1) = "Omnotron_Defense_System"
Boss(0,2) = "Chimaeron"
Boss(0,3) = "Atramedes"
Boss(0,4) = "Maloriak"
Boss(0,5) = "Nefarian"
Boss(1,0) = "Halfus_Wyrmbreaker"
Boss(1,1) = "Valiona_&_Theralion"
Boss(1,2) = "Twilight_Ascendant_Council"
Boss(1,3) = "Cho'gall"
Boss(2,0) = "Conclave_of_Wind"
Boss(2,1) = "Al'Akir"

Dim sClass(29)
sClass(0) = "Blood_Death_Knight"
sClass(1) = "Frost_Death_Knight"
sClass(2) = "Unholy_Death_Knight"
sClass(3) = "Balance_Druid"
sClass(4) = "Feral-Cat_Druid"
sClass(5) = "Restoration_Druid"
sClass(6) = "Beast%20Mastery_Hunter"
sClass(7) = "Marksmanship_Hunter"
sClass(8) = "Survival_Hunter"
sClass(9) = "Arcane_Mage"
sClass(10) = "Fire_Mage"
sClass(11) = "Frost_Mage"
sClass(12) = "Holy_Paladin"
sClass(13) = "Protection_Paladin"
sClass(14) = "Retribution_Paladin"
sClass(15) = "Discipline_Priest"
sClass(16) = "Holy_Priest"
sClass(17) = "Shadow_Priest"
sClass(18) = "Assassination_Rogue"
sClass(19) = "Combat_Rogue"
sClass(20) = "Subtlety_Rogue"
sClass(21) = "Elemental_Shaman"
sClass(22) = "Enhancement_Shaman"
sClass(23) = "Restoration_Shaman"
sClass(24) = "Affliction_Warlock"
sClass(25) = "Demonology_Warlock"
sClass(26) = "Destruction_Warlock"
sClass(27) = "Arms_Warrior"
sClass(28) = "Fury_Warrior"
sClass(29) = "Protection_Warrior"

Function GetHTML( sUrl )
Dim oXml
Set oXml = CreateObject("Msxml2.XmlHttp.3.0")
oXml.Open "GET", sUrl, False
oXml.Send
GetHTML = oXml.ResponseText
Set oXml = Nothing
End Function

Function UniToAsc(sUnicode)
Dim i, sAscii
For i = 1 To Len( sUnicode )
sAscii = sAscii & Chr( Asc( Mid(sUnicode, i, 1) ) )
Next
UniToAsc = sAscii
End Function

Set oFs = CreateObject( "Scripting.FileSystemObject" )
For a = 0 To 2 'raid
For b = 0 To 5 'boss
For c = 0 To 3 'raidtype
For d = 0 To 29 'sClass
For page = 1 To 5
If Boss(a,b) <> "" Then
sFile = "data\" & Raids(a) & "-" & Boss(a,b) & "-" _
& RaidType(c) & "-" & sClass(d) _
& "-" & page & ".txt"
sUrl = "http://worldoflogs.com/rankings/players/" _
& Raids(a) & "/" & Boss(a,b) & "/" _
& RaidType(c) & "/" & sClass(d) _
& "/?page=" & page
Set oFile = oFs.CreateTextFile( sFile, True )
oFile.Write( UniToAsc( GetHTML( sUrl ) ) )
oFile.Close
Set oFile = Nothing
End If
Next
Next
Next
Next
Next
Set oFs = Nothing

Msgbox "Done!"
WScript.Quit

Saturday, February 12, 2011

Asp.net: Event Logs to Asp.net

<% @Page Language="C#" %>
<% @Import Namespace="System.Diagnostics" %>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e)
{
  BindGrid();
}

void BindGrid()
{
  EventLog aLog = new EventLog();
  aLog.Log = "System";
  aLog.MachineName = ".";
 
  LogGrid.DataSource = aLog.Entries;
  LogGrid.DataBind();
}
</script>
<body bgcolor="#ffffff">

<h3>System Event Log</h3>

<form runat="server">
<asp:DataGrid id="LogGrid" runat="server"
    Font-Size="8pt"
    AllowPaging="True"
    AutoGenerateColumns="true">
</asp:DataGrid>
</form>

</body>
</html>

Asp.net: Run Batch from Asp as Specific User

Repost:


Imports System.Diagnostics
Imports System.IO
Partial Class RunBatchFile
    Inherits System.Web.UI.Page
    Dim _password As New System.Security.SecureString
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim password As String
        'Read from any Registry or Encrypted config file if you like for added security.
        password = "YOUR___PASSWORD"  
        For Each c As Char In password
            _password.AppendChar(c)
        Next
        Dim strFilePath As String = "c:\\temp\\test.bat"
        Dim psiMyProcess As ProcessStartInfo = New ProcessStartInfo("cmd.exe")
        psiMyProcess.LoadUserProfile = True
        psiMyProcess.UserName = "Administrator"
        psiMyProcess.Password = _password
        psiMyProcess.UseShellExecute = False
        psiMyProcess.CreateNoWindow = True
        psiMyProcess.RedirectStandardOutput = True
        psiMyProcess.RedirectStandardInput = True
        psiMyProcess.RedirectStandardError = True
        psiMyProcess.WorkingDirectory = "c:\\temp\\"
        Dim prcProcess As Process = Process.Start(psiMyProcess)
        Dim strm As StreamReader = File.OpenText(strFilePath)
        Dim strOut As StreamReader = prcProcess.StandardOutput
        Dim strIn As StreamWriter = prcProcess.StandardInput
        Do While strm.Peek() <> -1
            strIn.WriteLine(strm.ReadLine())
        Loop
        strm.Close()
        strIn.WriteLine(String.Format("# {0} ran successfully. Exiting now!", strFilePath))
        strIn.WriteLine("Exit")
        prcProcess.Close()
        Dim strOutput As String = strOut.ReadToEnd().Trim()
        strIn.Close()
        strOut.Close()
        Response.Write(String.Format("<font face=courier size=0>{0}</font>", _
                strOutput.Replace(System.Environment.NewLine, "<br>")))
    End Sub
End Class

Reference:
http://dotnetscraps.com/dotnetscraps/post/Run-a-batch-file-as-a-specific-User-(or-Administrator)-from-ASPNET.aspx

Asp.net: Show/Hide Rows


<%@ Page Language="VB" %>
<!DOCTYPE html>

<script runat="server">
    Sub submit(sender As Object, e As EventArgs)
        If row2.Visible = False Then
            row2.Visible = True
        Else
            row2.Visible = False
        End If
    End Sub
</script>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:Button ID="id" Text="Submit" OnClick="submit" runat="server" />
            <div>
                <table border="1">
                    <tr id="row1" runat="server">
                        <td>1</td><td>2</td><td>3</td>
                    </tr>
                    <tr id="row2" runat="server">
                        <td>4</td><td>5</td><td>6</td>
                    </tr>
                    <tr id="row3" runat="server">
                        <td>7</td><td>8</td><td>9</td>
                    </tr>
                    <tr id="row4" runat="server">
                        <td>10</td><td>11</td><td>12</td>
                    </tr>
                </table>
            </div>
        </form>
    </body>
</html>


Logparser: Microsoft Examples

These examples include:

Scenario 1: Parsing large text files for a specific text

Scenario 2: Finding the 10 largest files from a specific folder, including its subfolders

Scenario 3: Finding the 20 slowest pages in your Web site

Scenario 4: Finding the 20 most commonly used .aspx pages in your Web site


http://support.microsoft.com/kb/910447

Asp.net: Checkbox Toggle Row

<%@ Page Language="VB" %>
<!DOCTYPE html>

<script runat="server">
    Sub toggleRow1(sender As Object, e As EventArgs)
        row1.Visible = checkbox1.checked
    End Sub
    Sub toggleRow2(sender As Object, e As EventArgs)
        row2.Visible = checkbox2.checked
    End Sub
    Sub toggleRow3(sender As Object, e As EventArgs)
        row3.Visible = checkbox3.checked
    End Sub
</script>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:CheckBox id="checkbox1" runat="server"
                AutoPostBack="True"
                Checked="True"
                Text="Row1"
                TextAlign="Right"
                OnCheckedChanged="toggleRow1"/>
            <asp:CheckBox id="checkbox2" runat="server"
                AutoPostBack="True"
                Checked="True"
                Text="Row2"
                TextAlign="Right"
                OnCheckedChanged="toggleRow2"/>
            <asp:CheckBox id="checkbox3" runat="server"
                AutoPostBack="True"
                Checked="True"
                Text="Row3"
                TextAlign="Right"
                OnCheckedChanged="toggleRow3"/>
            <div>
                <table border="1">
                    <tr id="row1" runat="server">
                        <td>1</td><td>2</td><td>3</td>
                    </tr>
                    <tr id="row2" runat="server">
                        <td>4</td><td>5</td><td>6</td>
                    </tr>
                    <tr id="row3" runat="server">
                        <td>7</td><td>8</td><td>9</td>
                    </tr>
                    <tr id="row4" runat="server">
                        <td>10</td><td>11</td><td>12</td>
                    </tr>
                </table>
            </div>
        </form>
    </body>
</html>


SQL: Better Row Count

More efficient way of getting SQL table count.

I need to test these:

SQL 2005

SELECT OBJECT_NAME(P.object_id) AS [Name], P.* FROM sys.indexes I
INNER JOIN sys.partitions P ON P.object_id = I.object_id AND P.index_id = I.index_id
WHERE I.index_id < 2 AND P.object_id = OBJECT_ID(N'myTable')

Or

SQL 2008

SELECT 'MyTable' AS [Name], rows FROM sysindexes WHERE id = OBJECT_ID('MyTable') AND indid < 2

Ref: http://www.developmentalmadness.com/archive/2008/04/01/fast-rowcount-for-sql-2005.aspx

SQL: Paging Large Tables

My database has hundreds of millions of records.
Here is what I found to help me efficiently page the data.

Excellent article by Greg Hamilton:
A More Efficient Method for Paging Through Large Result Sets

Much better than Scott Mitchell's:
Efficiently Paging Through Large Amounts of Data

Asp.net: Show/Hide Rows


<%@ Page Language="VB" %>
<!DOCTYPE html>

<script runat="server">
    Sub submit(sender As Object, e As EventArgs)
        If row2.Visible = False Then
            row2.Visible = True
        Else
            row2.Visible = False
        End If
    End Sub
</script>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:Button ID="id" Text="Submit" OnClick="submit" runat="server" />
            <div>
                <table border="1">
                    <tr id="row1" runat="server">
                        <td>1</td><td>2</td><td>3</td>
                    </tr>
                    <tr id="row2" runat="server">
                        <td>4</td><td>5</td><td>6</td>
                    </tr>
                    <tr id="row3" runat="server">
                        <td>7</td><td>8</td><td>9</td>
                    </tr>
                    <tr id="row4" runat="server">
                        <td>10</td><td>11</td><td>12</td>
                    </tr>
                </table>
            </div>
        </form>
    </body>
</html>

Asp.net: Simple Form


<%@ Page Language="VB" %>
<!DOCTYPE html>

<script runat="server">
    Sub submit(sender As Object, e As EventArgs)
        lbl1.Text = "Hello " & name.Text & "!"
    End Sub
</script>

<html>
    <head>
        <title>Test Main</title>
    </head>
    <body>

        <form id="form1" name="myForm" method="post" action="default.aspx" runat="server">
        <div>
            Hello World!
        </div>
        Your name: <asp:TextBox id="name" runat="server" />
        <asp:Button ID="id" Text="Submit" OnClick="submit" runat="server" />
        <p><asp:Label id="lbl1" runat="server" /></p>
        </form>
    </body>
</html>

Thursday, January 13, 2011

MTU Settings

I log into my game and everything is good under 200ms latency. Then, after 5 minutes it spikes to 2k ms+. WTH?

So i'm revisiting my router's MTU settings. Hopefully reducing the ridiculous lag and disconnections.

I performed the PING TEST:
ping google.com -f -l 1492

I dropped this by 10 each time until I found the sweet spot. For me it is 1472. Add 28 for frame header space and we have 1500. However, my router defaults to 1500, so I will go with 1492 and see what happens. I did this change on Windows and my router.

Windows: HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
Create Decimal DWORD "MTU" and set to determined value

References:
http://support.microsoft.com/kb/314825
http://www.dslreports.com/faq/5793
http://www.dslreports.com/faq/695

For those interested, I also did this to my network 2 weeks prior to this. The link below is from mmo-champion's guide contest, from one of the contestants: 
http://www.mmo-champion.com/threads/818615-Multi-Core-Cpu-Architecture-and-WoW-Lag-and-Graphical-tweaks...Guide
http://www.speedguide.net/downloads.php