Sunday, November 2, 2008

ASP.net Custom Validation

ASP.net validation control , such as RequiredFieldValidator , RangeValidator and CompareValidator , is very useful.

But , there will be a day that we need to write a javascript function and used it as CustomValidation.

This is an example of CustomValidation that validate the value entered in a textbox.

The script will need 2 parameters , which will be supplied by CustomValidator control



function CustomValidation(ValidateResult,ObjectToValidate) {
if (ObjectToValidate.Value >= 1 && ObjectToValidate.Value <= 10) {
ObjectToValidate.IsValid = true;
}
else {
ValidateResult.innerText = "Please enter value in range of 1-10 only";
ObjectToValidate.IsValid = false;
}
}



Add a CustomValidator , point ControlToValidate to a textbox and set ClientValidationFunction as "CustomValidation"

Wednesday, September 24, 2008

ParamArray as a Parameter

Usually , we have to declare a (x) number of parameter for a method. But Mr Sascha has found a way to use ParamArray as a parameter , so that the method can accept any number of paramaters.

In this example , we'll call a sub , provided with few parameters

AddSilaPilih(ddlPaymentType, ddlDocLayer, ddlDocType)



Public Sub AddSilaPilih(ByVal ParamArray ddlObj() As DropDownList)
dim newItem As New ListItem
newItem.Value = 0
newItem.Text = "--Options--"
For i As Integer = 0 To ddlObj.GetLength(0) - 1
ddlObj(i).Items.Add(newItem)
ddlObj(i).SelectedIndex = ddlObj(i).Items.Count - 1
Next
End Sub



Credit to Mr Sascha

Thursday, September 11, 2008

Passing parameter to dynamic loaded user control

After a short discussion with Sascha

Create a class (clsHandle) that inherits System.Web.UI.UserControl

Create any variable or property
Public KeyProcessID As Integer

Create an EventHandler (so userControl can handle the event)
Public Event onShowDetail As EventHandler

Create a sub which will be called by user control's parent

Public Sub ShowDetail(ByVal intKeyProcessID As Integer)
KeyProcessID = intKeyProcessID
RaiseEvent onShowDetail(Me, EventArgs.Empty) 'Raise event
End Sub


In the page that will load the user control

ucLoad = Page.LoadControl("user control's path")
pnlUC.Controls.Add(ucLoad)
CType(ucLoad, clsHandle).ShowDetail(9)


In the User Control

Inherits clsHandle

Protected Sub Page_onShowDetail(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.onShowDetail
MsgBox(Me.KeyProcessID)
End Sub

Wednesday, August 27, 2008

Windows - XP on SATA , Compaq Presario V3000

AFAIK , XP SP1 , XP SP2 doesnt have driver to support SATA and Compaq V3000 is pre-installed with Vista. And there a lots of people that still using XP such as me. Two family members bought Compaq Presario V3000 running on Vista , but they want to use XP instead.

I've been asked for help twice for this problem. And i've notice that , there also many guys out there having the same problem. Here , i'll try to help you guys using the way i've done.

1.Copy all your's XP Home / Pro installation files and folder into local drive.

2.Google and download SATA driver for XP

3.Download and install nLite

4.Use nLite to slipstream your XP installation
4.1 Browse your XP installation folder (which you've already copied to local drive)
4.2 Browse for SATA XP's driver you have downloaded
4.3 Follow the instruction

5.Use any CD burning tool to burn slipstreamed XP installation onto a blank CD

6.Restart and boot your notebook using the new XP cd

7.Install XP , done

Problems with Sound and Wireless device
But then , we'll might have problems with sound and wireless device. Even though we've installed drivers for both device , it'll still failed to functioning. This is because , we have to install UAA's driver 1st (Microsoft UAA Bus Driver for High Definition Audio) before installing sound and wireless driver. Then you can start using your Compaq

Sunday, August 24, 2008

Windows - Share LAN connection through Wireless Network

Situation : 2 people with 2 notebooks , both want to use internet connection , but theres only 1 ethernet port and 0 router.

Solution : 1 notebook must connected to the LAN and share it through wireless.

Example :
2 notebooks , one is labeled as nb-A, another one is nb-B
Steps :

nb-A

1. Plug in the RJ45 cable

2. Open Control Panel -> Network Connections -> Right Click on Wireless Network Connection , Properties

3. Click the Wireless Networks tab , checked the Use Windows to configure my wireless network settings , Preferred networks , click Add



4. On Association tab , enter your Network name (SSID)
4.1 Network authentication : Open
4.2 Data Encryption : WEP
4.3 Network key : must be 5 or 13 character
4.4 Checked the This is a computer-to-computer(ad-hoc) network;wireless access point are not used. This is very important , if you dont use this , you wireless network will not available


5. Right click on Local Area Connection, Properties , click Advanced tab

6. Checked Allow other network users to connect through this computer's internet connection
6.1 Select Wireless network connection from Home networking connection drop down



nb-B

1. Open Wireless network connection , click View wireless networks , choose nb-A's wireless network


2. Double click or click Connect , enter password if required

Saturday, August 23, 2008

.net ASP.net JavaScript Multiple Upload

After doing some googling and based on our current project's requirement , this is how we'll handle mutiple upload

By using JavaScript , we'll dynamically create "input type='File'" object , and during postback , retrieve all the files using Request.Files

HTML

< div >
< a href="javascript:addUpload();" >Upload< /a >
< table id="tblContainerUpload" >
< /table >
< /div >
< br / >
< asp:Button ID="cmdSubmit" runat="server" Text="Submit" / >


JavaScript

function addUpload()
{
/* We have to change encoding type manually , so that we retrieve files using Request.Files */
if (document.forms[0].encoding != 'multipart/form-data') {
document.forms[0].encoding = 'multipart/form-data';
}
var tblContainer = document.getElementById('tblContainerUpload');
var lastRow = tblContainer.rows.length;
var row = tblContainer.insertRow(lastRow);
var cell = row.insertCell(0);
var lblFile = document.createElement('span');
var FileUpload = document.createElement('input');
var btnDelete = document.createElement('input');

/*
If you want to set a Css Class name for this column
cellRight.className ="ClassName";
*/

FileUpload.type = 'File';

FileUpload.name = 'FileUpload' + lastRow;

FileUpload.id = 'FileUpload' + lastRow;

FileUpload.style.width = '300px';

cell.appendChild(FileUpload);

/*
On FileUpload's onChange event :
Hide the FileUpload
Show the label that display FileName
Call addUpload() so that , new FileUpload will be shown
*/

FileUpload.onchange = function() { lblFile.innerHTML = FileUpload.value;FileUpload.style.display='none';btnDelete.style.display = "inline";addUpload(); };

lblFile.name = 'lblFile' + lastRow;

lblFile.id = 'lblFile' + lastRow;

lblFile.style.width = 0;

cell.appendChild(lblFile);

btnDelete.type = 'Button';

btnDelete.name = 'btnDelete' + lastRow;

btnDelete.id = 'btnDelete' + lastRow;

btnDelete.value ="Delete";

btnDelete.style.display = "none";

cell.appendChild(btnDelete);

btnDelete.onclick = function() { removeUpload(lastRow,FileUpload.id); };
}


function removeUpload(RowNum,C_ID) {
var tblContainer = document.getElementById('tblContainerUpload');
var FileUpload = document.getElementById(C_ID);

FileUpload.parentNode.removeChild(FileUpload);

/* Failed to delete row , so i just hide it */
tblContainer.rows[RowNum].style.display = 'none';
}



VB.net

Protected Sub cmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
Dim strMsg As String = ""
For intFile As Integer = 0 To Request.Files.Count - 2
If Request.Files(intFile).FileName <> "" Then

Dim strLongFilePath As String = Request.Files(intFile).FileName.Trim.Replace(" ", "")
Dim intFileNameLength As Integer = InStr(1, StrReverse(strLongFilePath), "\")
Dim strFileName As String = Mid(strLongFilePath, (Len(strLongFilePath) - intFileNameLength) + 2)
Dim intFileSize As Decimal = Request.Files(intFile).ContentLength / (1024 * 1024)


strMsg &= "File #" & intFile & vbCrLf
strMsg &= "Filename :" & strFileName & vbCrLf
strMsg &= "Location :" & strLongFilePath & vbCrLf
strMsg &= "Size :" & System.Decimal.Round(intFileSize, 2) & " MB" & vbCrLf & vbCrLf
'Use this to save uploaded file to server directory
'Request.Files(intFile).SaveAs(Directory & File Name)

End If
'Msgbox is used to show uploaded file's information for demo purpose only
Next
MsgBox(strMsg, MsgBoxStyle.Information, "Uploading...")
End Sub



Oracle - Start / Stop services manually

As suggested by Fiza , i'll shared the script here

For both script , it didnt just start or stop the services , but also change the StartupType for each Oracle services. Please remove returnCode = objService.Change( , , , , "Manual") or returnCode = objService.Change( , , , , "Automatic") if you dont need this.

Stop the services (Save as StopServices.vbs)

strComputer = "."
intKira = 0
intFail = 0

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

strService = "Oracle"

Set colListOfServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE Name LIKE '%" & strService & "%'")
For Each objService in colListOfServices

If objService.StartMode = "Auto" Then

returnCode = objService.Change( , , , , "Manual")

returnCode = objService.StopService()

If returnCode <> 0 Then
intFail = intFail +1
else
intKira = intKira +1
End If

End If

Next

if intKira > 0 then
msgbox "Stop Succeded : " & intKira & vbcrlf & "Failed : " & intFail
else
msgbox "Failed"
end if



Start the services {Save as StartServices.vbs)

strComputer = "."
intKira = 0
intFail = 0

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

strService = "Oracle"

Set colListOfServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE Name LIKE '%" & strService & "%'")
For Each objService in colListOfServices

If objService.StartMode = "Manual" Then

returnCode = objService.Change( , , , , "Automatic")

returnCode = objService.StartService()

If returnCode <> 0 Then
intFail = intFail +1
else
intKira = intKira +1
End If

End If

Next

if intKira > 0 then
msgbox "Start Succeded : " & intKira & vbcrlf & "Failed: " & intFail
else
msgbox "Failed"
end if

.net DataTable's Tricks

Copy Structure from another DataTable

Keyword : Clone
Usage : DataTable2 = DataTable1.Clone
Note : This method will only copies structure , schema & constraint from another DataTable , but not data


Copy Structure + Data from another DataTable

Keyword : Copy
Usage : DataTable2 = DataTable1.Copy
Note : Copies both structure and data from another DataTable


Combining two DataTables

Keyword : Merge
Usage : DataTable1.Merge DataTable2
Note : Sometimes we have 2 DataTables with same structure but different data , so we can use this method to combine the data into one DataTable (Both DataTable MUST have same structure , schema & constraint)


Copy DataRow from DataTable into another DataTable

Keyword : ImportRow
Usage : DataTable2.ImportRow (DataTable1.Rows(IndexOfRow))

Keyword : ItemArray
Usage : DataTable2.Rows.Add Row.ItemArray
Note : This one maybe more useful compare to ImportRow , when we have to loop for each row in DataTable , copy it into another DataTable without knowing the row's index

.net Casting - CType , DirectCast , TryCast

There are 3 ways of casting in .net. Here i'll give some explanation for each of it.

CType

Can be said most commonly used among the three. In project which i'm currently involved , Ctype is oftenly used in casting an object from FindControl to specific type. Ctype is alse used to cast a session that handle a datatable.

Ctype requires 2 parameter , the object and also the type.

Code Example :

Dim sessionFromDT as new DataTable

sessionFromDT = Ctype(Session("myDT"),DataTable)


DirectCast

Using DirectCast , you can only convert a type to another type that has inheritance or implementation relationship. I can't really explain this , but from what i read, using directCast for a double to integer ,will throw an exception because there are no relationship. But we can cast System.Windows.Forms.Form to System.Windows.Forms.Control. We can see that , both of this type inherit from the FORMS. Benefit of using this compare to CType is better perfomance because it doesn't rely on Visual Basic routine.



TryCast

This one is quite interesting to me, because CType , DirectCast will throw an exception when it fail to convert type. But, by using TryCast , we will get NOTHING. So , why do you want to write codes for handle exception when TryCast can handle it for you? Ok, we got NOTHING, proceed to the next code. Yeah, thats cool. But theres a limitation here, you can only convert reference types, such as classes and interfaces and it have the same condition as DirectCast , from and to types that have relationship.

1st post

Hi

This my 3rd blog , which will only focused on programming or technical stuff. I'll start posting some code examples as soon as possible.