Tuesday, April 21, 2009

sort table randomly

The following sample shows you on how to sort sql table randomly:

select * from(

select top 20 firstname, lastname from [user]

) as result order by NEWID()

identity_insert

The following example shows you on how to insert explicit value into the identity column of a table:

set identity_insert [MyModuleElement] on

Insert into MyModuleElement

(intID, strName, strDescription, intControllerID)

Values

(48, 'test name', 'desc', 46)

set identity_insert [MyModuleElement] off

Get the current page name in javascript

<script type="text/javascript">

var sPath = window.location.pathname;

var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);

alert(sPage);

</script>

Reference:

Get the current page name

Javascript refresh page

If you want to use javascript to refresh the page, you can use
  • location.reload(); => post request, same as click the refresh button on the browser
  • window.location=window.location; => get request
  • self.location=self.location; => get request
If you want to use javascript to redirect to another page, you can use
  • location.replace('webform1.aspx'); => get request, does not create a history entry so browser back button disabled if no history before
  • location.href='webform1.aspx'; => get request, create a history entry so browser back button works
  • window.location='webform1.aspx'; => get request, create a history entry so browser back button works

IE buttons

  • Back button => get request
  • Forward button => post request
  • Refresh button => post request

If you get an IE error saying 'To display the webpage again, Internet Explorer needs to resend the information you've previously submitted', you can use window.location=window.location; to refresh the page instead of location.reload();

Sample code:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="PostMethod_Test._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Literal ID="litJavascript" runat="server"></asp:Literal>

<div>

Post:

<div>

<asp:TextBox ID="txt" runat="server"></asp:TextBox>

Post Method:<asp:Button ID="btnPost" runat="server" Text="PostBack" />

</div>

</div>

<hr />

<div>

Redirect:

<div>

Get Method:<asp:Button ID="btnRedirect" runat="server" Text="ResponseRedirect" />

</div>

<div>

Get Method:<a href="javascript:location.replace('webform1.aspx');">JS Location Replace</a>

(does not create a history entry so browser back button disabled if no history before)

</div>

<div>

Get Method:<a href="javascript:location.href='webform1.aspx';">JS Location Href</a>

(create a history entry so browser back button works)

</div>

<div>

Get Method:<a href="javascript:window.location='webform1.aspx';">JS Window Location</a>

(create a history entry so browser back button works)

</div>

<div>

Get Method: IE Back button

</div>

<div>

Post Method: IE Forward button

</div>

</div>

<hr />

<div>

Refresh:

<div>

Get/Post Method:<a href="javascript:location.reload();">JS Location Reload</a> (if

there is any control in the form then after the form was submitted for the first

time, if you click this, it will be a post method coming with the IE alert)

</div>

<div>

Get Method:<a href="javascript:window.location=window.location;">JS Window Location</a>

(does not create a history entry) (if there is any control in the form then after

the form was submitted for the first time, if you click this, it will still be a

get method which means the form will not be submitted again)

</div>

<div>

Get Method:<a href="javascript:self.location=self.location;">JS Self Location</a>

(Same as above)

</div>

<div>

Get/Post Method: IE Refresh button - same as location.reload()

</div>

</div>

<hr />

<div>

Open New Window:

<div>

No Method:<a href="javascript:var a = window.open('webform1.aspx');">JS Window Open</a>

(just open)

</div>

<div>

Post Method for parent page:<asp:Button ID="btnOpen" Text="Open Window" runat="server" />

</div>

</div>

</div>

</form>

</body>

</html>


Partial Public Class _Default

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Private Sub btnRedirect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRedirect.Click

Response.Redirect("Default.aspx")

End Sub

Private Sub btnPost_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPost.Click

End Sub

Private Sub btnOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOpen.Click

Dim mstrMessage As New StringBuilder("")

mstrMessage.AppendFormat("<script type=""text/javascript"" >{0}", ControlChars.CrLf)

mstrMessage.AppendFormat(" window.open(""webform1.aspx"");{0}", ControlChars.CrLf)

mstrMessage.AppendFormat(" </script>")

litJavascript.Text = mstrMessage.ToString

End Sub

End Class

Friday, April 17, 2009

Reasons to Use Proxy Server

Increased internet security since:

  • Users are authenticated
  • Client requests are filtered
  • All content, inbound and outbound, is validated
  • All access is logged
  • All of the internal network details are hidden
  • Internet access performance is improved

Sunday, April 12, 2009

Create a screenshot image of a web page

I use HtmlCapture to capture a screenshot of a web page:

Imports HtmlCapture

Module Module1

Sub Main()

CreatePreviewImage()

End Sub

Private Sub CreatePreviewImage()

Dim theURL As String = "http://www.google.com.au/"

Dim snap As New SnapShooter

Dim snapResult As HtmlCaptureResult

snap.SetRegInfo("username", "licencekey")

snap.SetDelayTime(6000)

snap.SetTimeOut(15000)

snap.SetMinBrowserSize(SnapDimensions.BrowserWidth, SnapDimensions.BrowserHeight)

snap.SetClipRect(0, 0, SnapDimensions.ClipWidth, SnapDimensions.ClipHeight)

snap.SetThumbSize(SnapDimensions.ThumbWidth, SnapDimensions.ThumbHeight, True)

snap.SetJpegQuality(CByte(SnapDimensions.JpegQuality))

snapResult = snap.SnapUrl(theURL)

If snapResult = HtmlCaptureResult.HCR_SUCCESS Then

' success, save the image as a JPEG

snap.SaveImage("screenshot.jpg")

Else

' timeout, so throw error

Dim ex As New Exception("Timeout on capturing.")

Throw ex

End If

End Sub

Public Enum SnapDimensions As Integer

ThumbWidth = 200

ThumbHeight = 150

BrowserWidth = 1024

BrowserHeight = 768

ClipWidth = 1024

ClipHeight = 768

JpegQuality = 70

End Enum

End Module


Reference:

HtmlCapture Support

Clear form values

The following code will clear values entered in the form, currently only works with drop down list and textbox, you can expand it to cater for more controls.

Private Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click

ClearValues(Me.FindControl("MyControlID"))

End Sub

Private Sub ClearValues(ByVal container As Control)

For Each ctl As Control In container.Controls

Dim textBox As TextBox = TryCast(ctl, TextBox)

If textBox IsNot Nothing Then

If textBox.Text.Trim().Length <> 0 Then

textBox.Text = ""

End If

End If

If TypeOf ctl Is UI.WebControls.DropDownList Then

Dim ddl As UI.WebControls.DropDownList = DirectCast(ctl, UI.WebControls.DropDownList)

Dim li As ListItem = ddl.Items.FindByText("(none)")

If li IsNot Nothing Then

ddl.SelectedValue = li.Value

End If

li = ddl.Items.FindByText("Select")

If li IsNot Nothing Then

ddl.SelectedValue = li.Value

End If

End If

If ctl.Controls.Count > 0 Then

ClearValues(ctl)

End If

Next

End Sub

Save a CSV File in Browser

Private Sub lbCSVTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbCSVTemplate.Click

If File.Exists(Server.MapPath("~/CSVUploaded/template.csv")) Then

Response.ContentType = "text/csv"

'Some browsers open the file directly in browser, so this will cause a file "Save as" dialogue to appear.

Response.AppendHeader("Content-Disposition", "attachment; filename=template.csv")

Response.TransmitFile(Server.MapPath("~/CSVUploaded/template.csv"))

Response.End()

Else

lblMsg.Text = MessagesDAL.Instance.Get_MessageByID(Messages.MessageCodes.CSVTemplateNotAvailable)

lblMsg.ForeColor = Drawing.Color.Red

End If

End Sub

Reference:
Downloading a File with a Save As Dialog in ASP.NET

Friday, April 10, 2009

robocopy

  • robocopy, or "Robust File Copy", is a command-line directory replication command.
  • It was available as part of the Windows Resource Kit, and introduced as a standard feature of Windows Vista and Windows Server 2008.
  • Robocopy is notable for capabilities above and beyond the built-in Windows copy and xcopy commands.
  • You can script the commands and save them as .cmd files to deploy asp.net files to staging site or live site.

Command Examples:

  • Copy test.dll from bin folder under folder1 to bin folder under folder2, if test.dll has already existed in folder2, then it will be overwritten. It will not delete any files in folder2 which do not extist in folder1.
    • robocopy C:\folder1\bin C:\folder2\bin test.dll
  • Copy content from test to test, including subfolders, excludes folders named .svn, excludes files with .vb extension. If test folder does not exist in folder2, it will create one for you.
    • robocopy C:\folder1\test C:\folder2\test /S /XD .svn /XF *.vb
  • Create test folder only
    • robocopy C:\folder1\test C:\folder2\test /xf *.*

Reference:

robocopy

Disable Table Constraints

The following code will:

  • Disable/Enable All Table Constraints
  • E.g. if you have an user table and an UserLog table, UserLog have a foreign key which reference the UserID in the user table.
  • Now you can disable the foreign key Constraint on the UserLog table and insert a userid which does not exist in the user table into the UserLog table. After that you can enable the constraint.


CREATE PROCEDURE [dbo].[procDisableEnableAllTableConstraints]

@TblName VARCHAR(128),

@IsCheck BIT = 1

AS

DECLARE @SQLState VARCHAR(500)

IF @IsCheck = 0

BEGIN

SET @SQLState = 'ALTER TABLE [' + @TblName + '] NOCHECK CONSTRAINT ALL'

END

ELSE

BEGIN

SET @SQLState = 'ALTER TABLE [' + @TblName + '] CHECK CONSTRAINT ALL'

END

EXEC (@SQLState)


Public Shared Sub DisableEnableAllTableConstraints(ByVal tableName As String, ByVal isCheck As Boolean)

Dim dbCon As New SqlConnection(clsConfig.BaseConnectionString)

dbCon.Open()

Dim cmd As New SqlCommand("[procDisableEnableAllTableConstraints]", dbCon)

cmd.CommandType = CommandType.StoredProcedure

cmd.Parameters.AddWithValue("@TblName", tableName)

cmd.Parameters.AddWithValue("@IsCheck", IIf(isCheck, 1, 0))

Try

cmd.ExecuteNonQuery()

Catch ex As Exception

Throw (ex)

Finally

dbCon.Close()

End Try

End Sub


Reference:

Stored Procedure to Disable/Reenable All Constraints on a Given Table

Wednesday, April 8, 2009

Get Client IP address

Public Shared Function GetClientIPAddress() As String

Dim strIpAddress As String

Try

strIpAddress = HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR")

If strIpAddress = "" Then

strIpAddress = HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")

End If

Catch

strIpAddress = ""

End Try

Return strIpAddress

End Function


Sunday, April 5, 2009

Custom Validator

In the following example:
  • Required field validator for drop down list
  • Validate if any of the txtPostcode, txtSuburb, ddlCountry is filled in, then txtAddress is required.
  • ValidateEmptyText property is important for the validator to work

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="CustomValidator._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

<script language="javascript" type="text/javascript">

function cv_Validate(source, args)

{

var txtPostcode = document.getElementById("<%=txtPostcode.ClientID %>").value;

var txtSuburb = document.getElementById("<%=txtSuburb.ClientID %>").value;

var ddlCountry = document.getElementById("<%=ddlCountry.ClientID %>");

//alert(ddlCountry.selectedIndex);

if (txtPostcode.length > 0 txtSuburb.length > 0 ddlCountry.selectedIndex > 0)

{

If (args.Value.length <= 0)

{

args.IsValid = false;

}

else

{

args.IsValid = true;

}

}

else

{

args.IsValid = true;

}

}

function ValidateDropDown(source, arguments) {

var ddlCountry = document.getElementById("<%=ddlCountry.ClientID %>");

if (null != ddlCountry) {

var iValue = new Number(ddlCountry[ddlCountry.selectedIndex].value);

arguments.IsValid = (iValue > 0);

}

else {

arguments.IsValid = false;

}

}

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox ID="txtAddress" runat="server" Width="290px" CssClass="clsNormal"></asp:TextBox>

<asp:CustomValidator ID="CustomValidator4" ControlToValidate="txtAddress" Text="Address Required!"

ClientValidationFunction="cv_Validate" runat="server" Display="Dynamic" ValidateEmptyText="true" />

<asp:TextBox ID="txtSuburb" runat="server" Width="290px" CssClass="clsNormal"></asp:TextBox>

<asp:TextBox ID="txtPostcode" runat="server" Width="290px" CssClass="clsNormal"></asp:TextBox>

<asp:DropDownList ID="ddlCountry" runat="server" CssClass="clsNormal">

<asp:ListItem Text="Select" Value="0"></asp:ListItem>

<asp:ListItem Text="Aus" Value="1"></asp:ListItem>

<asp:ListItem Text="NZ" Value="2"></asp:ListItem>

</asp:DropDownList>

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateDropDown"

ErrorMessage="*" ForeColor="Red" Display="Dynamic"></asp:CustomValidator>

<asp:Button ID="btnSubmit" runat="server" Text="Submit" />

</div>

</form>

</body>

</html>


Reference:

Custom Validator On DropdownList Control

Saturday, April 4, 2009

JavaScript Events

onblur Event

  • The onblur event occurs when an object loses focus.
  • E.g. Make input uppercase.
  • Applies to: button, checkbox, fileUpload, layer, frame, password, radio, reset, submit, text, textarea, window

onkeydown Event

  • The onkeydown event occurs when a keyboard key is pressed.
  • E.g. user cannot type numbers into the input field
  • Applies to: document, image, link, textarea, text

onfocus Event

  • The onfocus event occurs when an object gets focus.
  • E.g. make the background color of the input fields change when they get focus.
  • Applies to: button, checkbox, fileUpload, layer, frame, password, radio, reset, select, submit, text, textarea, window

onkeypress Event

  • The onkeydown event occurs when a keyboard key is pressed or held down.
  • E.g. user cannot type numbers into the input field
  • Applies to: document, image, link, textarea, text

ondblclick Event

  • The ondblclick event occurs when an object gets double-clicked.
  • E.g. Copy field A's text to field B when a button gets double-clicked.
  • Applies to: button, document, link

onmouseover Event

  • The onmouseover event occurs when the mouse pointer moves over a specified object.
  • E.g. display an alert box when the user moves the mouse pointer over an image.
  • Applies to: layer, link, image

onmouseout Event

  • The onmouseout event occurs when the mouse pointer moves away from a specified object.
  • E.g. display an alert box when the user moves the mouse pointer away from an image.
  • Applies to: layer, link, image

onmousedown Event

  • The onmousedown event occurs when a mouse button is clicked.
  • E.g. an alert box is displayed when clicking on an image.
  • Applies to: button, document, link, image

onmouseup Event

  • The onmouseup event occurs when a mouse button is released.
  • E.g. an alert box is displayed when the mouse button is released after clicking an image.
  • Applies to: button, document, link, image

Reference:

JavaScript Event Reference

Friday, April 3, 2009

Print web page as PDF in VB.NET

I use ABCpdf .NET to print web page as pdf:

  • Add reference ABCpdf.dll
  • Render web page in pdf in landscape or portrait format
  • Write pdf to browser or save to disk
  • Save HTML as pdf or save the whole web page as pdf by given URL


<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="PrintToPDF._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Button ID="btnWriteToBrowserByHTML" runat="server" Text="Write To Browser By HTML"/>

<asp:Button ID="btnWriteToDiskByHTML" runat="server" Text="Write To Disk By HTML"/>

<asp:Button ID="btnWriteToBrowserByURL" runat="server" Text="Write To Browser By URL"/>

<asp:Button ID="btnWriteToDiskByURL" runat="server" Text="Write To Disk By URL"/>

</div>

</form>

</body>

</html>



Imports WebSupergoo.ABCpdf6

Imports System.Text

Imports System.IO

Partial Public Class _Default

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Private Function GenerateQuoteInHTML() As String

Dim sb As StringBuilder = New StringBuilder

Dim sw As StringWriter = New StringWriter(sb)

Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)

Dim litTop As New Literal

Dim litTopText As New StringBuilder()

'the width on div makes the table readable in landscape format

litTopText.AppendLine("<div style='width:1300px'><b>Title</b><br /><br />")

litTop.Text = litTopText.ToString()

Dim litBottom As New Literal

Dim litBottomText As New StringBuilder()

litBottomText.AppendFormat("</div>")

litBottom.Text = litBottomText.ToString()

litTop.RenderControl(hw)

litBottom.RenderControl(hw)

Return sb.ToString

End Function

Private Sub GeneratePDF(ByVal source As String, ByVal exportType As ExportType, ByVal sourceType As SourceType)

'set properties

Dim theDoc As New Doc

theDoc.HtmlOptions.PageCacheEnabled = False

theDoc.HtmlOptions.BrowserWidth = 0

theDoc.HtmlOptions.ImageQuality = 101

theDoc.MediaBox.Width = 1000

theDoc.Rect.Width = 1000

Dim theID As Integer

If sourceType = PrintToPDF.SourceType.HTML Then

'Renders a web page specified as HTML.

theID = theDoc.AddImageHtml(source)

ElseIf sourceType = PrintToPDF.SourceType.URL Then

'Renders a web page specified by URL.

theID = theDoc.AddImageUrl(source)

End If

'paging

'http://www.websupergoo.com/helppdf5/default.html?page=source%2F4-examples%2F08-landscape.htm

Do While True

theDoc.FrameRect()

If (theDoc.Chainable(theID) = False) Then

Exit Do

End If

theDoc.Page = theDoc.AddPage()

theID = theDoc.AddImageToChain(theID)

Loop

theDoc.HtmlOptions.LinkPages()

For x As Integer = 1 To theDoc.PageCount

theDoc.PageNumber = x

theDoc.Flatten()

Next

If exportType = PrintToPDF.ExportType.Browser Then

'write to browser

Dim theData As Byte() = theDoc.GetData()

Response.Expires = -1000

Response.ContentType = "application/pdf"

Response.AddHeader("content-length", theData.Length.ToString())

Dim timestamp As String = String.Format("{0}_{1}_{2}_{3}_{4}_{5}", Date.Now.Year.ToString, Date.Now.Month.ToString, Date.Now.Day.ToString, Date.Now.Hour.ToString, Date.Now.Minute.ToString, Date.Now.Second.ToString)

Response.AddHeader("content-disposition", "attachment; filename=MyPDF" + timestamp + ".PDF")

Response.BinaryWrite(theData)

theDoc.Clear()

ElseIf exportType = PrintToPDF.ExportType.Disk Then

'write to disk

Dim file As String = Path.Combine(Server.MapPath("CSVUploaded"), "test.pdf")

theDoc.Save(file)

End If

End Sub

Private Sub btnWriteToBrowserByHTML_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnWriteToBrowserByHTML.Click

Dim strHTML As String = GenerateQuoteInHTML()

GeneratePDF(strHTML, ExportType.Browser, SourceType.HTML)

End Sub

Private Sub btnWriteToBrowserByURL_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnWriteToBrowserByURL.Click

GeneratePDF("http://www.google.com.au", ExportType.Browser, SourceType.URL)

End Sub

Private Sub btnWriteToDiskByHTML_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnWriteToDiskByHTML.Click

Dim strHTML As String = GenerateQuoteInHTML()

GeneratePDF(strHTML, ExportType.Disk, SourceType.HTML)

End Sub

Private Sub btnWriteToDiskByURL_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnWriteToDiskByURL.Click

GeneratePDF("http://www.google.com.au", ExportType.Disk, SourceType.URL)

End Sub

End Class

Enum SourceType

URL

HTML

End Enum

Enum ExportType

Browser

Disk

End Enum


Reference:

ABCpdf PDF Component for ASP & VB