Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
DundasSoftwareisaprofessionaldeveloperofclasslibrariesandcomponentsforMicrosoftDevStudiodevelopers.Dundashasbeendevelopingsoftwareformajorcorporations,associations,andprivateorganizationssince1987.
Dundashasprovidedsoftwareandservicestodevelopersandorganizationsinmorethan50countriesthroughouttheworld.Ourcoretechnologycomponentshavebeenincludedineverytypeofsoftwareimaginable,includingretailandcorporateinternalprojects.Ourconsultingserviceshavealsoaidedincustomizingourcomponentsforthebanking,financial,insurance,medical,andpoliticalmarkets.
ThislongtermexposurehasprovenDundastobeareliablesoftwareprovider,andDundasisnowenablingdeveloperstoutilizetheirrobustsoftwareasActiveXcontrolsandCOMcomponents.
FormoreinformationonDundasSoftware'sproductsandservices,visitusatwww.dundas.com
Phone: (800)463-1492
(416)467-5100
Fax: (416)422-4801
Email: [email protected]
UltimateToolboxincludesmorethan200MFCclasses,addingvaluablefeaturesthatincludeGUIclasses,Frameworkclasses,Utilityclasses,MAPIclasses,OLEclasses,Imageclasses,Fileclassesandmore.
UltimateToolboxhasdrop-insimplicityandintegratesseamlesslywithMFC,therebybecomingapartoftheMFCframework.
CustomersconsistentlyreportthattheclassesinUltimateToolboxare"wellthoughtout,debugged,useful,andsavetimeandcoding".
Newclassesarereleasedeverytwoweeks,ensuringthatthetoolboxisalwaysuptodate.
Fullsourcecodeisincludedformorethan200classes,andanattractiveyearlysubscriptionplanisavailable.Thissubscriptionincludesaccesstothenewclassesreleasedeverytwoweeks,sourcecodeforthenewclassesandfulltechnicalsupport.
Formoreinformationvisitourwebsiteathttp://www.dundas.com/
COXMaskedEditOverview
Copyright©DundasSoftwareLtd.19971999,AllRightsReserved
ClassMembers|MaskCharacters
TheCOXMaskedEditcontrolextendstheMFCCEditcontroltoproviderestricteddatainputwithvisualcues,formatteddataoutput,overtypecapability,andavalidationframework.
YoucanuseCOXMaskedEditanywhereyouwoulduseaCEditclass.Ifnoinputmaskisset,itwillbehavelikeastandardCEdit.
Ifyoudefineaninputmask,eachcharacterpositionintheMaskedEditcontrolmapstoeitheraplaceholderofaspecifiedtypeoraliteralcharacter.(Literalcharacters,or'literals',cangivevisualcuesaboutthetypeofdatabeingused.Forexample,theparenthesessurroundingtheareacodeofatelephonenumberareliterals:(206)777-2222.)
Theinputmaskpreventsyoufromenteringinvalidcharactersintothecontrol.Ifyouattempttoenteracharacterthatconflictswiththeinputmask,thecontrolgeneratesaValidationErrorbeep.
Theinsertionpointautomaticallyskipsoverliteralsasyouenterdataormovetheinsertionpoint.
Whenyouinsertordeleteacharacter,allnonliteralcharacterstotherightoftheinsertionpointareshifted,asnecessary.Ifshiftingthesecharactersleadstoavalidationerror,theinsertionordeletionisprevented,andaValidationErrorbeepistriggered.
Forexample,supposetheMaskpropertyisdefinedas"?###",andthecurrentvalueoftheTextpropertyis"A12."Ifyouattempttoinserttheletter"B"totheleftoftheletter"A,"the"A"wouldshifttotheright.Sincethesecondvalueoftheinputmaskrequiresanumber,theletter"A"wouldcausethecontroltogenerateaValidationErrorbeep.
TheMaskedEditcontrolalsovalidatestheparametervalueoftheSetInputTextfunctiontheuserpassesatruntime.IfyouusetheSetInputTextfunctionsothatitconflictswiththeinputmask,thefunctionwillreturnanerrorcode.
Youmayselecttextinthesamewayasforastandardtextboxcontrol.Whenselectedtextisdeleted,thecontrolattemptstoshifttheremainingcharacterstotherightoftheselection.However,anyremainingcharacterthatmightcauseavalidationerrorduringthisshiftisdeleted,andnoValidationErrorbeepisgenerated.
Normally,whenaselectionintheMaskedEditcontroliscopiedontotheClipboard,theentireselection,includingliterals,istransferredontotheClipboard.YoucanusetheSetClipModefunctiontodefinethebehaviorfortransferringonlyuser-entereddataontotheClipboardornot-literalcharactersthatarepartoftheinputmaskarenotcopied.
UsingCOXMaskedEdit
YoucanattachaCOXMaskedEdittoanexistingeditcontrolbysubclassingthelatter.
ThisisremarkablysimpletodointheDevStudioIDEwhenworkingwithanMFCdialog.
Placeastandardeditcontrolonthedialogusingthedialogeditor.InvoketheClassWizardandselecttheMemberVariablespage.AddamembervariablefortheIDoftheeditcontrol,selectingaCEditcontrolasthetype.
Next,opentheheaderfileforthedialog.IncludeOXMaskedEdit.h.
IntheAFX_DATAsectionforthedialogyouwillseethedeclarationfortheeditcontrolasaCEdit.ChangethistoCOXMaskedEdit(oraclassderivedfromCOXMaskedEdit)andviola!
TypicallyyouwillcallSetMaskandSetPromptSymbolonthecontrolinOnInitDialogtosetupyourparticularmasketc.
Notethatyouwon'tneedtocallCreateinthisscenario.
Don'tforgettoincludetheOXMaskedEdit.cppfileinyourproject!
DependingontheorderofcompilationyoumayalsofindifhelpfultoincludeOXMaskedEdit.hinthedialogand/ormainapplication.cppfileofyourproject.
COXMaskedEdit
Copyright©DundasSoftwareLtd.19971999,AllRightsReserved
Overview|EditMaskCharacters
COXMaskedEdit Theconstructor.Canbecalledwithamask.
Create Createsthecontrol-muchlikeCEditcreate.
GetMask Retrievesthecurrentmask.
SetMask Setsthemask.
ShowMask Retrievesthedata-bothuserinputandliterals.
GetInputData Retrievesthedata-userinputonly.
SetInputData Allowsprogrammaticentryofuserdata.
GetPromptSymbol Retrievestheplaceholdercharacter.
SetPromptSymbol Setstheplaceholdercharacter.
EmptyData Clearsinputdata.Optionallyclearsthemask.
IsInputEmpty Determinesifdatahasbeenenteredbytheuser.
GetInsertMode Retrievestheovertypestate.
SetInsertMode Setstheovertypestate.
ValidationError Anoverridable,calledforerrors.
OnValidate Anoverridablemethodwhichallowsforvalidationwhenthecontrollosesfocus.
GetAutoTab Retrievesthestateoftheautotaboption.
SetAutoTab Setsthestateoftheautotaboption.
RPtoLP Convertstherealpositiontothelogicalposition.
LPtoRP Convertsthelogicalpositiontotherealposition.
COXMaskedEditMaskCharacters
ClassMembers|Overview
Thesearethecharactersyoucanusetosetthemask:
.(period) Decimalplaceholder.Theactualcharacterusedistheonespecifiedasthedecimalplaceholderinyourinternationalsettings.Thischaracteristreatedasaliteralformaskingpurposes.
,(comma) Thousandsseparator.Theactualcharacterusedistheonespecifiedasthethousandsseparatorinyourinternationalsettings.Thischaracteristreatedasaliteralformaskingpurposes.
:(colon) Timeseparator.Theactualcharacterusedistheonespecifiedasthetimeseparatorinyourinternationalsettings.Thischaracteristreatedasaliteralformaskingpurposes.
/(slash) Dateseparator.Theactualcharacterusedistheonespecifiedasthedateseparatorinyourinternationalsettings.Thischaracteristreatedasaliteralformaskingpurposes.
# Digitplaceholder(0-9).
A Alphanumericcharacterplaceholder(0-9anda-Z).
? Alphabeticplaceholder(a-Z).
> Alphabeticplaceholder,butforcesuppercasechars(A-Z).
< Alphabeticplaceholder,butforcesthemtolowercase(a-z).
& Characterplaceholder.ValidvaluesforthisplaceholderareANSIcharactersinthefollowingranges:32-126and128-255.
\ Literalescape.Usethistoplaceyourownliteralsinthemask-notethattwobackslashesmustbeusedinstringliteralstoaccomodateforthefactthatthisisalsotreatedasanescapecharacterforASNI/ISOstringformatting.
Asanexample,letslookatastringtomaskanIPaddress:
"IP\\Address:###\\.###\\.###\\.###"
Thiswillappearas:
IPAddress:___.___.___.___
Assumingthattheplaceholderor'prompt'symbolhas
beensettotheunderscore.
Notethatweneededtousetheescapecharactertoenableboththe'A'inAddressandtheperiodstoshowasliterals.
Todisplaythestring'http://'wewouldhavetousetheescapecharforthecolonandslashes:
"http\\:\\/\\/"
Todisplayabackslashasaliteral,weneedtoescapetheescape,asin"c:\\\\AAAAAAAA\\.AAA"
Seealso:COXMaskedEdit::SetMask|COXMaskedEdit::GetMask|COXMaskedEdit::COXMaskedEdit|COXMaskedEdit::SetPromptSymbol
COXMaskedEdit::COXMaskedEdit
ClassMembers|Overview
COXMaskedEdit(LPCTSTRpszMask=_T(""))
Parameters
pszMask Amaskcanbespecifiedatconstructiontime.
Remarks
Constructstheobject.
COXMaskedEdit::Create
ClassMembers|Overview
BOOLCreate(DWORDdwStyle,constRECT&rect,CWnd*pParentWnd,UINTnID)
Parameters
dwStyle Editcontrolstyles.
rect Editcontrolsizeandposition.
pParentWnd Editcontrolparentwindow.
nID EditcontrolID.
ReturnValue
Trueonsuccess.
Remarks
SameasCEdit::Createexceptthatitsetsthemaskaftercreationandshowsitasthetextofthecontrol(themaskmayhavebeensetbySetMaskortheconstructor).
Seealso:SetMask|COXMaskedEdit
COXMaskedEdit::EmptyData
ClassMembers|Overview
voidEmptyData(BOOLbOnlyInput=FALSE)
Parameters
bOnlyInput SettoTRUEtoonlyclearthedata.
Remarks
Clearsthecontentsofthemaskededit.DependingonthevalueofbOnlyInput,thisfunctionclearsalldata(mask+input)oronlyinputdata.
COXMaskedEdit::GetAutoTab
ClassMembers|Overview
BOOLGetAutoTab()const
ReturnValue
TRUEifAutoTabmodeisset,otherwiseFALSE.
Remarks
IfAutoTabmodeissetthenwhenthelastallowedsymbolistypedthefocusgoestothenextcontrolwithaWS_TABSTOPstyle.AutoTabmodeisnotsetbydefault.
Seealso:SetAutoTab
COXMaskedEdit::GetInputData
ClassMembers|Overview
CStringGetInputData()const
Returns
ACStringwhichstoresthestringthatwasentered(excludestheliterals).
Remarks
ToretrievethecontentsofthecontrolincludingliteralscallShowMask.YoucanalsocalltheCWndmethodGetWindowTexttoretrievetheactualcontentsofthecontrol,includingpromptsymbols.
Seealso:GetMask
COXMaskedEdit::GetInsertMode
ClassMembers|Overview
BOOLGetInsertMode()const
ReturnValue
TRUEifinsertmodeenabled,otherwiseFALSE.
Remarks
ThestandardCEditcontroldoesnotsupportover-typing.COXMaskedEditsupportsanovertypemode,andGetInsertModeletsthecodercheckifthismodeisset.
Overtypewillonlytakeeffectifaninputmaskisset.
Notethatinternallythecontrolwilltoggletheinsertmodeinresponsetotheinsertkey,andwillreverttoovertypeifthereisnoroomtoinsertcharacters.
SeeAlso:SetInsertMode
COXMaskedEdit::GetMask
ClassMembers|Overview
CStringGetMask()const
ReturnValue
Astringrepresentingthecurrentmask.
Seealso:SetMask|GetInputData|ShowMask|COXMaskedEdit|COXMaskedEditMaskCharacters
COXMaskedEdit::GetPromptSymbol
ClassMembers|Overview
TCHARGetPromptSymbol()
ReturnValue
Thecurrentpromptsymbol.
Remarks
Thepromptsymbolisshownoccupyingthespaceavailableforuserinput.Forexample,atelephonenumbermasksuchas(###)\###\-#####mighttypicallyusetheunderscorecharacterasthepromptcharacter,resultinginadisplayof(___)___-____inthecontrol.
Thedefaultpromptcharacteristhespace.
COXMaskedEdit::IsInputEmpty
ClassMembers|Overview
BOOLIsInputEmpty()
ReturnValue
TRUEifthecontrolonlyhasmaskandpromptsymbols,FALSEotherwise.
Remarks
Retrievestheflagthatspecifieswhetherthecontrolispopulatedwithsometextotherthanmaskandpromptsymbols.
Seealso:GetInputData|ShowMask
COXMaskedEdit::LPtoRP
ClassMembers|Overview
intLPtoRP(intnLogicalPos)const
Parameters
nLogicalPos Logicalpositionintheeditcontrol(onlytakesintoaccountnon-literalcharacters).
ReturnValue
Thecorrespondingrealposition(takingintoaccountallsymbolsincludingliterals)orone(1)ifnLogicalPosisnotavalidlogicalposition.
Remarks
Convertsthelogicalpositionwithinthemaskededitcontroltothecorrespondingrealone.
AllCOXMaskedEditfunctionsthattakeacursorpositionasanargumentinterpretitasarealpositionwithinthecontrol(takingintoaccountallsymbolsincludingliterals).Butsometimeswewanttosetthecursoratapositionbeforeorafteraparticularnon-literalsymbol.Thisiswherethismethodcomesinhandy.
Seealso:RPtoLP
COXMaskedEdit::OnValidate
ClassMembers|Overview
virtualBOOLOnValidate()
ReturnValue
TRUEifthecurrenttextpassesvalidation,otherwiseFALSE.
Remarks
Thisvirtualfunctiongetscalledwhenthecontrollosesfocus,unlesstheOMMEN_VALIDATEnotificationhandleroftheparentdecidesotherwise(seebelow).UseinaCOXMaskedEditderivedclasstoperformuservalidation.ThedefaultimplementationreturnsTRUE.
IfthismethodreturnsFALSE,thevirtualmethodValidationErrorwillbecalled.ThedefaultbehaviorofCOXMaskedEdit::ValidationErroristosimplysoundamessagebeep.
Thereisanotherwaytoprovidedatavalidationthatcanbeusedirregardlessofthecontrolbeingusedasabaseclass.
WhenthecontrollosesfocusitwillsendaWM_NOTIFYnotificationtoitsparentpassingtheIDofthecontrolinwParamandapointertoaMENMHDRstructureinlParam.Thehdr.codememberofthestructurewillcontainOXMEN_VALIDATE.
TherearetwoBOOLmembersoftheMENMHDRstructureyoucanmodifytoreturninformationonwhatactiontotake:
MENMHDR.bVaild Specifieswhetherdataisvalid.
MENMHDR.bDefaultValidation SpecifieswhethertocallOnValidate.
Seealso:ValidationError
COXMaskedEdit::RPtoLP
ClassMembers|Overview
intRPtoLP(intnRealPos)const
Parameters
nRealPos Therealpositionintheeditcontrol(takesintoaccountallsymbolsincludingliterals).
ReturnValue
Correspondinglogicalposition(takingintoaccountonlynonliterals),or-1ifthecharacterattherealpositionspecifiedcorrespondstoaliteral.
Remarks
Convertsarealposition(characterlocation)withinthemaskededitcontroltoacorrespondinglogicalone.
SeeAlso:LPtoRP
COXMaskedEdit::SetAutoTab
ClassMembers|Overview
voidSetAutoTab(BOOLbAutoTab)
Parameters
bAutoTab TRUEwillsetthecontrolinAutoTabmode,FALSEwillsetthecontrolinNormalmode.
Remarks
ChangestheAutoTabmode.IftheAutoTabmodeissetthenwhenthelastallowedsymbolistypedthefocusgoestothenextcontrolwithaWS_TABSTOPstyle.AutoTabmodeisturnedoffbydefault.
SeeAlso:GetAutoTab
COXMaskedEdit::SetInputData
ClassMembers|Overview
BOOLSetInputData(LPCTSTRpszInputData,intnBeginPos=0,BOOLbAllowPrompt=TRUE)
Parameters
pszInputData Eachcharacterisenteredintothecontrolasiftheusertypeditin.
nBeginPos StartingpositionforinsertingoroverwritingtheInsertsymbolsinthemask.
bAllowPrompt Determineswhetherornotthepromptsymbolisavalidinputcharacter.
ReturnValue
TRUEifsomedatawasinserted,otherwiseFALSE.
Remarks
UsethistoprogrammaticallyinsertpszInputDataintothemaskededitcontrol.ThemaskisappliedtotheInputData.
COXMaskedEdit::SetInsertMode
ClassMembers|Overview
voidSetInsertMode(BOOLbInsertMode)
Parameters
bInsertMode IfTRUEcharactersareinserted;ifFALSEcharacterswilloverwriteexistingcharacters.
Remarks
ThestandardCEditcontroldoesnotsupportover-typing,butCOXMaskedEditdoessupportanovertypemode.SetInsertModeletsthecodertogglethismodeonoroff,butthecontrolcanalsochangemodebasedonuserinput.
Internally(inOnKeyDown)thecontrolwillrespondtotheinsertkeytotoggleinsertmodeusingthisfunction.
Ifthecontrolisininsertmodeandthereisnoroomtoinsertcharactersthecontrolwillreverttoover-typemodeautomatically.
Notethatovertypemodeisrelatedtotheinputmask-ifnomaskissetthecontrolwillactlikeanormalCEditandSetInsertModewillhavenoeffect.
SeeAlso:GetInsertMode
COXMaskedEdit::SetMask
ClassMembers|Overview
voidSetMask(LPCTSTRpszMask=_T(""))
Parameters
pszMask Astringcontainingthenewmask.
Remarks
Changingthemaskmayinvolvelossofuserdatafromthemaskededitcontrol.
SeeAlso:GetMask|COXMaskedEditMaskCharacters
COXMaskedEdit::SetPromptSymbol
ClassMembers|Overview
voidSetPromptSymbol(TCHARchNewPromptSymbol)
Parameters
chNewPromptSymbol Setsanewpromptsymbol.ThenewsymbolcannotbeNULL,acarriagereturnoralinefeed.
Remarks
Thepromptsymbolisshownoccupyingthespaceavailableforuserinput.Forexample,atelephonenumbermasksuchas(###)\###\-#####mighttypicallyusetheunderscorecharacterasthepromptsymbol,resultinginadisplayof(___)___-____inthecontrol.
Thedefaultsymbolisaspace.
SeeAlso:GetPromptSymbol
COXMaskedEdit::ShowMask
ClassMembers|Overview
CStringShowMask()const
ReturnValue
Thefullyformatedmaskwithallinputdata.ToretrieveonlythecharactersenteredbytheusercalltheGetInputDatamethod.
Seealso:COXMaskedEditMaskCharacters
COXMaskedEdit::ValidationError
ClassMembers|Overview
virtualvoidValidationError()
Remarks
Thisisanoverridablefunctionthatiscalledwhendatafailsvalidationoranincorrectkeyispressed.
SeeAlso:OnValidate
COX3DTabViewContainerOverview
Copyright©DundasSoftwareLtd.1997-1999,AllRightsReserved
ClassReference
DependenciesandRelatedFiles
Exampleofa3DTabViewContainer:
Formostapplicationsit'snotenoughtouseonlyonewindowtoprovideoutput.Therearedifferentsolutionsforthisproblemlikesplittersordockingwindowsbuttheyusuallyhaveonecommoninconvenience:allofthewindowsareshownatthesametime,takinguppreciousscreenspacewhilebeingunused.
AgoodexampleofhowthisproblemcanberesolvedcanbefoundintheMicrosoftVisualStudioIDEwithits"Output"window(with"Build","Debug","FindinFiles..."panes)and"ResultList"window(with"Search","Lookup","SeeAlso"and"History"panes).WecallthesewindowsTabViews.
TabViewsareagoodalternativeforsplitterwindowswhenyouneedtohavemorethanoneviewperdocument.TabViewscanbeusedwithinadockingwindowandcanalsoserveasacontainerforassociatedwindows(pages)thatareimplementedasdialogbars.
COX3DTabViewContainerintroducesanewimplementationofTabViews.Theparadigmremainsthesamebutwe'vechangedthewayassociatedwindows(pages)arerepresentedinthecontainer.WeuseastandardTabcontrolanddisplayatabbuttonforeachpage,andwhenauserclicksonabuttonthecorrespondingpageisactivatedanddisplayed.TabbuttonscanbepositionedatanysideofthecontainerwindowbyapplyingcorrespondingTabcontrolstyles(refertotheCreate()functionfordetails).
COX3DTabViewContainerisderivedfromthestandardCTabCtrlandimplementsallofthefunctionalityneededtosupporttabviews.
HereisalistofstepsthatshouldbetakeninordertodeployTabViewsinyourapplication:
FirstCaseScenario:COX3DTabViewContainerwillbeusedasacontainerfordocumentview(s).
1)EmbedaCOX3DTabViewContainermembervariableintheparentframe(mainframewindowforSDIapplication,MDIChildwindowforMDIapplication).
2)Overridetheparentframe'sCFrameWnd::OnCreateClient()memberfunction.
3)FromwithintheoverriddenOnCreateClient,calltheCreate()memberfunctionoftheCOX3DTabViewContainer.Youwillhavetospecifytheparentwindowandyoucanoptionallyspecifytheinitialrectangle,windowstylesandthewindowID.ThisiswhereyoucanspecifytheTabcontrolstylesthatdefinethewaytabbuttonsarepositionedanddisplayed.
4)ToassignimagestoTabViewpagesyouwillhavetocreateandload
animagelistandassociateitwithaCOX3DTabViewContainerobjectusingtheCTabCtrl::SetImageList()function.
5)AftertheCOX3DTabViewContainerwindowissuccessfullycreatedyoucanpopulateitwithwindowobjectsusingtheAddPage()orInsertPage()functions.Ifyouareinsertingaviewobjectyouhavetospecifytheruntimeclassandcontextinformationinordertokeepthedocument/viewarchitectureinplace.IfyouareaddingawindowobjectthatisnotadocumentviewthenyouwillhavetocreateitbeforeaddingittotheCOX3DTabViewContainerwindow.IntheAddPage()orInsertPage()functionsyoucanspecifythetextthatwillbeusedasthepagetitleinthecorrespondingtabbutton.Youcanalsospecifytheindexoftheimageinthetabcontrol'simagelistthatshouldbedisplayedinthetabbutton.
Forexample:
BOOLCChildFrame::OnCreateClient(LPCREATESTRUCTlpcs,CCreateContext*pContext)
{//TODO:Addyourspecializedcodehereand/orcallthebaseclass
UNREFERENCED_PARAMETER(lpcs);
if(!m_TabViewContainer.Create(this))
returnFALSE;
VERIFY(m_ilTabView.Create(IDB_IL_TABVIEWS,16,0,RGB(255,0,255)));
m_TabViewContainer.SetImageList(&m_ilTabView);
if(!m_TabViewContainer.AddPage(pContext->m_pNewViewClass,pContext,_T("PrimaryView"),0))
{returnFALSE;
}
if(!m_TabViewContainer.AddPage(RUNTIME_CLASS(CMyView2),pContext,_T("View2"),1))
{returnFALSE;
}
m_TabViewContainer.SetActivePageIndex(0);
returnTRUE;
}
SecondCaseScenario:TheCOX3DTabViewContainerwillbeusedasacontainerforwindowswithinacontrolbar.
1)CreateyourownCControlBar-derivedclass(youcanuseourCOXSizeControlBarasaparentclassifyouneedsizabledockingwindows).Let'scallitCMyControlBar.
2)EmbedaCOX3DTabViewContainermembervariableinthisclass.
3)OverridetheCMyControlBar::OnCreate()memberfunction.
4)FromwithintheoverriddenOnCreate(),calltheCreatememberfunctionoftheCOX3DTabViewContainerobject.Youhavetospecifytheparentwindowandyoucanoptionallyspecifytheinitialrectangle,windowstylesandwindowID.ThisiswhereyoucanspecifyTabcontrolstylesthatdefinesthewaytabbuttonsarepositionedanddisplayed.
5)IfyouplantoassignimagestoTabViewpagesthenyouhavetocreateandloadanimagelistandassociateitwiththeCOX3DTabViewContainerusingtheCTabCtrl::SetImageList()function.
6)AftertheCOX3DTabViewContainerwindowissuccessfullycreatedyoucanpopulateitwithwindowobjectsusingtheAddPage()orInsertPage()functions.NotethatyouhavetocreatethewindowobjectbeforeaddingittoCOX3DTabViewContainer.IntheAddPageorInsertPagefunctionsyoucanspecifythetextthatwillbeusedasthepagetitleinatabbutton.Youcanalsospecifytheindexofanimagein
thetabcontrolimagelistthatshouldbedisplayedinthetabbutton.
7)OverridetheCMyControlBar::OnSize()memberfunctionandresizetheCOX3DTabViewContainerobject.
Forexample:
intCMyControlBar::OnCreate(LPCREATESTRUCTlpCreateStruct)
{
if(COXSizeControlBar::OnCreate(lpCreateStruct)==-1)
return-1;
if(!m_TabViewContainer.Create(this))
return-1;
VERIFY(m_ilTabView.Create(IDB_IL_TABVIEWS,16,0,RGB(255,0,255)));
m_TabViewContainer.SetImageList(&m_ilTabView);
//editcontrol
if(!edit.Create(WS_CHILD|ES_MULTILINE|ES_AUTOHSCROLL|ES_AUTOVSCROLL|WS_HSCROLL|WS_VSCROLL,CRect(0,0,0,0),&m_TabViewContainer,1))
{
return-1;
}
m_TabViewContainer.AddPage(&edit,_T("Edit"),0);
//listbox
if(!listBox.Create(WS_CHILD|WS_HSCROLL|WS_VSCROLL,CRect(0,0,0,0),&m_TabViewContainer,2))
{
return-1;
}
m_TabViewContainer.AddPage(&listBox,_T("ListBox"),1);
//listcontrol
if(!listCtrl.Create(WS_CHILD|LVS_REPORT,CRect(0,0,0,0),&m_TabViewContainer,3))
{
return-1;
}
m_TabViewContainer.AddPage(&listCtrl,_T("List"),2);
//treecontrol
if(!treeCtrl.Create(WS_CHILD|TVS_HASLINES|TVS_LINESATROOT|TVS_HASBUTTONS,CRect(0,0,0,0),&m_TabViewContainer,4))
{
return-1;
}
m_TabViewContainer.AddPage(&treeCtrl,_T("Tree"),3);
m_TabViewContainer.SetActivePageIndex(0);
return0;
}
NotethatanychildwindowcanbeusedasaCOX3DTabViewContainerpage.
ThestepstobetakeninordertoimplementCOX3DTabViewContainerinaCControlBarderivedwindowshouldbeusedingeneralcasesaswell.ACControlBarderivedwindowwasusedabovesinceitisalikelychoicefortheparentwindow.
ThefollowingfunctionshavebeenprovidedforthosewhoneedtodynamicallychangethecontentsofaCOX3DTabViewContainerobject:
InordertoremoveanypageatruntimecalltheDeletePage()function.
Toset/retrievethepagetitlethatisdisplayedinthecorrespondingtabbuttonuseGetPageTitle()andSetPageTitle().
Toset/retrievetheactivepageindexcallGetActivePageIndex()andSetActivepageIndex().
Formoreinformationexaminethesamplefoundin:<INSTALLDIR>\3DTabVws\Samples\Gui\3DTabView\TabViews.dsw
COX3DTabViewContainerClassMembers
Copyright©DundasSoftwareLtd.19971999,AllRightsReserved
Overview
COX3DTabViewContainer Constructstheobject.
Create Createsthe3DTabViewcontainer.
AddPage Addsanewpagetothe3DTabViewContainer.
InsertPage Insertsanewpageintothe3DTabViewContainer.
DeletePage Deletesanexistingpagefromthe3DTabViewcontainer.
GetPage Retrievesapointertoapagewhichisspecifiedbyanindex.
GetPageTitle Retrievesthetitleofthespecifiedpage.
SetPageTitle Setsthetitleofthespecifiedpage.
GetPageImageIndex Retrievestheimageindexofthespecifiedpage.
SetPageImageIndex Setstheimageindexofthespecifiedpage.
GetPageCount Retrievesthenumberofpagesinthe3DTabViewcontainer.
FindPage Retrievesaflagindicatingwhetherornotthespecifiedwindowisapagebelongingtothe3DTabViewContainer.Ifitisthentheindexofthelocatedpageisprovided.
IsPage Retrievesaflagindicatingwhetherornotthespecifiedwindowisapagebelongingtothe3DTabViewContainer.
IsActivePage Retrievesaflagindicatingwhetherthe
specifiedwindowisthecurrentlyactivepageforthe3DTabViewContainer.
GetActivePageIndex Retrievestheindexofthecurrentlyactivepage.
GetActivePage Retrievesapointertothecurrentlyactivepage.
SetActivePage Setsthespecifiedpageastheactivepage.
SetActivePageIndex Setsthespecifiedpageastheactivepageviathepageindex.
SetOffsetExternal Setsthetabcontroloffsetfromtheparentwindowborders.
GetOffsetExternal Retrievesthetabcontroloffsetfromtheparentwindowborders.
SetOffsetInternal Setsthepagewindowoffsetfromthetabcontroldisplayrectangle.
GetOffsetInternal Retrievesthepagewindowoffsetfromthetabcontroldisplayrectangle.
AcceptDraggedObject Toggles"dragobjectover"supportforthetabcontrolonoroff.
IsAcceptingDraggedObject Retrievesaflagthatspecifieswhetherthe3DTabViewcontaineractivatesthecorrespondingpagewindowwhenanobjectisdraggedovertabcontrolitems.
RecalcPageRect Calculatestherectanglewhichspecifiesthecoordinatesoftheactivepagewindow.
GetPageRect Retrievestherectanglewhcihspecifiesthecoordinatesoftheactivepagewindow.
COX3DTabViewContainer::COX3DTabViewContainer
ClassMembers|Overview
COX3DTabViewContainer()
Remarks
Constructor.
COX3DTabViewContainer::AcceptDraggedObject
ClassMembers|Overview
voidAcceptDraggedObject(constBOOLbAccept=TRUE)
Parameters
bAccept AnyobjectdraggedovertabitemswillresultinthecorrespondingpagewindowbeingactivatedifsettoTRUE.
Remarks
Toggles'dragobjectover'supportforthetabcontrolonandoff.
COX3DTabViewContainer::AddPage
ClassMembers|Overview
BOOLAddPage(CRuntimeClass*pClass,CCreateContext*pContext,LPCTSTRlpszTitle=NULL,constintnImage=-1)
BOOLAddPage(CWnd*pWnd,LPCTSTRlpszTitle=NULL,constintnImage=-1)
Parameters
pClass Pointertotheruntimeclassinformationofthenewwindowtobeaddedasnewpage.
pContext Pointertocontextinformation(refertothedescriptionoftheCCreateContextclassintheMFCdocumentation).
pWnd Pointertoacreatedwindowtobeaddedasanewpage.
lpszTitle Textthatwillbeusedasthepagetitleforatabbutton.
nImage Indexoftheimageintheimagelistassociatedwiththecontainerthatwillbesettothecorrespondingbutton.
ReturnValue
TRUEifthenewpagewassuccessfullyadded,otherwiseFALSE.
Remarks
Addsanewpagetoa3DTabViewcontainer.UsethefirstversionofthefunctionifyouhavetoaddaCViewderivedclassthatwillbepartofthedocument/viewarchitectureofyourapplication.
COX3DTabViewContainer::Create
ClassMembers|Overview
virtualBOOLCreate(CWnd*pParentWnd,CRectrect=CRect(0,0,0,0),DWORDdwStyle=DEFAULT_TABCTRLSTYLE,UINTnID=AFX_IDW_PANE_FIRST)
Parameters
pParentWnd Pointertothewindowthatisthe3DTabViewContainer'sparent.
rect Windowrectangle.
dwStyle The3DTabViewcontainer'sstyle.BydefaultweuseDEFAULT_TABCTRLSTYLEwhichexpandsasTCS_MULTILINE|TCS_BOTTOM|TCS_HOTTRACK|TCS_SCROLLOPPOSITE|TCS_RIGHTJUSTIFY|TCS_FOCUSNEVER|WS_VISIBLE|WS_CHILD.
nID The3DTabViewContainer'sID.
ReturnValue
TRUEifthe3DTabViewContainerwassuccessfullycreated,otherwiseFALSE.
Remarks
Createsa3DTabViewContainer.
COX3DTabViewContainer::DeletePage
ClassMembers|Overview
virtualBOOLDeletePage(constCWnd*pWnd,constBOOLbDestroy=TRUE)
virtualBOOLDeletePage(constintnIndex,constBOOLbDestroy=TRUE)
Parameters
pWnd Pointertothepagetobedeleted.
nIndex Indexofthepagetobedeleted.
bDestroy Flagwhichspecifiesifthewindowhastobedestroyed.
ReturnValue
TRUEifthespecifiedpagewassuccessfullydeleted,otherwiseFALSE.
Remarks
Deletesanexistingpagefroma3DTabViewContainer.
COX3DTabViewContainerDependenciesandRelatedFiles
Copyright©DundasSoftwareLtd.1997-1999,AllRightsReserved
Overview
SOURCE OX3DTabView.cpp
INCLUDEOX3DTabView.h
SAMPLE <INSTALLDIR>\3DTabVws\Samples\Gui\3DTabView\TabViews.dsw
COX3DTabViewContainer::FindPage
ClassMembers|Overview
BOOLFindPage(constCWnd*pTestWnd,int&nIndex)const
BOOLFindPage(constHWNDhTestWnd,int&nIndex)const
Parameters
pTestWnd Pointertothewindowtobetestedasa3DTabViewContainer'spage.
hTestWnd Handleofthewindowtobetestedasa3DTabViewContainer'spage.
nIndex Referencevariable,storestheindexofthepageiffound.Thisindexiszero(0)based.
ReturnValue
TRUEifthespecifiedwindowisa3DTabViewcontainer'spage,otherwiseFALSE.
Remarks
Retrievesaflagwhichspecifieswhetherthespecifiedwindowisa3DTabViewContainer'spage.IfitisthentheindexofthelocatedpageisindicatedbynIndex.
COX3DTabViewContainer::GetActivePage
ClassMembers|Overview
CWnd*GetActivePage()const
ReturnValue
Pointertothecurrentlyactivepageofa3DTabViewContainer.
Remarks
Retrievesapointertothecurrentlyactivepageofa3DTabViewContainerobject.
Seealso:GetActivePageIndex
COX3DTabViewContainer::GetActivePageIndex
ClassMembers|Overview
intGetActivePageIndex()const
ReturnValue
Indexofa3DTabViewContainer'scurrentlyactivepage.
Remarks
Retrievestheindexofthecurrentlyactivepage.
Seealso:GetActivePage
COX3DTabViewContainer::GetOffsetExternal
ClassMembers|Overview
DWORDGetOffsetExternal()const
ReturnValue
Offsetinpointsfromtheparentwindowclientareawherethetabcontrolwillbedisplayed.
Remarks
Retrievesthetabcontroloffsetfromtheparentwindow'sborders.
Seealso:SetOffsetExternal
COX3DTabViewContainer::GetOffsetInternal
ClassMembers|Overview
DWORDGetOffsetInternal()const
ReturnValue
Offsetinpointsfromthedisplayareaofthetabcontrolandactivepagewindow.
Remarks
Retrievesthepagewindowoffsetfromthetabcontroldisplayrectangle.
Seealso:SetOffsetInternal
COX3DTabViewContainer::GetPage
ClassMembers|Overview
CWnd*GetPage(constintnIndex)const
Parameters
nIndex Zero-basedindexofthepagetoberetrieved.
ReturnValue
PointertothecorrespondingpagewindoworNULLifthespecifiedindexwasoutofrange.
Remarks
Retrievesapointertothespecifiedpage.
COX3DTabViewContainer::GetPageCount
ClassMembers|Overview
intGetPageCount()const
ReturnValue
Thenumberofpagesinthe3DTabViewcontainer.
Remarks
RetrievesthenumberofpagesintheCOX3DTabViewContainer.
COX3DTabViewContainer::GetPageImageIndex
ClassMembers|Overview
intGetPageImageIndex(constCWnd*pWnd)const
intGetPageImageIndex(constintnIndex)const
Parameters
pWnd Pointertothepagewhoseimageindexistoberetrieved.
nIndex Zero-basedindexofthepagewhoseimageindexistoberetrieved.
ReturnValue
Imageindexofthespecifiedpage.
Remarks
Retrievestheimageindexofthespecifiedpage.
COX3DTabViewContainer::GetPageRect
ClassMembers|Overview
CRectGetPageRect()const
ReturnValue
Therectanglethatspecifiesthecoordinatesoftheactivepagewindow.
Remarks
Retrievestherectanglewhichspecifiesthecoordinatesoftheactivepagewindow.
COX3DTabViewContainer::GetPageTitle
ClassMembers|Overview
CStringGetPageTitle(constCWnd*pWnd)const
CStringGetPageTitle(constintnIndex)const
Parameters
pWnd Pointertoapageforwhichthetitleistoberetrieved.
nIndex Zero-basedindexofthepageforwhichtheimageindexistoberetrieved.
ReturnValue
Titleofthecorrespondingpage.
Remarks
Retrievesthetitleofthespecifiedpage.
COX3DTabViewContainer::InsertPage
ClassMembers|Overview
virtualBOOLInsertPage(constintnIndex,CRuntimeClass*pClass,CCreateContext*pContext,LPCTSTRlpszTitle=NULL,constintnImage=1)
virtualBOOLInsertPage(constintnIndex,CWnd*pWnd,LPCTSTRlpszTitle=NULL,constintnImage=1)
Parameters
nIndex Zero-basedindexofthepagetobeadded.
pClass Pointertotheruntimeclassinformationofthenewwindowtobeadded.
pContext Pointertocontextinformation(refertothedescriptionoftheCCreateContextclassintheMFCdocumentation).
pWnd Pointertothecreatedwindowtobeinsertedasthenewpage.
lpszTitle Thetextthatwillbeusedasthepagetitleinatabbutton.
nImage Indexoftheimageintheimagelist(whichisassociatedwiththecontainer)thatwillbeusedforthecorrespondingbutton.
ReturnValue
TRUEifthenewpagewassuccessfullyinserted,otherwiseFALSE.
Remarks
Insertsanewpageintoa3DTabViewContainer.Usethefirstversionof
thefunctionifyouhavetoinsertaCViewderivedclasswhichispartofthedocument/viewarchitectureofyourapplication.
COX3DTabViewContainer::IsAcceptingDraggedObject
ClassMembers|Overview
BOOLIsAcceptingDraggedObject()const
ReturnValue
TRUEifthe3DTabViewContaineractivatesthecorrespondingpagewindowwhenanobjectisdraggedovertabcontrolitems,otherwiseFALSE.
Remarks
Retrievestheflagthatspecifieswhetherthe3DTabViewContaineractivatesthecorrespondingpagewindowwhenanobjectisdraggedovertabcontrolitems.
COX3DTabViewContainer::IsActivePage
ClassMembers|Overview
BOOLIsActivePage(constHWNDhTestWnd)const
BOOLIsActivePage(constCWnd*pTestWnd)const
Parameters
hTestWndHandleofthewindowtobetestedasthecurrentlyactive3DTabViewContainer'spage.
pTestWnd Pointertothewindowtobetestedasthecurrentlyactive3DTabViewContainer'spage.
ReturnValue
TRUEifthespecifiedwindowisthecurrentlyactive3DTabViewContainer'spage,otherwiseFALSE.
Remarks
Retrievesaflagwhichindicateswhetherornotthespecifiedwindowisthecurrentlyactive3DTabViewContainer'spage.
COX3DTabViewContainer::IsPage
ClassMembers|Overview
BOOLIsPage(constHWNDhTestWnd)const
BOOLIsPage(constCWnd*pTestWnd)const
Parameters
hTestWndHandleofthewindowtobetestedasthe3DTabViewContainer'spage.
pTestWnd Pointertothewindowtobetestedasthe3DTabViewContainer'spage.
ReturnValue
TRUEifthespecifiedwindowisapageofthe3DTabViewContainer,otherwiseFALSE.
Remarks
Retrievesaflagwhichindicateswhetherthespecifiedwindowisapageofthe3DTabViewContainer.
COX3DTabView::RecalcPageRect
ClassMembers|Overview
voidRecalcPageRect()
Remarks
Calculatestherectanglewhcihspecifiesthecoordinatesoftheactivepagewindow.
COX3DTabViewContainer::SetActivePage
ClassMembers|Overview
BOOLSetActivePage(constCWnd*pWnd)
Parameters
pWnd Pointertothepagetobesetasactive.
ReturnValue
TRUEifthespecifiedpagewassuccessfullysetastheactivepage.
Remarks
Setsthespecifiedpageasbeingactive.
COX3DTabViewContainer::SetActivePageIndex
ClassMembers|Overview
virtualBOOLSetActivePageIndex(constintnIndex)
Parameters
nIndex Indexofthepagetobesetastheactivepage.
ReturnValue
TRUEifapagewiththespecifiedindexwassuccessfullysetastheactivepage.
Remarks
Setsapagewiththespecifiedindexastheactivepage.
COX3DTabViewContainer::SetOffsetExternal
ClassMembers|Overview
voidSetOffsetExternal(constDWORDdwOffset)
Parameters
dwOffset Theoffsetinpointsfromtheparentwindowclientareawherethetabcontrolwillbedisplayed.
Remarks
Setsthetabcontroloffsetfromtheparentwindowborders.
Seealso:GetOffsetExternal
COX3DTabViewContainer::SetOffsetInternal
ClassMembers|Overview
voidSetOffsetInternal(constDWORDdwOffset)
Parameters
dwOffset Theoffsetinpointsfromthedisplayareaofthetabcontrolandactivepagewindow.
Remarks
Setsthepagewindowoffsetfromthetabcontroldisplayrectangle.
Seealso:GetOffsetInternal
COX3DTabViewContainer::SetPageImageIndex
ClassMembers|Overview
BOOLSetPageImageIndex(constCWnd*pWnd,intnImage)
BOOLSetPageImageIndex(constintnIndex,intnImage)
Parameters
pWnd Pointertothepageforwhichtheimageistobeset.
nIndex Zero-basedindexofthepageforwhichtheimageistobeset.
nImage Indexofanimageintheimagelistthatwillbeusedasthepageimageinthecorrespondingtabbutton.
Remarks
Setstheimageindexofthespecifiedpage.
COX3DTabViewContainer::SetPageTitle
ClassMembers|Overview
BOOLSetPageTitle(constCWnd*pWnd,LPCTSTRlpszTitle)
BOOLSetPageTitle(constintnIndex,LPCTSTRlpszTitle)
Parameters
pWnd Pointertothepageforwhichthetitleistobeset.
nIndex Zero-basedindexofthepageforwhichthetitleistobeset.
lpszTitle Thetextthatwillbeusedasthepagetitleinthetabbutton.
Remarks
Setsthetitleofthespecifiedpage.
COXToolTipCtrlOverview
Copyright©DundasSoftwareLtd.1997-1999,AllRightsReserved
COXToolTipCtrlClassMembers
COXToolTipCtrlisanextendedtooltipcontrolthatallowsmultilinetooltips,plusextendedtooltiptext.Extendedtooltiptextisextratextthatisdisplayediftheuserclicksonthetooltipwindow.Ifthetooltipcontainsextendedtext(aswellasastandardtooltipstring)thentheinfowindowwillcontainasmallarrowthatpromptstheusertoclickonthewindow.Oncethewindowisclickedtheextendedtextisshown.Ifthewindowisclickedagainthenthewindowisreducedtodisplayingjustthestandardtext.
Themaximumwidthofthetooltipscanbespecified,andiftheinfotextistoolargetofitwithintheseboundsthenthetextwillbewrappedovermultiplelines.Thecontrolalsoallowsyoutospecifydifferenttextandbackgroundcolorsforthetooltips,andthedisplayfontcanalsobechanged.
ThisclassisadirectreplacementfortheCToolTipCtrlclass.ItincorporatestheentireAPIofthestandardCToolTipCtrlandintroducesnewfeaturesnotfoundinthestandardtooltip.
Thecontrolisusedjustlikeanyothertooltipcontrol.TouseitsimplycallCreate(...)andspecifytheparentwindowofthetool,thenaddtoolstothecontrolusingtheAddTool(...)memberfunctions.Forexample,toaddthetooltiptoaformviewordialog:
tooltip.Create(this);tooltip.AddTool(GetDlgItem(IDC_CONTROL),_T("Tooltiptext\rThisistheextended\ntooltiptext"));
whereID_CONTROListheIDofacontrol.
Tospecifyextendedtextforatooltipsimplyappenda'\r'afteryourtooltip
text,andthenappendtheextendedtooltipinfo.
Aswiththestandardtooltipcontrolyoucanspecifytheactualtextforthetoolatcreationtime(asshownabove),oryoucanspecifytheLPSTR_TEXTCALLBACKvalueandprovideaTTN_NEEDTEXThandlertoreturnthetextdynamicallyatruntime.
TohandletheTTN_NEEDTEXTmessageyouwillneedtoaddamessagehandlerintheparentwindowaswellasanentryinthemessagemap.Forexample,inavieworform:
BEGIN_MESSAGE_MAP(CMyDlg,CDialog)
...............
ON_NOTIFY_EX(TTN_NEEDTEXT,0,OnToolTipNotify)
END_MESSAGE_MAP()
BOOLCMyDlg::OnInitDialog()
{
CDialog::OnInitDialog();
tooltip.Create(this);
tooltip.AddTool(GetDlgItem(IDC_CONTROL),LPSTR_TEXTCALLBACK);
....
}
BOOLCMyDlg::OnToolTipNotify(UINTid,NMHDR*pNMHDR,LRESULT*pResult)
{
TOOLTIPTEXT*pTTT=(TOOLTIPTEXT*)pNMHDR;
UINTnID=pNMHDR->idFrom;
if(nID==IDC_CONTROL)//Fillinthetextbuffer
{
_tcscpy(pTTT->szText,_T("Tooltiptext\rExtendedtooltiptext"));
returnTRUE;
}
returnFALSE;
}
Alternativelyyoucansupplytextbyeithersupplyingastringresource:
pTTT->lpszText=MAKEINTRESOURCE(nID);pTTT->hinst=AfxGetResourceHandle();returnTRUE;
orbysupplyingapointertothetext:
pTTT->lpszText=_T("Tooltiptext\rExtendedtooltiptext");returnTRUE;
Newlinecharacters('\n')canbeembeddedanywherewithinthetextorextendedtexttoproduceamultilinetooltip.IfthewidthofthetooltipwindowisspecifiedusingSetMaxTipWidth()thenthetooltiptextwillbewrappedtothislength,andifnecessarywillbedisplayedonmorethanoneline.
TochangethefontofthetooltipssimplyusetheSetFont()memberfunction.
TheGetToolInfo/SetToolInfofunctionsandtheHitTestfunctionsareverysimilartotheCToolTipCtrlversionswiththeexceptionthattheyuseaOXTOOLINFOstructureinsteadofaTOOLINFOstructure.Thisstructure
isdefinedas
structOXTOOLINFO:publicTOOLINFO{#if(_WIN32_IE<0x0300)LPARAMlParam;//Applicationdefinedvaluethatisassociatedwiththetool#endifintnWidth;//Widthofbox,or0fordefaultCOLORREFclrTextColor;//textcolorCOLORREFclrBackColor;//backgroundcolor}
andisverysimilartothestandardTOOLINFO.ItisusedinthesamewayexceptthattheuFlagsmemberisnotused(yet).
TochangethecolorofanindividualtipusetheGetToolInfo/SetToolInfofunctions:
OXTOOLINFOToolInfo;
if(m_toolTip.GetToolInfo(ToolInfo,GetDlgItem(IDC_CONTROL)))
{
ToolInfo.clrBackColor=RGB(255,255,255);
ToolInfo.clrTextColor=RGB(0,0,255);
m_toolTip.SetToolInfo(&ToolInfo);
}
TheToolTipExsamplethatdemonstratesthefunctionalityoftheCOXToolTipCtrlclasscanbefoundin:<INSTALLDIR>\ToolTips\Samples\Gui\ToolTipEx\ToolTipEx.dsw.
COXToolTipCtrlClassMembers
Copyright©DundasSoftwareLtd.1997-1999,AllRightsReserved
Overview
COXToolTipCtrl Constructsandinitializestheobject.
GetToolInfo Retrievestheinformationthatatooltipcontrolmaintainsaboutatool.
SetToolInfo Setstheinformationthatatooltipmaintainsforatool.
GetMargin Retrievesthemarginsusedfordrawingthetextinthetooltip.
GetText Retrievesthetextthatatooltipcontrolmaintainsforatool.
SetDelayTime Setsthedelaytimesforthetooltipinmilliseconds.
GetDelayTime Retrievestheinitial,pop-up,andreshowdurationscurrentlysetforatooltipcontrol.
GetMaxTipWidth Retrievesthemaximumwidthofthetooltipwindow.
SetMaxTipWidth Setsthemaximumtooltipwindowwidth.
GetTipBkColor Retrievesthebackgroundcolor.
SetTipBkColor Setsthebackgroundcolourforalltoolsmaintainedbythiscontrol.
GetTipTextColor Retrievesthetextcolor.
SetTipTextColor Setsthetextcolorforalltoolsmaintainedbythiscontrol.
Activate Activates/deactivatesthetooltipcontrol.
GetToolCount
Retrievesacountofthetoolsregisteredwiththetooltipcontrol.
SetMargin Setsthetop,left,bottom,andrightmarginsforatooltipwindow.
Create Createsthetooltipwindow.
AddTool Registersatoolwiththetooltipcontrol.
DelTool Removesthespecifiedtool.
RelayEvent Passesamousemessagetoatooltipcontrolforprocessing.
HitTest Retrievesaflagwhichspecifiesifagivenpointisinthewindowstoolinfoboundingrectangle.
Pop Hidesthetooltip.
CalculateInfoBoxRect Advancedoverridable.Protectedvirtualfunction
thatcalculatestherectangle(inscreencoords)thatisbestsuitedtodisplayingthetooltipinfo.
GetBoundsRect Advancedoverridable.Protectedvirtualfunctionthatcalculatesthesmallestpossiblerectanglethatwillcontainthetext.
COXToolTipCtrl::Activate
Members|Overview
voidActivate(BOOLbActivate)
Parameters
bActivate Specifieswhetherthetooltipcontrolistobeactivatedordeactivated.
Remarks
Callthisfunctiontoactivateordeactivateatooltipcontrol.IfbActivateisTRUE,thecontrolisactivated.IfFALSE,itisdeactivated.Whenatooltipcontrolisactive,thetooltipinformationappearswhenthecursorisonatoolthatisregisteredwiththecontrol;whenitisinactive,thetooltipinformationdoesnotappear,evenwhenthecursorisoveraregisteredtool.
COXToolTipCtrl::AddTool
Members|Overview
BOOLAddTool(CWnd*pWnd,UINTnIDText,LPCRECTlpRectTool=NULL,UINTnIDTool=0)
BOOLAddTool(CWnd*pWnd,LPCTSTRszText,LPCRECTlpRectTool=NULL,UINTnIDTool=0)
Parameters
pWnd Pointertothewindowthatcontainsthetool.
nIDText IDofthestringresourcethatcontainsthetextorthetool.Ifthetextcontainsa'\r'character,thenalltextbeforethe\risthestandardtooltiptext,andalltextafterthe\rwillbedisplayedasextendedtextiftheuseclicksonthetooltip.
lpszText Pointertothetextforthetool.Ifthetextcontainsa'\r'character,thenalltextbeforethe\risthestandardtooltiptext,andalltextafterthe\rwillbedisplayedasextendedtextiftheuserclicksonthetooltip.IfthetextisLPSTR_TEXTCALLBACKthenthecontrolwillsendtheTTN_NEEDTEXTnotificationmessagetotheparentwindowtoretrievethetext.
lpRectTool PointertoaRECTstructurecontainingcoordinatesofthetool'sboundingrectangle,usingclientcoordinatesrelativetothewindowidentifiedbypWnd.
nIDTool IDofthetool.
ReturnValue
TRUEonsuccess,FALSEotherwise.
Remarks
Registersatoolwiththetooltipcontrol,sothattheinformationstoredinthetooltipisdisplayedwhenthecursorisoverthetool.
Seealso:GetToolCount|DelTool
COXToolTipCtrl::CalculateInfoBoxRect
Members|Overview
virtualCRectCalculateInfoBoxRect(CPoint&pt,COXToolTipInfo*pToolTip,CRect&rectTextBounds)const
Parameters
pt Thetopleftcorneroftheregion.
pToolTip Informationonthetooltip.
rectTextBounds Theminimumrectangleneededtocontainthetext.
ReturnValue
Arectanglecontainingtheboundsofthetooltip.
Remarks
Giventheboundingrectangleofsometext,thisfunctionreturnstherectangle(inscreencoordinates)thatisbestsuitedtodisplayingthetooltipinformation(usesthecurrentmouseposition).Youcanoverridethismethodinaderivedclasstocustomizethecalculationmethod.
COXToolTipCtrl::COXToolTipCtrl
Members|Overview
COXToolTipCtrl()
Remarks
Constructor.Createsaninstanceofthisclass.
COXToolTipCtrl::Create
Members|Overview
BOOLCreate(CWnd*pParentWnd)
Parameters
pParentWnd Apointertothetooltipcontrol'sparent.
ReturnValue
TRUEifsuccessfulk,otherwiseFALSE.
Remarks
Createsthetooltipwindowwhichinitiallyisnotvisible.
COXToolTipCtrl::DelTool
Members|Overview
voidDelTool(CWnd*pWnd,UINTnIDTool=0)
Parameters
pWnd Pointertothewindowthatcontainsthetool.
nIDTool IDofthetool.
Remarks
RemovesthetoolspecifiedbypWndandnIDToolfromthecollectionoftoolssupportedbyatooltipcontrol.
Seealso:AddTool
COXToolTipCtrl::GetBoundsRect
Members|Overview
virtualCRectGetBoundsRect(CStringstrText,intnWidth)const
Parameters
strText Thetexttobedisplayed(maybemultiline).
nWidth Thedesiredwidth.Ifthisiszero(0)thewidthwillbecalculated.
ReturnValue
TheboundingRECTforthetext(withthetopleftcornerat0,0).
Remarks
Returnsthesmallestpossiblerectanglethatwillcontainthetext(includingmargins).
Seealso:CalculateInfoBoxRect
COXToolTipCtrl::GetDelayTime
Members|Overview
intGetDelayTime(DWORDdwDuration)const
Parameters
dwDuration Flagthatspecifieswhichdurationvaluewillberetrieved.Itcanbeoneofthefollowing:
TTDT_AUTOPOP Thelengthoftimethetooltipwindowremainsvisibleifthepointerisstationarywithinatool'sboundingrectangle.
TTDT_INITIAL Thelengthoftimethepointermustremainstationarywithinatool'sboundingrectanglebeforethetooltipwindowappears.
ReturnValue
Thedelaytimesforthetooltipareinmilliseconds(mS).
Remarks
Retrievestheinitial,pop-up,andreshowdurationscurrentlysetforatooltipcontrol.
Seealso:SetDelayTime
COXToolTipCtrl::GetMargin
Members|Overview
voidGetMargin(LPRECTlprc)const
Parameters
lprc AddressofaRECTstructurethatwillstorethemargininformation.
Remarks
Retrievesthemarginsusedfordrawingthetextinthetooltip.Therectangledoesnotspecifyaboundingrect,butratherthetop,bottom,leftandrightdistances(inpixels)betweenthetextandtheedgeofthetooltipwindow.
Seealso:GetBoundsRect
COXToolTipCtrl::GetMaxTipWidth
Members|Overview
intGetMaxTipWidth()const
ReturnValue
Themaximumwidthforatooltipwindow,orzero(0)ifthiswidthiscalculatedautomatically.
Remarks
Retrievesthemaximumwidthofthetooltipwindow.
Seealso:SetMaxTipWidth
COXToolTipCtrl::GetText
Members|Overview
voidGetText(CString&str,CWnd*pWnd,UINTnIDTool=0)
Parameters
str ReferencetoaCStringobjectthatstoresthetoolstext.
pWnd Pointertothewindowthatcontainsthetool.
nIDTool IDofthetool.
Remarks
Retrievesthetextthatatooltipcontrolmaintainsforatool.IfpWndandnIDToolspecifyavalidtoolthathasbeenpreviouslyregistered,thenstrisfilledwiththetooltip'stext.
COXToolTipCtrl::GetTipBkColor
Members|Overview
COLORREFGetTipBkColor()const
ReturnValue
ACOLORREFvaluethatrepresentsthebackgroundcolorofthetooltipwindow.
Remarks
Retrievesthebackgroundcolorofthetooltipwindow.
Seealso:SetTipBkColor|SetTipTextColor
COXToolTipCtrl::GetTipTextColor
Members|Overview
COLORREFGetTipTextColor()const
ReturnValue
ACOLORREFvaluethatrepresentsthetextcolor.
Remarks
Retrievesthetextcolorofthetooltipwindow.
Seealso:SetTipTextColor|SetTipBkColor
COXToolTipCtrl::GetToolCount
Members|Overview
intGetToolCount()const
ReturnValue
Thenumberoftoolsregisteredwiththetooltipcontrol.
Remarks
Retrievesthenumberoftoolsregisteredwiththetooltipcontrol.
Seealso:AddTool|DelTool
COXToolTipCtrl::GetToolInfo
Members|Overview
BOOLGetToolInfo(OXTOOLINFO&ToolInfo,CWnd*pWnd,UINTnIDTool=0)
Parameters
ToolInfo ReferencetoanOXTOOLINFOobjectthatreceivesthetoolstext.
pWnd Pointertothewindowthatcontainsthetool.
nIDTool IDofthetool.
ReturnValue
TRUEifsuccessful,otherwiseFALSE.
Remarks
Callthisfunctiontoretrievetheinformationthatatooltipcontrolmaintainsaboutatool.IfthecontrolhasinformationonthetoolidentifiedbypWndandnIDToolthentheCOXToolTipInfostructureispopulatedwiththatinformation.
SeetheoverviewforadescriptionoftheOXTOOLINFOstructure.
Seealso:SetToolInfo
COXToolTipCtrl::HitTest
Members|Overview
BOOLHitTest(CWnd*pWnd,POINTpt,OXTOOLINFO*pToolInfo)const
Parameters
pWnd Pointertothewindowthatcontainsthetool.
pt PointertoaCPointobjectcontainingthecoordinatesofthepointtobetested.
pToolInfo PointertoaOXTOOLINFOstructurethatcontainsinformationaboutthetool.
ReturnValue
TRUEifthepointspecifiedbythehit-testinformationiswithinthetoolsboundingrectangle;otherwiseFALSE.
Remarks
ReturnsTRUEifthegivenptisinthewindowstoolinfoboundingrectangle(ptisinclientcoordinatesrelativetotheparentwindow).IfthisfunctionreturnsTRUEthestructurepointedtobypToolInfoispopulatedwithinformationaboutthecorrespondingtool.
SeetheoverviewforinformationontheOXTOOLINFOstructure.
COXToolTipCtrl::Pop
Members|Overview
voidPop()
Remarks
Hidesthetooltip.
COXToolTipCtrl::RelayEvent
Members|Overview
voidRelayEvent(MSG*pMsg)
Parameters
pMsg PointertoaMSGstructurethatcontainsthemessagetorelay.
Remarks
Callthisfunctiontopassamousemessagetoatooltipcontrolforprocessing.
COXToolTipCtrl::SetDelayTime
Members|Overview
voidSetDelayTime(DWORDdwDuration,intnTime)voidSetDelayTime(UINTnDelay)
Parameters
dwDuration Flagthatspecifieswhichdurationvaluewillbeset.Canbeoneofthefollowingvalues:
TTDT_AUTOPOP Thelengthoftimethetooltipwindowremainsvisibleifthepointerisstationarywithinatool'sboundingrectangle.
TTDT_INITIAL Thelengthoftimethepointermustremainstationarywithinatool'sboundingrectanglebeforethetooltipwindowappears.
nTime Specifiesthenewdelaytime,inmilliseconds(mS).
nDelay Specifiesthenewdelaytime,inmilliseconds(mS).
Remarks
Setsthedelaytimesforthetooltipinmilliseconds.
Seealso:GetDelayTime
COXToolTipCtrl::SetMargin
Members|Overview
voidSetMargin(LPRECTlprc)
Parameters
lprc AddressofaRECTstructurethatcontainsthemargininformationtobeset.ThemembersoftheRECTstructuredonotdefineaboundingrectangle,butratherthetop,bottom,leftandrightdistances(inpixels)betweenthetextandthetheedgeofthetooltipwindow.
Remarks
Setsthetop,left,bottom,andrightmarginsforatooltipwindow.Amarginisthedistance,inpixels,betweenthetooltipwindowborderandthetextcontainedwithinthetooltipwindow.
Seealso:GetMargin
COXToolTipCtrl::SetMaxTipWidth
Members|Overview
intSetMaxTipWidth(intnWidth)
Parameters
nWidth Themaximumwidthofatooltipwindow,orzero(0)ifthiswidthistobecalculatedautomatically.Themaximumtooltipwidthvaluedoesnotindicateatooltipwindow'sactualwidth.Rather,ifatooltipstringexceedsthemaximumwidth,thecontrolbreaksthetextintomultiplelines,usingspacestodeterminelinebreaks.Ifthetextcannotbesegmentedintomultiplelines,itwillbedisplayedonasingleline.Thelengthofthislinemayexceedthemaximumtooltipwidth.
ReturnValue
Thepreviousmaximumtooltipwindowwidth.
Remarks
Setsthemaximumtooltipwindowwidth.
Seealso:GetMaxTipWidth
COXToolTipCtrl::SetTipBkColor
Members|Overview
voidSetTipBkColor(COLORREFclr)
Parameters
clr Thenewbackgroundcolor,asaCOLORREFstructure.
Remarks
Setsthebackgroundcolorforalltoolsmaintainedbythiscontrol.IfthevalueisCLR_DEFAULTthenthedefaultsystemcolorisused.
Seealso:GetTipBkColor
COXToolTipCtrl::SetTipTextColor
Members|Overview
voidSetTipTextColor(COLORREFclr)
Parameters
clr Thenewtextcolor.
Remarks
Setsthetextcolorforalltoolsmaintainedbythiscontrol.IfthevalueisCLR_DEFAULTthenthedefaultsystemcolorisused.
COXToolTipCtrl::SetToolInfo
Members|Overview
voidSetToolInfo(OXTOOLINFO*pToolInfo)
Parameters
pToolInfo ApointertoanOXTOOLINFOstructurethatspecifiestheinformationtobeset.
Remarks
Appliestheinformationthatatooltipmaintainsforatool.
SeetheoverviewforadescriptionoftheOXTOOLINFOstructure.
TheultimatesetofInternet/IntranetproductsforC++,MFCandATLdevelopers.DundasTCP/IPproductsallowforsimpleEmailintegration,fullysecurereal-timedatastreaming,andmuch,muchmore!
NeedtoInternet-enableanapplication,butdon'thavethetimeornecessaryexperience?TheDundasTCP/IPclienteditionmaybejustwhatyouneed.ThisproductletsyouInternet-enableanapplicationwithincredibleease!Includesmanyclientsideprotocols,suchasEmail(SMTP,POP3,IMAP4),FTP,andWeb(HTTP).more
NeedtocreatescalableInternet/Intranetapplicationsfast?TheDundasTCP/IPEnterpriseEditionincludesallofthecomponentsnecessaryforcreatinghighlyscalableclientandserverapplications.more
NeedtosecureyourInternet/Intranetdata?TheDundasTCP/IPSecurityAdd-onprovidesindustrystandardSSL/TLSsecurityforapplicationsusingtheDundasTCP/IPClientorEnterpriseeditions.more
CUT_RASOverviewCopyright©DundasSoftwareLtd.1996-1999,AllRightsReserved
CUT_RASClassMembers
DependenciesandRelatedFiles
TheRASDialupclass(CUT_RAS)ispartoftheUltimateTCP/IPclientandenterpriseeditionsandprovideseasytousemodemdialingcapabilities.Thisclassallowsyoutocreateandmodifydial-upentries,dialandhangupconnectionsandmore.CUT_RASworkswithinMFC,ATLandstraightSDKprojects.
CUT_RASworkswiththemainsystemphonebook.
ToutilizeyourownerrorcodesyoucanuseUTExtErr.h.
SampleCode:
Thefollowingcodedemonstrateshowtosetupadialogboxinordertodialthefirstentryinasystemphonebook,andauserdefinedWM(windowmessage)iscreatedtoinformusofthedialupprogress.
NOTE:forthisdemotoworkyoumusthaveDialUpNetworkinginstalled.PleaserefertoCUT_RASDependenciesandRelatedFilesforalistingofdependencyfiles.
Torunthissamplecodefollowthestepsbelow:
1. Openanewwin32project.
2. Insertanewdialog(namedIDD_DIALOG1).
3. RenametheOKbuttonofthedialogtoIDC_DIAL.
4. AddaneditcontrolnamedIDC_EDIT1.
5. Addanewheaderfile"stdafx.h"thatcontainsthefollowingfourlinesofcode:
#ifndef__UT_RAS12345_STDAFX#define__UT_RAS12345_STDAFX#include<windows.h>#endif//__UT_RAS12345_STDAFX
6. Locateandaddut_RAS.h&ut_RAS.cpptotheproject.
7. Createanewc++sourcefile(letscallitmain.cpp).
8. Copyandpastthecodeshownbelow
9. Runtheprogram.
ForanMFCsamplepleaseseetheprojectincludedwiththeinstallprogramforthisclass.
#include"stdafx.h"//thestdafxfile
//TheheaderfileofCUT_RASclass
#include"ut_ras.h"
//resourceheaderforadialog(IDD_DIALOG1)whichcontainsacancelbutton(IDCANCEL),
//adialbuttonandareadonlyeditbox(IDC_EDIT1)
#include"resource.h"
//Userdefinedwindowmessagethatwillbesentbacktousbythe
//CUT_RASclasstoinformusofthedialupprogress
#defineWM_CUT_RAS_DIALSTATUSWM_USER+1
//DialogprocPrototype
BOOLCALLBACKDialupDlgProc(HWNDhwndDlg,UINTmessage,WPARAMwParam,LPARAMlParam);
//WindowMainfunction
intCALLBACKWinMain(HINSTANCEhInstance,HINSTANCE,LPSTR,int)
{
//createmodaldialogbox
DialogBox(hInstance,MAKEINTRESOURCE(IDD_DIALOG1),NULL,(DLGPROC)DialupDlgProc);
return0;
}
//Dialogproc
BOOLCALLBACKDialupDlgProc(HWNDhwndDlg,UINTmessage,WPARAMwParam,LPARAMlParam)
{
//astaticinstanceoftheCUT_RASobject
staticCUT_RASras;
//Poolthewindowmessages
switch(message){
caseWM_INITDIALOG:
{
//uponinitializingthisdialogletsinstructtheCUT_RASobjecttosendthisdialog
//ouruserdefinedmessagetoreportthedialupstatus.
ras.SetDialStatusCallback(hwndDlg,WM_CUT_RAS_DIALSTATUS);
return1;
}
//handleuserinputs
caseWM_COMMAND:
switch(LOWORD(wParam))
{
//userpressedthecancelbutton
caseIDCANCEL:
{
//abortanybendingdialattemptifany
ras.CancelDial();
//Hangupthecurrentconnection
ras.HangUp();
//Exitclosingthisdialog
EndDialog(hwndDlg,IDOK);
break;
}
//userpressedthedialbutton
caseIDC_DIAL:
{
//createaphoneentrynameplaceholder
LPRASENTRYNAMEren=newRASENTRYNAME[sizeof(RASENTRYNAME)+1];
//clearanydatainthenewallocatedmemory
memset(ren,0,sizeof(RASENTRYNAME));
//initializetheRASdllandenumeratetheavailableentries
ras.EnumEntries();
//getthefirstentry
ras.GetEntry(ren,0);
//dialthefirstentryinthephonebook
ras.Dial(ren->szEntryName);
//reclaimtheallocatedmemory
delete[]ren;
break;
}
}
break;
//ifthisincomingmessageisthesameastheonewespecifiedasthedialstatusnotification
//thengetthestringfromtheLowerwordofthemessageparameter
//anddisplayitinthestatuseditbox.
caseWM_CUT_RAS_DIALSTATUS:
{
SetDlgItemText(hwndDlg,IDC_EDIT1,(LPCSTR)(LPARAM)lParam);
return1;
}
//thewindowisclosing
caseWM_CLOSE:{
//abortanypendingdialattempts(ifanyexist)
ras.CancelDial();
//Hangupthecurrentconnection
ras.HangUp();
EndDialog(hwndDlg,IDOK);
break;
}
}
return0;
}
CUT_RASClassMembers
Copyright©DundasSoftwareLtd.1996-2000.AllRightsReserved
Overview
CUT_RAS Classconstructor.
~CUT_RAS Destructoroftheclass.
InitRAS LoadsintheRASDLLsdynamically.
OnError Callbackfunctionwhichisraisedwhenanerroroccurs.Youcanusethisfunctiontoprovideextendederrorhandlinganddebuggingcapabilities.
Dial Dialsagivenphonebookentry.
HangUp CallthisfunctiontohangupacurrentlyactiveRASconnection.
SetDialStatusCallback Setsthewindowwhichwillreceivemessagesduringdialing.
GetDialState Callthisfunctiontoretrievethecurrentstateofthedialupprocess.Ifthisisnotavailablethenthelastdialupstateisretrieved.
CancelDial Cancelsthecurrentdial-upprocess.
IsConnected Callthisfunctiontocheckthestateofthecurrentconnection.
EnumDevices EnumeratesalloftheavailableRASdialupdevices.
GetDeviceCount RetrievesthenumberofavailableRASdialupdevices.
GetDevice Callthisfunctiontoretrievedeviceinformation.PopulatesthesuppliedRASDEVINFOstructurewiththedeviceinformation.
EnumConnections
CallthisfunctiontoenumeratealloftherunningRASconnectionsandstoretheminaninternalarrayofRASCONNstructures.
GetConnectionCount RetrievesthecurrentnumberofRASconnections.
GetConnection FillsinthesuppliedRASCONNstructurewiththeconnectioninformationforthespecifiedrunningconnection.
EnumEntries Callthisfunctiontoenumerateallofthephonebookentrynamesforthemainphonebook(theCUT_RASclassonlysupportsthemainphonebook).
GetEntryCount Returnsthenumberofavailablephonebookentriesforthemainphonebook(theCUT_RASclassonlysupportsthemainphonebook).
GetEntry CallthisfunctiontofillinthegivenRASENTRYNAMEstructurewithaphonebookentry'sname.
GetEntryProperties Retrievesthepropertiesforagivenphonebook
entry.
SetEntryProperties Callthisfunctiontocreateormodifyaphonebookentry.
SetDialEntryParams Setsthedialingparametersforagivenphonebookentry.
GetDialEntryParams Retrievesthedialingparametersforagivenphonebookentry.
DoesEntryExist CallthisfunctiontoseeifthespecifiedphonebookentryexistsinthemainRASphonebook.
ValidateEntryName Checkstoseeifthespecifiedentrynameisavalidnameforanewphonebookentry.
ClearEntryPassword Callthisfunctiontoclearthepasswordfromagivenphonebookentry.
DeleteEntry Deletesanentryfromaphonebook.
RenameEntry Callthisfunctiontorenamethegivenphonebookentry.
GetEntryPhoneNumber Retrievesthephonenumberandareacodeforthegivenphonebookentryfromthemainphonebook.
GetEntryUserName Retrievesthemainphonebook'susernameforthegivenphonebookentry.
GetEntryPassword Retrievesthemainphonebook'spasswordforthespecifiedphonebookentry.
GetLastRASError RetrievestheerrorcodefromthelastRASfunctioncalled.
GetRASErrorString ReturnstheappropriateerrorstringcorrespondingtothepassedRASerrorcode.
CUT_RASDependenciesandRelatedFiles
Copyright©DundasSoftwareLtd.1996-2000,AllRightsReserved
Overview
SOURCE Ut_ras.cpp
INCLUDE Ut_err.h
Ut_ras.h
LIBRARIESRasApi32.dllORRnaph.dll(comeswithDialUpNetworking).
SAMPLE
<INSTALLDIR>\RasDial\Sample\Ras\TestApp.dsw
CUT_RAS::~CUT_RAS
Members|Overview
virtual~CUT_RAS()
Remarks
Destructorfunction.FreestheloadedRASDLLandreclaimsanylocallyallocatedmemory.
CUT_RAS::CUT_RAS
Members|Overview
CUT_RAS()
Remarks
Constructor.
CUT_RAS::CancelDial
Members|Overview
voidCancelDial()
Remarks
Cancelsthecurrentdial-upprocessthatwasinitiatedwithDial.CancelDialisusuallyusedinsideoftheDialcallbackmessagehandler.SeeSetDialStatusCallbackformoredetails.
OnceCancelDialiscalledtheDialfunctionwillcleanupafteritselfandreturnwithoutcompletingthedialoperation.
CUT_RAS::ClearEntryPassword
Members|Overview
intClearEntryPassword(LPCSTRszEntryName)
Parameters
szEntryName Phonebookentrytodeletethepasswordfrom.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Functioncallfailed(seeGetLastRASErrorformoredetails).
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
Callthisfunctiontoclearthepasswordfromagivenphonebookentry.ThiscanalsobeperformedbyusingtheSetDialEntryParamsfunction,butClearEntryPasswordencapsulatestheoperation.
Seealso:SetDialEntryParams
CUT_RAS::DeleteEntry
Members|Overview
intDeleteEntry(LPCSTRszEntryName)
Parameters
szEntryName Nameofthephonebookentrytodelete.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Operationfailed(seeGetLastRASErrorformoredetails).
UTE_RAS_LOAD_ERRORUnabletoloadtheRASDLLs.
Remarks
Callthisfunctiontodeleteanentryfromthemainphonebook.
CUT_RAS::Dial
Members|Overview
intDial(LPCSTRszEntry,LPCSTRszUserName=NULL,LPCSTRszPassword=NULL,LPCSTRszNumber=NULL)
Parameters
szEntry Thenameofthephone-bookentrytodial.
szUserName Astringcontainingtheuser'susername.Thisstringisusedtoauthenticatetheuser'saccesstotheremoteaccessserver.
szPassword Astringcontainingtheuser'spassword.Thepasswordisusedtoauthenticatetheuser'saccesstotheremoteaccessserver.
szNumber Astringcontaininganoverridingphonenumber.Anemptystring("")indicatesthatthephone-bookentry'sphonenumbershouldbeused.NOTE:IfszEntryis""thenszNumbercannotbeNULL.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Operationfailed.
UTE_RAS_DIALINIT_ERROR Erroroccurredwhenthedialingprocesswasinitiated(seeGetLastRASErrorformoredetails).
UTE_RAS_DIAL_ERROR Erroroccurredduringthedialingprocess.UsetheGetDialStatefunctiontoretrievemoredetailedinformation.
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
Dialsagivenphonebookentry.TheszUserName,szPasswordandszNumberparametersareoptionalandcanbeNULL.Tooverrideinformationlocatedinthedialupentryyouwouldthenspecifytheseparameters(thephonebookentryitselfwillnotbemodified).
UnderWin98andNTthisfunctioncandialwithoutaphonebookentrybyusingthegiveninformationandthefirstavailabledial-updevice.Althoughadialupconnectioncanbemadewithoutspecifyingaphonebookentryitisrecommendedthatyoudosoforreliabilitypurposes.
Thisfunctiondoesnotreturnuntilthedialinghaseitherbeensuccessfullycompletedoranerroroccurs.
TomonitortheconnectionusetheSetDialStatusCallbackfunctiontosenddialstatusinformation(asamessage)toagivenwindow.ToretrievemoreinformationwhenthisfunctionreturnsusetheGetDialStatefunction.
Seealso:DoesEntryExist
Example
/**********************************
Inthefollowingexamplewewillenumeratetheavailablephonebookentriesandthenwewillattempttoconnecttothefirstavailableentry.
**********************************/
#include"stdafx.h"//thisheaderincludesnothingbutthe#include<windows.h>statement
#include"ut_ras.h"//theheaderfilesfortheCUT_RASclass
//resourceheaderforadialog(IDD_DIALOG1)thatcontainsareadonlyeditbox(IDC_EDIT1),Dialbutton(IDC_DIAL)andacancelbutton(IDCANCEL)
#include"resource.h"
//ouruserdefinedwindowmessagefordialupstatus
#defineWM_CUT_RAS_DIALSTATUSWM_USER+1
//prototypeoftheonlydialogprocedure
BOOLCALLBACKDialupDlgProc(HWNDhwndDlg,UINTmessage,WPARAMwParam,LPARAMlParam);
//windowsmainentrypoint
intCALLBACKWinMain(HINSTANCEhInstance,HINSTANCE,LPSTR,int)
{
//createmodaldialogbox
DialogBox(hInstance,MAKEINTRESOURCE(IDD_DIALOG1),NULL,(DLGPROC)DialupDlgProc);
return0;
}
//enumeratetheavailablephonebookentriesandattempttoconnecttothefirstoneavailable
BOOLCALLBACKDialupDlgProc(HWNDhwndDlg,UINTmessage,WPARAMwParam,LPARAMlParam)
{
//staticinstanceoftheCUT_RASclass
staticCUT_RASras;
//dispatchthewindowmessages
switch(message){
//initializingthedialog
caseWM_INITDIALOG:
{
//wewanttheCUT_RASclasstosendustheWM_CUT_RAS_DIALSTATUSwindowmessage
//informingusoftheprogressofthedialupattempt
ras.SetDialStatusCallback(hwndDlg,WM_CUT_RAS_DIALSTATUS);
return1;
}
//ifthemessageistheonewehaveaskedtheCUT_RAStouse
//theninformusofthedialupattemptprogress
caseWM_CUT_RAS_DIALSTATUS:
{
//UpdatetheeditboxwiththestringpassedbytheCUT_RASclass.
//Thelowerwordofthemessageparameteristhestringdescribingthecurrentdialupstate
SetDlgItemText(hwndDlg,IDC_EDIT1,(LPCSTR)(LPARAM)lParam);
return1;
}
//ifthemessageisausercommand
caseWM_COMMAND:
switch(LOWORD(wParam))
{
//theuserclickedontheCancelbutton
caseIDCANCEL:
{
//cancelanypendingnewdialupattemptonthisinstanceoftheCUT_RASclass
ras.CancelDial();
//hang-upthecurrentconnection
ras.HangUp();
//cLosethedialog
EndDialog(hwndDlg,IDOK);
break;
}
//theuserpressedtheDialbutton
caseIDC_DIAL:
{
LPRASENTRYNAMEren=newRASENTRYNAME[sizeof(RASENTRYNAME)+1];
//getthefirstentry
ras.EnumEntries();
memset(ren,0,sizeof(RASENTRYNAME));
ras.GetEntry(ren,0);
//dialthefirstentry
ras.Dial(ren->szEntryName);
break;
}
}
break;
caseWM_CLOSE:
{
ras.CancelDial();
ras.HangUp();
EndDialog(hwndDlg,IDOK);
break;
}
}
return0;
}
CUT_RAS::DoesEntryExist
Members|Overview
intDoesEntryExist(LPCSTRszEntryName)
Parameters
szEntryName Thenameofthemainphonebookentrytocheckfor.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Operationfailed.
UTE_RAS_LOAD_ERRORUnabletoloadtheRASDLLs.
Remarks
CallthisfunctiontoseeifthespecifiedphonebookentryexistsinthemainRASphonebook.
CUT_RAS::EnumConnections
Members|Overview
intEnumConnections()
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_RAS_ENUM_ERROR Enumerationerroroccurred(seeGetLastRASErrorformoredetails).
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
CallthisfunctiontoenumeratealloftherunningRASconnectionsandstoretheminaninternalarrayofRASCONNstructures.
OnceenumeratedthedatacanberetrievedbyusingtheGetConnectionCountandGetConnectionfunctions.EnumConnectionsMUSTbecalledforthesefunctionstosucceed.
Seealso:GetConnection|GetConnectionCount
Example
//retrievesallavailableRASconnections
CComboBox*cb3=(CComboBox*)GetDlgItem(IDC_COMBO3);
m_ras.EnumConnections();
intcnt=m_ras.GetConnectionCount();
RASCONNrc;
for(x=0;x<cnt;x++){
m_ras.GetConnection(&rc,x);
cb3->AddString(rc.szEntryName);
}
cb3->SetCurSel(0);
CUT_RAS::EnumDevices
Members|Overview
inEnumDevices()
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_RAS_ENUM_ERROR Enumerationerroroccurred(seeGetLastRASErrorformoredetails).
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
CallthisfunctiontoenumeratealloftheavailableRASdialupdevices.StoresthedevicesinaninternalarrayofRASDEVINFOstructures.OnceitisenumeratedthedatacanberetrievedbyusingtheGetDeviceCountandGetDevicefunctions.EnumDevicesMUSTbecalledforthesefunctionstosucceed.
RefertotheMSDNlibraryformoreinformationontheRASDEVINFOstructure.
Seealso:GetDeviceCount|GetDevice
Example
//retrieveallavailabledialupdevices
CComboBox*cb2=(CComboBox*)GetDlgItem(IDC_COMBO2);
m_ras.EnumDevices();
cnt=m_ras.GetDeviceCount();
RASDEVINFOrdi;
for(x=0;x<cnt;x++){
m_ras.GetDevice(&rdi,x);
cb2->AddString(rdi.szDeviceName);
}
cb2->SetCurSel(0);
CUT_RAS::EnumEntries
Members|Overview
intEnumEntries()
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_RAS_ENUM_ERROR Enumerationerroroccurred(seeGetLastRASErrorformoredetails).
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
Callthisfunctiontoenumerateallofthephonebookentrynamesforthemainphonebook(thisfreeversionoftheCUT_RASclassonlysupportsthemainphonebook)andstorestheminaninternalarrayofRASENTRYNAMEstructures.
OnceenumeratedthedatacanberetrievedbyusingtheGetEntryCountandGetEntryfunctions.EnumEntriesMUSTbecalledforthesefunctionstosucceed.
RefertotheMSDNlibraryformoreinformationontheRASENTRYNAMEstructure.
Seealso:GetEntryCount|GetEntry
Example
//enumeratesallmainphonebookentries
CComboBox*cb=(CComboBox*)GetDlgItem(IDC_COMBO1);
m_ras.EnumEntries();
intcnt=m_ras.GetEntryCount();
RASENTRYNAMEren;
for(intx=0;x<cnt;x++){
m_ras.GetEntry(&ren,x);
cb->AddString(ren.szEntryName);
}
cb->SetCurSel(0);
CUT_RAS::GetConnection
Members|Overview
intGetConnection(LPRASCONNrc,DWORDindex)
Parameters
rc ApointertoanexistingRASCONNstructure.
index Azero-basedindex(0to(GetConnectionCount()-1)),specifyingtheRASconnectionfromwhichinformationwillberetrieved.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Anerroroccurredandthereisnodatatoreturn.
UTE_INDEX_OUTOFRANGE ThegivenindexdoesnotpointtoavalidRASCONNentry.
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
CallthisfunctiontofillinthegivenRASCONNstructurewiththeconnectioninformationforthespecifiedrunningconnection.ARASCONNstructurecontainsthephonebookentry'snameaswellasthedevice'stypeandname.
RefertotheMSDNlibraryformoreinformationonRASCONNstructures.
Seealso:GetConnectionCount
Example
//retrievesandshowsconnectioninformationforallrunningconnections
CComboBox*cb3=(CComboBox*)GetDlgItem(IDC_COMBO3);
m_ras.EnumConnections();
intcnt=m_ras.GetConnectionCount();
RASCONNrc;
for(x=0;x<cnt;x++){
m_ras.GetConnection(&rc,x);
cb3->AddString(rc.szEntryName);
}
cb3->SetCurSel(0)
CUT_RAS::GetConnectionCount
Members|Overview
DWORDGetConnectionCount()
ReturnValue
Thenumberofavailableconnections.Returns-1ifanerroroccurs.
Remarks
Callthisfunctiontoretrievethenumberofconnectionsfoundduringtheenumeration.EnumConnectionsneedstobecalledbeforethisfunctionwillreturnanyvaluableinformation.
Seealso:EnumConnections|GetConnection
Example
//retrievesanddisplaysthenumberofavailableconnections
CComboBox*cb3=(CComboBox*)GetDlgItem(IDC_COMBO3);
m_ras.EnumConnections();
intcnt=m_ras.GetConnectionCount();
RASCONNrc;
for(intx=0;x<cnt;x++){
m_ras.GetConnection(&rc,x);
cb3->AddString(rc.szEntryName);
}
cb3->SetCurSel(0);
CUT_RAS::GetDevice
Members|Overview
intGetDevice(LPRASDEVINFOrdi,DWORDindex)
Parameters
rdi ApointertoanexistingRASDEVINFOstructure.
index Azero-basedindex(0to(GetDeviceCount()-1)).Specifiesthedevicefromwhichinformationwillberetrieved.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Operationfailedandthereisnodatatobereturned.
UTE_INDEX_OUTOFRANGE Thegivenindexdoesnotpointtoavaliddeviceentry.
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
CallthisfunctiontofillinthegivenRASDEVINFOstructurewiththespecifieddeviceinformation.RASDEVINFOcontainsthedevice'stypeandname.
RefertotheMSDNlibraryformoreinformationonRASDEVINFOstructures.
Seealso:EnumDevices|GetDeviceCount
Example
//retrievesandlistsallavailableRASdevices
CComboBox*cb2=(CComboBox*)GetDlgItem(IDC_COMBO2);
m_ras.EnumDevices();
intcnt=m_ras.GetDeviceCount();
RASDEVINFOrdi;
for(intx=0;x<cnt;x++){
m_ras.GetDevice(&rdi,x);
cb2->AddString(rdi.szDeviceName);
}
cb2->SetCurSel(0);
CUT_RAS::GetDeviceCount
Members|Overview
DWORDGetDeviceCount()
ReturnValue
DWORD Thenumberofdevicesfound,or-1ifanerroroccurs.
Remarks
Callthisfunctiontoretrievethenumberofavailabledevices.EnumDevicesMUSTbecalledbeforethisfunctionwillreturnanyvaluableinformation.
Seealso:GetDevice|EnumDevices
Example:seeGetDevice
CUT_RAS::GetDialEntryParams
Members|Overview
intGetDialEntryParams(LPCSTRszEntryName,LPRASDIALPARAMSpRasDialParams,BOOL*bClearPassword=NULL)
Parameters
szEntryName Aphonebookentryname.
pRasDialParams ApointertoaRASDIALPARAMSstructure.
bClearPassword IfTRUEthenthepasswordhasbeencleared,ifFALSEthenthepasswordisvalid.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Operationfailed.
UTE_NULL_PARAM pRasDialParamsisNULL.
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
Callthisfunctiontoretrievethedialingparametersforthegivenphonebookentry.
YouMUSTusethisfunctioninordertoretrievetheusernameandpasswordforaphonebookentry.
TheRASDIALPARAMSalsocontainsotherinformationaswell.
Seealso:GetEntryPassword|GetEntryUserName|GetEntryPhoneNumber
CUT_RAS::GetDialState
Members|Overview
DWORDGetDialState()
ReturnValue
DWORD TheLOWORDcontainsthethecurrent(orlast)stateofthedialupprocess(seeRASCONNSTATEintheMSDNlibraryforacompletelistingofstates).TheHIWORDcontainstheerrorcodewhichappliestothecurrentstate(foracompletelistingoferrorcodesseetheRASERROR.HheaderfileoftheWindowsSDKorthe"RASErrorValues"topicintheMSDNlibrary).
Remarks
Callthisfunctiontoretrievethecurrentstateofthedialupprocess.Ifthisisnotavailablethenthelastdialupstateisretrieved.ThisisusefulfordeterminingthestateofthedialupaftertheDialfunctionhascompleted.
Seealso:GetRASErrorString
CUT_RAS::GetEntry
Members|Overview
intGetEntry(LPRASENTRYNAMEren,DWORDindex)
Parameters
ren ApointertoanexistingRASENTRYNAMEstructure.
index Azero-basedindex(0to(GetEntryCount()-1)).Determinestheentryfromwhichtoretrieveinformation.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Operationfailedandthereisnodatatobereturned.
UTE_INDEX_OUTOFRANGE Thesuppliedindexdoesnotpointtoavalidphonebookentry.
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
CallthisfunctiontofillinthegivenRASENTRYNAMEstructurewiththephonebookentry'sname.
Seealso:EnumEntries|GetEntryCount
Example
//storesthefirstphonebookentry'snametoaRASENTRYNAMEstructure
LPRASENTRYNAMEren=newRASENTRYNAME[sizeof(RASENTRYNAME)+1];
//getthefirstphonebookentry
ras.EnumEntries();
memset(ren,0,sizeof(RASENTRYNAME));
ras.GetEntry(ren,0);
delete[]ren;
CUT_RAS::GetEntryCount
Members|Overview
DWORDGetEntryCount()
ReturnValue
DWORD Numberofavailablephonebookentries,or-1ifanerroroccurs.
Remarks
Returnsthenumberofphonebookentries.EnumEntriesMUSTbecalledbeforethisfunctionwillreturnanyvaluableinformation.
RefertotheMSDNlibraryformoreinformationonRASDEVINFOstructures.
Seealso:GetEntry|EnumEntries
Example
//retrievesphonebookentriesanddisplaysthem
CComboBox*cb=(CComboBox*)GetDlgItem(IDC_COMBO1);
m_ras.EnumEntries();
intcnt=m_ras.GetEntryCount();
RASENTRYNAMEren;
for(intx=0;x<cnt;x++){
m_ras.GetEntry(&ren,x);
cb->AddString(ren.szEntryName);
}
cb->SetCurSel(0);
CUT_RAS::GetEntryPassword
Members|Overview
intGetEntryPassword(LPCSTRszEntryName,LPSTRszPassword,longnMaxLen)
Parameters
szEntryName Aphonebookentry.
szPassword Pointertoastringbufferthatwillstorethepassword.
nMaxLen LengthoftheszPasswordbuffer.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Thefunctionfailed(seeGetLastRASErrorformoredetails).
UTE_BUFFER_TOO_SHORT ThepasswordstringislargerthanthespecifiednMaxLen.
UTE_NULL_PARAM ThepassedbufferisNULL.
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
Returnsthemainphonebook'spasswordforthespecifiedphonebookentry.ThisfunctionismoreefficientthantheGetEntryPropertiesfunctionwhenitcomestoretrievingapassword.
Seealso:GetEntryProperties|GetEntryUserName|GetEntryPhoneNumber
CUT_RAS::GetEntryPhoneNumber
Members|Overview
intGetEntryPhoneNumber(LPCSTRszEntryName,LPSTRszPhoneNumber,longnPhoneNumberLen,LPSTRszAreaCode,longnAreaCodeLen)
Parameters
szEntryName Thedesiredphonebookentry.
szPhoneNumber Pointertoastringbufferthatwillstoretheretrievedphonenumber.
nPhoneNumberLen LengthoftheszPhoneNumberbuffer.
szAreaCode Pointertoastringbufferthatwillstoretheretrievedareacode.
nAreaCodeLen LengthoftheszAreaCodebuffer.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Functionfailed(seeGetLastRASErrorformoredetails).
UTE_RAS_LOAD_ERRORUnabletoloadtheRASDLLs.
Remarks
Retrievesthemainphonebooknumberandareacodeforthegivenphonebookentry.Thisfunctionreducestheamountofworkrequiredto
retrieveaphonenumbercomparedtousingtheGetEntryPropertiesfunctiondirectly.
Seealso:GetEntryProperties
Example
//retrievesanentryphonenumberanddisplaysitifthenumberwassuccessfullyretrieved
if(m_pRas->GetEntryPhoneNumber(m_szEntryName,szTemp,sizeof(szTemp),szAreaCode,
{
SetDlgItemText(IDC_PHONE_NUMBER,szTemp);
SetDlgItemText(IDC_AREA_CODE,szAreaCode);
}
CUT_RAS::GetEntryProperties
Members|Overview
intGetEntryProperties(LPCSTRszEntryName,LPRASENTRYpRasEntry,DWORD*pnRasEntryLen)
Parameters
szEntryName Aphonebookentry.
pRasEntry ApointertoanallocatedRASENTRYstructure.ThedwSizememberofthestructuremustbesetto"sizeof(RASENTRY)".
pnRasEntryLen ThesizeofthepRasEntrybuffer.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Functionfailed(seeGetLastRASErrorformoredetails).
UTE_BUFFER_TOO_SHORT Thesuppliedbufferwastoosmall.
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
Retrievesthepropertiesforagivenphonebookentry.ThisfunctiontakesapointertoaRASENTRYstructurewhichmustalreadyexist.
NOTE:theRASENTRYstructurecanbefollowedbyanarrayofnull-
terminatedalternatephonenumberstrings.Thelaststringisterminatedbytwoconsecutivenullcharacters.ThedwAlternateOffsetmemberoftheRASENTRYstructurecontainstheoffsettothefirststring.
SetthenRasEntryLenparametertothetotallengthofthegivendatabuffer.Ifthebufferistoosmallthenthefunctionwillfail.
TohelpensuresuccesscallthefunctionwithpRasEntrysettoNULLandnRasEntryLensetto0.IfthefunctionreturnswithavalueofUTE_BUFFER_TOO_SHORTthennRasEntryLenwillcontaintherequiredsizeofthebuffer.Allocateabufferoftherequiredsizeandcallthefunctionagain.
Example
//iftheentrynameispassedthenamodificationcallismade
//tothisdialoginsteadofanaddcall.
if(m_pRas->GetEntryProperties(m_szEntryName,NULL,&size)==UTE_BUFFER_TOO_SHORT)
{
m_rasEntry=newRASENTRY[size];
m_rasEntry->dwSize=size;
//retrieveallpropertiesfortheselectedbookentry
if(m_pRas->GetEntryProperties(m_szEntryName,m_rasEntry,&size)==UTE_SUCCESS)
{
//gettheusername
if(m_pRas->GetEntryUserName(m_szEntryName,szTemp,sizeof(szTemp))==UTE_SUCCESS)
{
SetDlgItemText(IDC_USER,szTemp);
}
//getthepassword
if(m_pRas->GetEntryPassword(m_szEntryName,szTemp,sizeof(szTemp))==UTE_SUCCESS)
{
SetDlgItemText(IDC_PASSWORD,szTemp);
}
//getphonenumberandareacode
if(m_pRas->GetEntryPhoneNumber(m_szEntryName,szTemp,sizeof(szTemp),szAreaCode,
{
SetDlgItemText(IDC_PHONE_NUMBER,szTemp);
SetDlgItemText(IDC_AREA_CODE,szAreaCode);
}
}
}
CUT_RAS::GetEntryUserName
Members|Overview
intGetEntryUserName(LPCSTRszEntryName,LPSTRszUserName,longnMaxLen)
Parameters
szEntryName Phonebookentrytoretrievetheusernamefrom.
szUserName Pointertoastringbufferthatwillstoretheretrievedusernamevalue.
nMaxLen LengthoftheszUserNamebuffer.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Functionfailed(seeGetLastRASErrorformoredetails).
UTE_BUFFER_TOO_SHORT TheusernamestringislargerthanthespecifiednMaxLenparameter.
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
Returnsthemainphonebook'susernameforthegivenphonebookentry.ThisfunctionreducestheamountofworkrequiredtoretrieveausernamecomparedtousingtheGetEntryPropertiesfunctiondirectly.
Seealso:GetEntryProperties|GetEntryPassword
Example
//retrieveusernameforthespecifiedphonebookentry
charszTemp[]
if(m_pRas->GetEntryUserName(m_szEntryName,szTemp,sizeof(szTemp))==UTE_SUCCESS)
{
SetDlgItemText(IDC_USER,szTemp);
}
CUT_RAS::GetLastRASError
Members|Overview
DWORDGetLastRASError()
ReturnValue
DWORD ErrorcodeofthelastRASoperation.
Remarks
ThisfunctionreturnstheerrorcodefromthelastRASfunctioncalled.ForacompletelistingoferrorcodesseetheRASERROR.HheaderfileoftheWindowsSDKorthe"RASErrorValues"topicintheMSDNlibrary.
Callingthisfunctionisusefulifextendederrorinformationisrequired.
Seealso:GetErrorString|GetRASErrorString
Example
//iferrorisaRASerrordisplaytheappropriateerrorstring,
//otherwiseuseCUT_ERR::GetErrorString.
intCUT_TestRas::OnError(intnError)
{
if(nError!=UTE_SUCCESS&&nError!=UTE_BUFFER_TOO_SHORT)
{
//iftheerrorisaRASerrordialthendisplaytheerrorstring
if(nError!=UTE_RAS_DIAL_ERROR)
{
MessageBox(NULL,CUT_ERR::GetErrorString(nError),"ONERROR",MB_OK);
}else
{
//letsmakesurethattheerroriswithinthelimit
if(GetLastRASError()>RASBASE&&GetLastRASError()<=ERROR_HANGUP_FAILED)
{
MessageBox(NULL,GetRASErrorString(GetLastRASError()),"ONERROR",MB_OK);
}
}
}
returnnError;
}
CUT_RAS::GetRASErrorString
Members|Overview
LPCSTRGetRASErrorString(DWORDerror)
Parameters
error DWORDspecifyingtheRASerrorcode.
ReturnValue
LPCSTR Astringdescribingtheerrorcode.
Remarks
ThisfunctionreturnstheappropriateerrorstringcorrespondingtothepassedRASerrorcode.ForacompletelistingoferrorcodesseetheRASERROR.HheaderfileoftheWindowsSDKorthe"RASErrorValues"topicintheMSDNlibrary.
Callingthisfunctionisusefulifextendederrorinformationisrequired.
Seealso:GetErrorString
Example
//displayanerrorstringbasedonanerrorcode
intCUT_TestRas::OnError(intnError)
{
if(nError!=UTE_SUCCESS&&nError!=UTE_BUFFER_TOO_SHORT)
{
//iftheerrorisaRASdialingerrordisplaytheerrorstring
if(nError!=UTE_RAS_DIAL_ERROR)
{
MessageBox(NULL,CUT_ERR::GetErrorString(nError),"ONERROR",MB_OK);
}
else
{
//letsmakesurethattheerroriswithinthelimitsofourerrorcodes
if(GetLastRASError()>RASBASE&&GetLastRASError()<=ERROR_HANGUP_FAILED)
MessageBox(NULL,GetRASErrorString(GetLastRASError()),"ONERROR",MB_OK);
}
}
returnnError;
}
CUT_RAS::HangUp
Members|Overview
intHangUp()
intHangUp(HRASCONNrasConn)
Parameters
rasConn ARASconnectionhandle.
ReturnValue
UTE_SUCCESS Successfullyhunguptheconnectionoritwasnotconnectedtobeginwith.
UTE_RAS_HANDLE_ERRORNULLRAShandlesupplied.
UTE_RAS_LOAD_ERROR UnabletoloadtheRASDLLs.
Remarks
CallthisfunctiontohangupacurrentlyactiveRASconnection.IfrasConnisnotspecifiedthenthefunctionattemptstohangupthecurrentconnectionthatwasinitiatedwiththeDialfunction.OtherwiseitwillhangupthespecifiedRASconnectionbyusingthesuppliedRASconnectionhandle.
RASconnectionhandlescanberetrievedusingtheEnumConnectionsfunction.
Oncethehang-upprocessstartsthisfunctionwillwaituntilthehang-upiscomplete.Hang-uptimesvaryanddependonthemodem.Usually1-3
secondsisthenorm.
Ifthehang-upstatuscannotbemonitored(whichisthecaseonsomeolderversionsofWin95)thena4secondwaitingperiodisappliedtoensureaproperhang-up.
Example
//hangsupaspecifiedconnection
voidCTestAppDlg::OnHangUp()
{
RASCONNrConection;
intindex=0;
//ifwearecurrentlytryingtoconnectthenexittheconnectionattempt
m_ras.CancelDial();
//GettheSelectedconnectionoutoftheComboBox
index=m_ctlConnections.GetCurSel();
if(index!=LB_ERR&&index<m_ctlConnections.GetCount())
{
m_ras.GetConnection(&rConection,index);
m_ras.HangUp(rConection.hrasconn);
}
else
m_ras.HangUp();
//displaytheconnections
CComboBox*cb3=(CComboBox*)GetDlgItem(IDC_COMBO3);
cb3->ResetContent();
cb3->SetWindowText("");
m_ras.EnumConnections();
intcnt=m_ras.GetConnectionCount();
RASCONNrc;
for(intx=0;x<cnt;x++){
m_ras.GetConnection(&rc,x);
cb3->AddString(rc.szEntryName);
}
cb3->SetCurSel(0);
}
CUT_RAS::InitRAS
Members|Overview
BOOLInitRAS()
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_RAS_LOAD_ERROR CouldnotloadtheRASDLLs.
Remarks
ThisfunctionloadsintheRASDLLsdynamically.ThisallowstheclasstobeusedinapplicationswhereRASmayormaynotbeinstalled.ForWin95OSR2andlatertheRASAPI32.DLLisused.ForearlierWin95versionsRNAPH.DLLisusedforsomefunctions.ThisDLLmaybere-distributedsinceitisnotapartofRASbutapatchforearlyWin95versions.
ThisfunctionSHOULDBECALLEDpriortocallingotherfunctionsofCUT_RAS.NotethatInitRASiscalledinternallybysomefunctionsoftheCUT_RASclasssuchasEnumEntriesandEnumConnections.
CUT_RAS::IsConnected
Members|Overview
BOOLIsConnected()
ReturnValue
ReturnsTRUEifconnected,otherwiseitreturnsFALSE.
Remarks
Callthisfunctiontocheckthestateofthecurrentconnection.IftheconnectionisstillgoodthenTRUEisreturnedbutiftheconnectionhasbeenterminatedFALSEisreturned.
Thisfunctionisusefulformonitoringaconnectionthroughoutitslifetime,sincedisconnectionsarequitecommonforavarietyofreasons(ISPtimeouts,voicepriorityoverdataonbusyphonelines,noisyphonelines,etc.).
Example
//updatetheconnectionstatusofthisapplication'sinstanceoftheRASconnection
voidCTestAppDlg::OnTimer(UINTnIDEvent)
{
CStringstrStatus;
//checkifweareconnected
if(m_ras.IsConnected())
strStatus="Connected";
else
strStatus="Disconnected";
SetDlgItemText(IDC_STATUS,strStatus);
CDialog::OnTimer(nIDEvent);
}
CUT_RAS::OnError
Members|Overview
virtualintOnError(intnError)
Parameters
nError Theerrorcodeoftheerrorthatoccurred.
ReturnValue
UTE_SUCCESSOperationcompletedsuccessfully.
UTE_ERROR Operationfailed.
Remarks
Allfunctionswhichhavereturnerrorcodescallthisfunction.OverrideOnErrortoprovideextendederrorhandlinganddebuggingcapabilities.
Seealso:GetLastRASError|GetRASErrorString
Example
//displayanerrorstringviatheOnErrorcallback
intCUT_TestRas::OnError(intnError)
{
if(nError!=UTE_SUCCESS&&nError!=UTE_BUFFER_TOO_SHORT)
{
if(nError!=UTE_RAS_DIAL_ERROR)
{
MessageBox(NULL,CUT_ERR::GetErrorString(nError),"ONERROR",MB_OK);
}else
{
if(GetLastRASError()>RASBASE&&GetLastRASError()<=ERROR_HANGUP_FAILED)
MessageBox(NULL,GetRASErrorString(GetLastRASError()),"ONERROR",MB_OK);
}
}
returnnError;
}
CUT_RAS::RenameEntry
Members|Overview
intRenameEntry(LPCSTRszEntryName,LPCSTRszNewEntryName)
Parameters
szEntryName Phonebookentrytorename.
szNewEntryNameNewnameofthephonebookentry.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Functionfailed(seeGetLastRASErrorformoredetails)
UTE_RAS_LOAD_ERRORUnabletoloadtheRASDLLs.
Remarks
Callthisfunctiontorenamethegivenphonebookentry.
CUT_RAS::SetDialEntryParams
Members|Overview
intSetDialEntryParams(LPCSTRszEntryName,LPRASDIALPARAMSpRasDialParams,BOOLbClearPassword=FALSE)
Parameters
szEntryName Aphonebookentryname.
pRasDialParams ApointertoaRASDIALPARAMSstructure.
bClearPassword SetthistoTRUEtoremovethepasswordfromthegivenentry.SetthistoFALSEtosetthepassword.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Functionfailed(seeGetLastRASErrorformoredetails).
UTE_NULL_PARAM ThepRasDialParamsparameterisNULL.
UTE_RAS_LOAD_ERRORUnabletoloadtheRASDLLs.
Remarks
Callthisfunctiontosetthedialingparametersforthegivenphonebookentry.ThephonebookentryMUSTexistforthisfunctiontosucceed.
UseSetDialEntryParamstostoretheusernameandpasswordforaphonebookentry.TheRASDIALPARAMSstructurealsocontainsother
optionalinformation.
RefertotheMSDNlibraryformoreinformationontheRASDIALPARAMSstructure.
Example
//setthedialingparametersforadialupentry
if(m_pRas->SetEntryProperties(m_szEntryName,m_rasEntry)==UTE_SUCCESS)
{
//nowsettheDialupproperties
LPRASDIALPARAMSpDialParam=newRASDIALPARAMS[sizeof
memset(pDialParam,0,sizeof(RASDIALPARAMS));
pDialParam->dwSize=sizeof(RASDIALPARAMS);
//SettheEntryname
strcpy(pDialParam->szEntryName,m_szEntryName);
//setthephonenumber
GetDlgItemText(IDC_PHONE_NUMBER,pDialParam->szPhoneNumber,RAS_MaxPhoneNumber);
//settheusername
GetDlgItemText(IDC_USER,pDialParam->szUserName,UNLEN);
//setthepasswordstring
GetDlgItemText(IDC_PASSWORD,pDialParam->szPassword,PWLEN);
//nowupdatetheentry'sDialupparameters
m_pRas->SetDialEntryParams(m_szEntryName,pDialParam,FALSE);
delete[]pDialParam;
}
CUT_RAS::SetDialStatusCallback
Members|Overview
intSetDialStatusCallback(HWNDhWnd,intnMessageID)
Parameters
hWnd Handleofthewindowwhichwillreceivethewindowmessages.
nMessageID IDofthemessagetosend.
ReturnValue
UTE_SUCCESS Thisfunctionalwaysreturnassuccessful.
Remarks
Setsthewindowwhichwillretrievemessagesduringdialing(seetheDialfunction).Messagesaresenteachtimethedialingstatechanges,andthisfunctionisusefulforshowingtheuserthecurrentstatewithinawindowordialogbox.
TheformatofthemessagesentbackbytheclasstothewindowspecifiedbythehWndhandleis:
wParamTheLOWORDcontainsastringindicatingthecurrentstateofthedialupprocess.TheHIWORDcontainstheerrorcodewhichappliestothecurrentstate.SeetheRASERROR.Hheaderfileforacompletelistingoferrorcodes.
lParamPointstoastringbufferwhichdescribesthecurrentstate.
Examples
Dialisinvokedasanasynchronousoperationandthefunctionreturnsimmediately.TheusermustthereforespecifyanotificationhandlerthattheRASobjectusestoinformtheclientapplicationwhentheconnectionoperationstatechangesoranerroroccurs.Thishandlerisimplementedbelow.FormoreinformationseethesamplecodeintheOverviewpage.
MFCSample
HeaderFile
//Generatedmessagemapfunctions
//{{AFX_MSG(CTestAppDlg)
........
afx_msgLRESULTOnDialStatus(WPARAMwParam,LPARAMlParam);
.......
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
SourceFile
BEGIN_MESSAGE_MAP(CTestAppDlg,CDialog)
//{{AFX_MSG_MAP(CTestAppDlg)
...
ON_MESSAGE(WM_USER+1,OnDialStatus)
.......
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
.....
(inOnInitDialog)
//specifyanotificationhandlerthatRASuses
//toinformtheclientapplicationwhentheconnection
//operationstatechangesoranerroroccurs
m_ras.SetDialStatusCallback(m_hWnd,WM_USER);
......
LRESULTCTestAppDlg::OnDialStatus(WPARAMwParam,LPARAMlParam){
DWORDdwError=HIWORD(wParam);
UpdateData();
CStringszTemp=(LPCSTR)m_strStatus;
szTemp+="\r\n";
szTemp+=(LPCSTR)lParam;
SetDlgItemText(IDC_EDIT1,szTemp);
if(dwError){
MessageBox(m_ras.GetRASErrorString(dwError));
}
m_ctlStatus.LineScroll(100000);
return0;
}
SDKSample
ras.SetDialStatusCallback(hwndDlg,WM_USER+1);
caseWM_USER+1:
{
SetDlgItemText(hwndDlg,IDC_EDIT1,(LPCSTR)(LPARAM)lParam);
return1;
}
CUT_RAS::SetEntryProperties
Members|Overview
intSetEntryProperties(LPCSTRszEntryName,LPRASENTRYpRasEntry,DWORDnRasEntryLen=sizeof(RASENTRY)
Parameters
szEntryName Nameofthephonebookentrytoaddorupdate.
pRasEntry ApointertoaRASENTRYstructurewhichcontainsthedatafortheentrytoaddorupdate.ThedwSizememberofthestructuremustbesettosizeof(RASENTRY).NOTE:Thiscanoptionallybefollowedbyalistofalternativephonenumbers.
nRasEntryLen SizeoftheRASentry.Defaultstosizeof(RASENTRY).Itcanbesetifalistofalternativephonenumbersarealsoavailable.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Functionfailed(seeGetLastRASErrorformoredetails).
UTE_RAS_LOAD_ERRORUnabletoloadtheRASDLLs.
Remarks
Callthisfunctiontocreateormodifyaphonebookentry.Ifthegivenentrydoesnotexistthenanewoneiscreated,butiftheentryalreadyexists
thenitisoverwritten.ThisfunctiontakesapointertoaRASENTRYstructurewhichcontainsallofthefieldsrequiredtomakeacompletephonebookentryexceptfortheusernameandpassword(seeSetDialEntryParams).NOTE:theRASENTRYstructurecanbefollowedbyanarrayofnull-terminatedalternatephonenumberstrings.Thelaststringisterminatedbytwoconsecutivenullcharacters.ThedwAlternateOffsetmemberoftheRASENTRYstructurecontainstheoffsettothefirststring.
SetthenRasEntryLenparametertothetotallengthofthegivendata.nRasEntryLenhasadefaultvalueofsizeof(RASENTRY).
UseValidateEntryNametomakesurethatanewentrynameisvalid.
Seealso:GetEntryProperties|GetEntry
Example
/*******************************************************************
Readthevaluesfromthedialog'scontrolsandupdatethe
RasEntrystructureandthensetthepropertiesofthespecifiedentry.
Thissamplecodeonlyaddsnewentries.Forclarity,iftheentry
existsitisnotmodified(youcanmodifythecodeto
alterexistingentries).
*******************************************************************/
voidCAddModifyEntry::OnOk()
{
//readthevaluesfromthedialog'scontrolsandupdatethe
//RasEntrystructurethenSettheProperties
if(m_bModify){
//UpdatetheDialogscontrolsbasedontheentry'sData
GetDlgItemText(IDC_ENTRYNAME,m_szEntryName,RAS_MaxEntryName);
if(m_pRas->DoesEntryExist(m_szEntryName)==UTE_SUCCESS)
{
//askiftheuserwantstomodifytheexistingentry
MessageBox("Anentrywiththisnamealreadyexists");
}else
{
if(m_pRas->ValidateEntryName(m_szEntryName)==UTE_SUCCESS)
{
//getthenewphonenumber
GetDlgItemText(IDC_PHONE_NUMBER,m_rasEntry->szLocalPhoneNumber,RAS_MaxPhoneNumber);
//getthenewarecodenumber
GetDlgItemText(IDC_AREA_CODE,m_rasEntry->szAreaCode,RAS_MaxAreaCode);
if(m_pRas->SetEntryProperties(m_szEntryName,m_rasEntry)==UTE_SUCCESS)
{
//nowsettheDialupproperties
LPRASDIALPARAMSpDialParam=newRASDIALPARAMS[sizeof(RASDIALPARAMS)+1];
memset(pDialParam,0,sizeof(RASDIALPARAMS));
pDialParam->dwSize=sizeof(RASDIALPARAMS);
//SettheEntryname
strcpy(pDialParam->szEntryName,m_szEntryName);
//setthephonenumber
GetDlgItemText(IDC_PHONE_NUMBER,pDialParam->szPhoneNumber,RAS_MaxPhoneNumber);
//settheusername
GetDlgItemText(IDC_USER,pDialParam->szUserName,UNLEN);
//setthepasswordstring
GetDlgItemText(IDC_PASSWORD,pDialParam->szPassword,PWLEN);
//nowupdatetheentry'sDialupparameters
m_pRas->SetDialEntryParams(m_szEntryName,pDialParam,FALSE);
delete[]pDialParam;
CDialog::OnOK();
}
}else//theselectednameisnotvalidname
MessageBox("Namenotvalid");
}
}else//ifwearenotaddinganewentrythenjustexit
CDialog::OnOK();
}
CUT_RAS::ValidateEntryName
Members|Overview
intValidateEntryName(LPCSTRszEntryName)
Parameters
szEntryName Astringspecifyingthephonebookentrytocheck.
ReturnValue
UTE_SUCCESS Operationcompletedsuccessfully.
UTE_ERROR Functionfailed(seeGetLastRASErrorformoredetails).
UTE_RAS_LOAD_ERRORUnabletoloadtheRASDLLs.
Remarks
Checkstoseeifthespecifiedphonebookentryisavalidnameforanewentry.Thisfunctionwillalsofailifthephonebookentryalreadyexists.
CUT_ERROverviewCopyright©DundasSoftwareLtd.1996-1999,AllRightsReserved
CUT_ERRClassMembers
DependenciesandRelatedFiles
CUT_ERRcanbethoughtofasasortof'namespace'classwhichorganizesthedeclarationoferrorcodesandtheirassociatederrortext.Themotivationfortheclasswastomoveerrorcodedefinitionsoutoftherealmofthepreprocessorandintothecodeitself,sothatvalueswouldbevisibleduringdebugsessions,etc.
Theclassusesanenumerationtodefineerrorcodesthatwillbeusedforotherclassesinthelibrary.Thesecouldhavebeendeclaredasconstmembers,butnotallcompilerssupportthisfeature.
Theconstructor,destructor,copyconstructorandassignmentoperatoraredeclaredasprivatemembers.Thisclasscannotbeinstantiatedorusedasabaseclass.
Alongwiththeenumerationoferrorcodes,twostaticpublicmethodsaredeclared.GetErrorString()allowstheusertoretrieveatextdescriptionoftheerror.GetSocketError()canbeusedduringdevelopmenttoretrievetheerrorassociatedwithawinsockAPIcallthathasreturnedSOCKET_ERROR.
GetErrorStringcallsthestaticprivatemethodInitErrorStrings()thefirsttimeitiscalled.InitErrorStrings()theninitializesanarrayofstringconstants.
AddingNewCodes
Thelistoferrorsavailable(inuterr.h)iseasilyextendedbyaddingthenewconstant(e.g.UTE_THE_ERROR_DUNDAS_FORGOT)tothe
CUT_ERROR_CONSTANTSenumerationandthenaddingalineofcodetotheinitializationmethodInitErrorStrings.Youmightliketoleavethecorecodealone,sowe'veprovidedamechanismforextendingtheerrorswithoutmodifyinguterr.h.
Anadditionalheader'UTExtErr.h'canbefoundintheIncludedirectory.YoucanusethisfiletoinsertnewerrorcodesandtheircorrespondingtextintotheCUT_ERRenumeration.Youcaneditthisfileinplaceifyouwanttoextendyournewerrorstoallprojects,oryoucanuseitonaper-projectbasisbycopyingittoyourprojectdirectory.(Makesureyourprojectpre-processoradditionalincludescontains".\"sothatthisversionisincludedfromwithinuterr.h).
InsideUTExtErr.hyouwillfindthefollowing(commented)sample:
#ifndef_EXT_ERR_STRINGS//Addyourerrorconstantshere.Seeexamplebelow://UTE_DATABASE_CONNECT_ERROR,//UTE_NOT_SUPPORTED,#else//Addyourerrorstringassociationshere.Seeexamplebelow://pStrings[UTE_DATABASE_CONNECT_ERROR]=_T("Databaseconnectionerror.");//pStrings[UTE_NOT_SUPPORTED]=_T("Operationisnotsupported.");#endif
Addthemnemonicforyournewcodefollowedbyacomma,andspecifyastringtobereturnedfromGetErrorString().
Usage
Whiletheenumerated'constants'areavailablewithouttheneedforscoping,thestaticGetErrorStringneedstobeprefacedbytheclassname.(Thisisthe'namespace'aspectoftheclass.)
Forexample,todisplayalloftheavailableerrorcodesandtheirnumericvalueonecouldwrite:
for(inti=0;i<CUT_MAX_ERROR;i++)
cout<<i<<"."<<CUT_ERR::GetErrorString(i)<<endl;
Thismaybesomethingyouwanttodoinordertohaveanumericreferencefordebugging.Wedon'texplicitlyassignvaluestothecodesinsidetheenumeration,soyoucannotjustrefertotheheadertoseewhat'error43'means.BeingabletocallGetErrorStringprovidessomecompensation.
ManyoftheclientandserverclassesthatusetheseenumerationsasreturncodesdosoviaavirtualOnErrormethodwhichcanbeoverriddenormodifiedtotraceerrormessagesthroughtheuseofGetErrorString.Inmostcasesweleaveituptoyoutoimplementthissothatyoucanthenselecttheappropriateoutputdevice.
CUT_ERRClassMembers
Copyright©DundasSoftwareLtd.1996-1999,AllRightsReserved
Overview
GetErrorString Retrievestheerrortextforagivenerror.
GetSocketError Retrievestheerrorandstringdescriptionofawinsockerrorforasocket.
CUT_ERRDependenciesandRelatedFiles
Copyright©DundasSoftwareLtd.1996-1999,AllRightsReserved
Overview
INCLUDE uterr.h
CUT_ERR::GetErrorString
Members|Overview
staticconst_TCHAR*GetErrorString(interr)
Parameters
err Theenumeratederrorcode.
ReturnValue
Returnsatextdescriptionoftheerrorthathasoccurred.Ifthecallismadewithanerrvaluethatisoutofrangethestringthen"CUT_ERR::GetErrorString:ErrorStringarrayimproperlyinitialized"willbereturned.
Remarks
YouwillusuallycallthismethodtoobtainadescriptionofanerrorreturnedfromoneoftheclientorserverUltimateTCPIPv3.0classes.NotethatyoumustusetheCUT_ERR::scopingpreface-thisisastaticmethodofaclassthatisneverinstantiated.
Example
//testforthesuccess/failureofaSendFileoperation.
if(UTE_SUCCESS!=(res=MyDerivedWSClient.SendFile("myfile.txt"))){
#ifdef_DEBUG
cout<<CUT_ERR::GetErrorString(res)<<endl;
#endif
switch(res)
{
caseUTE_ABORTED:
//sendabortedbyuser
break;
caseUTE_FILE_OPEN_ERROR:
//unabletoopenspecifiedfile
break;
caseUTE_CONNECT_TERMINATED:
//remoteconnectionterminated
break;
default:
assert(0);//shouldneverhappen...
break;
}
}
CUT_ERR::GetSocketError
Members|Overview
staticLPCSTRGetSocketError(SOCKET*s,int*result=NULL)
Parameters
s Apointertothesockettobequeried.
result Anoptionalintegerthatwillreceivetheactualwinsockerrorcode.
ReturnValue
Astringcontainingareadabledescriptionofthelasterrortooccuronthesocket(ifavailable).
Remarks
Inmostcases,thepredefinedreturncodesaresufficienttoindicatewhatwentwrongwithacalltoamethodofoneoftheUltimateTCPIPclasses.
OccasionallyyouwillfindthatyouneedtodealwithareturnvalueofSOCKET_ERRORfromacalltoawinsockAPIfunction,particularlywhenextendingaclass.
ThisususallyinvolvesacalltoWSAGetLastError,andaswitchstatementtodeterminewhicherrorconstantwasreturned.Oftenyouwillneedtheswitchtodetermineacourseofactiontotake,butifallyouareconcernedwithisknowingwhattheerrorwas,GetSocketErrorcanbeatimeandspacesaver.
WSAGetLastErrorwillreturnthelasterrorthatoccurredonanysocketinthecurrentthread.ThecodeinGetSocketErrortakesapointertothe
socketinordertoquerythesocket.ThisisdonebyusingtheGetSockOptcall,ratherthanWSAGetLastError.
Ifthesocketisinvalidthereturnstringwillbe"GetSockOpterror:WSAENOTSOCK",indicatingthatthecalltoGetSockOptfailed.OthererrorsmaybereturnedasGetSockOpterrors.
Ifyouwanttheactualerrorcodepassapointertotheresultparameter.
ForsomeTCPIPmethodsyoushouldcallWSAGetLastErrortodeterminethesocketerrorifaparticularcallreturnsUTE_ERRORor-1.Thisisindicatedwhereappropriate.
Ifthesocketisstillvalid(i.e.themethodwasnotinvolvedwithcreatingordestroyingthesocket)youmayfinditmoreconvenienttocallGetSocketErrorinsteadofWSAGetLastError.
GetSocketErrorisintendedmoreasadevelopmentaidthanalibraryexport.
Seealso:GetErrorString
Example
//ifanerroroccursconnectingthenintheOnErrorcallback
//wearejustexaminingtheerrorandthenreturninganerrorcode.
if(connect(m_socket,(LPSOCKADDR)&m_sockAddr,sizeof(m_sockAddr))==SOCKET_ERROR)
{
//youcanplaceabreakpointheretoexaminethestring
LPCSTRstr=CUT_ERR::GetSocketError(&m_socket);
returnOnError(UTE_SOCK_CONNECT_FAILED);
}
DundasMailerControl1.0
Copyright©DundasSoftwareLtd.2000,AllRightsReserved.
Overview|Properties|Methods
TheDundasMailerControl1.0isafreecommercialemailcontrolwhichutilizestheSMTP,MIMEandNNTPprotocolstosendemailmessagesandpostnewsarticles.IthasbeendesignedforusewithinActiveServerPages(ASP)andcanbeusedbyanypersonororganizationthatishostingwebsitesusingMicrosoft'sInternetInformationServer.ItisalsousedinconjunctionwiththeDundasUploadControlwhendealingwithuploadedfilestobesenteitherasattachmentsorembeddedhtmlobjects.
TheDundasMailercontrolisextremelyfastandreliable.Thefollowingisalistingofthecontrol'sfeatures:
SpecifymultiplerecipientsbyusingtheTOs,CCs,andBCCscollections.
Abilitytopostnewsarticlestonewsgroups.
Supportsbothtext-basedandhtml-basedemail.
Supportforembeddedhtmlobjectswithinanhtml-basedemail(audiofiles,images,etc.).
Abilitytosendmultiplefileattachments.
ReplyToproperty(implementedasacollection).
Messageheaderscanbesettonon-ASCIIvalueswiththeEncodeHeadermethod.
Youcanspecifythecharactersettobeusedforthemessagebody(fornon-Englishemails).
Prioritypropertyusedtoindicatelow,highornormalpriorities.
AQuickSendmethodwhichallowsyoutosendanemailwithaminimalamountofcode.
UsemultipleSMTPrelaysforimprovedspeedandreliability.
ValidateemailaddresseswiththeValidateAddressmethod.
UseoneormorespecifiedDNSserversforDirectSendingofemail.
ConfirmReadproperty.
ReturnReceiptproperty.
Optionallyloadthemessagebodyfromfile.
Supportstheadditionofcustomheaderstoanemail.
MSDNintegratedhelp.
Fullcontrolovervarioustimeoutproperties.
TheDundasMailercontrolexposestwomethodswhichwillsendanemailmessage.TheQuickSendmethodletsyousendanemailwithaminimalamountofcode,anditsadvantageisitssimplicityandeaseofuse.SendMailalsosendsanmessagebutitdoesrequirethatcertainpropertiesandcollectionstobesetfirst.TheadvantageofSendMailisthatitincorporatesALLfeaturesofthecontrol.
TopostanarticletoanewsgroupyoucancallthePostArticlemethod.
TheProgIDofthecontrolis"Dundas.Mailer".
Mostmethodsofthiscontrolwillthrowanexceptionifanerroroccurs.Trapforthesuccess/failureofmailoperationsbyusinganOnErrorResumeNextstatementandexaminetheErrobjectafterafunctioncall.
SeeAlso:ProductOverview|HowtoUsetheDundasMailerControl|DundasUploadControl
ProductOverview(DundasMailerControl1.0)
Overview|Properties|Methods
TheDundasMailerControl1.0isafreecommercialemailcontrolwhichutilizestheSMTP,MIMEandNNTPprotocolstosendemailmessagesandpostnewsarticles.IthasbeendesignedforusewithinActiveServerPages(ASP)andcanbeusedbywebdevelopersorASPdeveloperstoquicklyandpainlesslyaddweb-basedemailcapabilitiestotheirASPapplications.
TheDundasUploadcontrol,whichalsoincorporatesanUploadProgresscomponentandaStateServerexecutable,canbeusedinconjunctionwiththeMailercontrolwhenworkingwithuploadedfilesinordertoprovidedeveloperswithweb-basedemailsolutionswhichfullysupportaweb-farmenvironment.
FeaturesListInstallation/RedistributionHowtousetheDocumentation
FeaturesList
ThefollowingisjustsomeofthefeaturesoftheDundasMailercontrol:
1. Choosebetweentextand/orhtml-basedemail.
2. Fullysupportsembeddedhtmlobjectswithinanhtml-basedemail(audiofiles,graphicsfiles,etc.).
3. Abilitytopostnewsarticlestonewsgroups.Youhavetheoptionofpostingtotherootdirectoryorasaresponsetoaparticulararticle.
4. SpecifymultiplerecipientsbyusingtheTOs,CCs,andBCCscollections.
5. Messageheadersandthemessagebodycanbesettonon-ASCIIvalues.
6. Validateyouremailaddressestosaveyourbandwidth.
7. SpecifymultipleSMTPandDNSserverstomakeyouremailoperationslightningquick.
8. Fullysupportstheuseofcustomheaders.
9. Optionallyprioritizesyourmessages.Youcanalsorequestconfirmationwhentheuserretrievesand/orreadsanemailmessage.
10. Sendmultipleattachmentswithyourmessages.
11. MSDNintegratedhtmlhelp.
Installation/Redistribution
ControlsandSamplesInstall
Thenameoftheinstallfileis:"AspMail.exe".
Thewindowsaccountunderwhichtheinstallrunsneedstohaveadministrativepriviledgesforasuccessfulinstallation.
Thefollowingfileswillbecopiedtotheselectedinstallationdirectory:
1)ASPpages:AutoResponse.asp,PostArticle.asp,PostArticle_Process.asp,SendMail.asp,SendMail_Process.asp,SendHtmlEmail.asp,SendHtmlEmail_Process.aspandError.asp.
2)VariousgraphicsfilesrequiredbytheASPpages(InstallDirectory/Images/).
3)ReadMe.htm.
Startmenuentriesareasfollows:
DundasSoftware|FreeProducts|MailerandUploadControls|ReadMe
DocumentationInstall
Touninstallthedocumentationruntheinstallfileagain(FPDocInst.exe)andchooseeither"RemoveFromMSDN"ifyouintegratedintotheMSDNor"RemoveAll"ifyoudidnotintegrateintotheMSDN.
HowtousetheDocumentation
DocumentationfortheMailercontrolconsistsofthefollowing:
1. Compiledhtmlhelp(optionallyintegratedintotheMSDN).Thehtmlhelpprovidesdetailedexplanationsforallmembersofthecontrolaswellasacontroloverview.Othertopicswhichshouldbeespeciallyusefulare:
HowtoUsetheDundasMailerControl
Overview(DundasMailerControl1.0)
QuickStart(DundasMailerControl1.0)
Tutorial1:SendinganEmailwithanAttachment
Tutorial2:SendinganHtmlEmailwithanEmbeddedImage
Tutorial3:PostingtoaNewsgroup
2. ReadMe.htm.ThisfileisdistributedwiththeMailercontrol,andconsistsofinstallationinformation,releasenotesandatroubleshootingsection.
HowtoUsetheDundasMailerControl
Overview|Properties|Methods
TheDundasMailerControlisafreefullycommercialemailcontrolwhichallowsyoutosendbothhtmlandtext-basedemailsaswellaspostarticlestonewsgroups.ItisusedinconjunctionwiththeDundasUploadControlwhendealingwithuploadedfiles,htmlembeddedobjectsandfileattachments.
Twomethodsareusedforsendinganemail:QuickSendandSendMail.RefertothesectionsbelowforadetailedexplanationonhowtousetheMailercontrolwitheitherofthesetwomethods.TopostarticlestonewsgroupsyoucanutilizethePostArticlemethod.SeeTutorial3:PostingtoaNewsGroupforfurtherdetails.
RefertothesectionbelowfordetailsonhowtousetheMailerandUploadcontrolstogether.YoucanalsoexamineTutorial1:SendinganEmailwithanAttachmentorTutorial2:SendinganHtmlEmailwithanEmbeddedImageforexamplesourceofthis.
NOTE:AllsendingmethodsutilizetheSMTPRelayServersandDNSServerscollections.Tomaximizethespeedofthemailoperationpopulatethesecollectionsbeforesendingtheemailmessage.
UsingQuickSend
1. CreateaninstanceoftheMailercontrol.TheProgIDofthecontrolis"Dundas.Mailer".
2. Optionallysetproperties(includingcollections)usedbytheQuickSendmethod.UnlikeSendMail(whichincorporatesallofthecontrol'sfunctionality)QuickSendonlyutilizessomeofthecontrol'spropertiesandcollections(allofwhichareoptional).SeeQuickSendforalistingoftheseproperties.
3. CallQuickSendtosendanemail.Noticethatthismethod's
argumentsareusedtosetanyrequiredmessageheaders.
4. Errortrapforthesuccess/failureoftheoperationbyusinganOnErrorResumeNextstatementandexamineVBScript'sErrobject(Err.Numberwillbeanon-zerovalueifanerroroccurred)immediatelyfollowingthefunctioncall.
5. DestroytheinstanceoftheMailercontrol.
Advantage-Letsyousendanemailwithaminimalamountofcoding.
UsingSendMail
1. CreateaninstanceoftheMailercontrol.TheProgIDofthecontrolis"Dundas.Mailer".
2. UnliketheQuickSendmethodSendMaildoesnotusefunctionargumentsatall.Itreliesonvariouspropertiesandcollectionstosetmessageheadersandothermessageelements(e.g.Bodyproperty,SMTPRelayServerscollection,TOscollection,TimeOutConnectproperty,etc.).ForthefunctioncalltosucceedyouMUSTspecifyadestinationaddressbyaddinganAddressobjecttooneofthefollowingcollections:TOs,CCs,orBCCs.UsetheAddmethodofthecollectionstodothis.
3. Onceyouhavespecifiedadestinationaddresssetanyotherproperties(collectionsincuded)thatyouwouldliketobeusedforthemailingoperation.
4. Errortrapforthesuccess/failureoftheoperationbyusinganOnErrorResumeNextstatementandexamineVBScript'sErrobject(Err.Numberwillbeanon-zerovalueifanerroroccurred)immediatelyfollowingthefunctioncall.
5. DestroytheinstanceoftheMailercontrol.
Advantage-AlthoughmorecodingisrequiredtosendanemailcomparedtoQuickSendtheSendMailmethodoffersyouatremendousamountofflexibiltyandoptionsforthemailingoperation.ItutilizesALL
properties/collectionsofthecontrol.
UsingtheUploadandMailerControls
UsetheDundasUploadcontroltosaveuploadedfilesandaccessformelements.OnceyouhavesavedtheuploadedfilestodiskyoucanthenaccessformelementsviatheFormcollection.YoucanalsoiteratethroughalluploadedfilesviatheUploadcontrol'sFilescollection,whichstoresUploadedFileobjects.
IfyouarejustsendinganattachmentwiththeemailthenaddtheuploadedfiletotheMailercontrol'sAttachmentscollection.UsetheUploadedFileobject'sPathpropertyastheFileNameargumentoftheAttachments.Addmethodcall.ThencalltheSendMailmethodtosendtheemailwiththeattachment.
ToembeduploadedfilesintoanhtmlemailloopthroughtheFilescollectionoftheUploadcontrolandaddtheUploadedFileobjectstotheHtmlEmbeddedObjscollection,andthenembedtheobjectbywrappingtheappropriatehtmltagsaroundtheobjectintheMailercontrol'sHtmlBodyproperty.YoucanusetheUploadedFileobject'sTagNamepropertytodeterminewhichfileinputboxtheobjectoriginatedfrom,andyoucanalsouseVBScripts'sInStrmethodinconjunctionwiththeUploadedFileobjectsContentTypepropertytodeterminethetypeoftheobject.Thisletsyoumakesurethatanobjectisnotembeddedintothehtmlbodyoftheemailwiththewrongtagsaroundit.
Therearefourtutorialswhichillustratethevarioussendmessageoperations:
QuickStart(Illustrateshowtosendanemailwithaminimumofcode).
Tutorial1:SendinganEmailwithanAttachment
Tutorial2:SendinganHtmlEmailwithanEmbeddedImage
Tutorial3:PostingtoaNewsgroup
QuickStart(DundasMailerControl1.0)
Overview|Properties|Methods
ThefollowingsourcecodedemonstrateshowtosendanemailwithboththeQuickSendandtheSendMailmethods.ThedifferencebetweenthetwomethodsisthatSendMailincorporatesallfunctionalityofthecontrol,whileQuickSendonlyutilizessomeofthecontrol'sproperties.PleasenotethatthissamplesendstheemailmessageswithaminimalamountofcodesonotalloftheMailercontrol'sfunctionalityisdemonstrated.
SendinganEmailwiththeQuickSendMethod<%'mostcontrolmethodsthrowanexceptionifanerroroccurssowewilluseanOnErrorstatementOnErrorResumeNext
DimobjMailer'Mailercontrol
'createinstanceofMailercontrolSetobjMailer=Server.CreateObject("Dundas.Mailer")
'sendemailobjMailer.QuickSend"[email protected]","[email protected]","Subject","Thisisthebody."'youcantestforthesuccess/failureoftheoperationbyexaminingVBScript'sErrobjecthere
SetobjMailer=Nothing%>
SendinganEmailwiththeSendMailMethod<%'mostcontrolmethodsthrowanexceptionifanerroroccurssowewilluseanOnErrorstatementOnErrorResumeNext
DimobjMailer'Mailercontrol
'createinstanceofMailercontrolSetobjMailer=Server.CreateObject("Dundas.Mailer")
'setMailercontrolpropertiesandcollectionitemsobjMailer.TOs.Add"[email protected]"objMailer.FromAddress="[email protected]"objMailer.Subject="Subject"objMailer.Body="Thisisthebody."
'sendemailobjMailer.SendMail'youcantestforthesuccess/failureoftheoperationbyexaminingVBScript'sErrobjecthere
SetobjMailer=Nothing%>
Tutorial1:SendanEmailwithanAttachment
Overview|Properties|Methods
ThefollowingsourcecodedemonstrateshowtosendanemailalongwithafileattachmentviaanASPpage.
Filesareuploadedbytheuserviafileinputelementsinaform(withanEncTypeof"multipart/form-data").ThentheDundasUploadControlisusedtosaveuploadedfilestodisk.OncethisisdonewetheniteratethroughalluploadedfilesviatheUploadcontrol'sFilescollectionandaddeachfiletotheMailercontrol'sAttachmentscollection.OnceallfileshavebeenaddedtothiscollectiontheemailissentwiththeSendMailmethodoftheMailercontrol.
Assumptions
AformwithanENCTYPEof"multipart/form-data"isPOSTINGdatatothisASPpage.
Theformcontainsoneormorefileinputelements(e.g.<inputtype="file"name="txtFile">
<%DimobjUpload'storesuploadcontrolinstanceDimobjEmail'storesmailercontrolinstanceDimstrPath'storespathoftheasppageDimIndex'countervariable
'functionswillthrowanexceptionifnotsuccessfulsoOnErrorResumeNextisusedforinlineerrortrappingOnErrorResumeNext
SetobjUpload=Server.CreateObject("Dundas.Upload")'UploadobjectSetobjEmail=Server.CreateObject("Dundas.Mailer")'Mailerobject
'createtemporarydirectorytostoreuploadedfiles(ifitdoesn'talreadyexist)
'atthesamedirectorylevelasthisasppagestrPath=Server.MapPath(".")&"\temp\"objUpload.DirectoryCreatestrPath
'savetheuploadedfilestothetempdirectory.'doingthispopulatestheUploadcontrol'scollections'notethatwecouldalsosavetomemorywiththeSaveToMemorymethodobjUpload.SavestrPath
'addanAddressobjecttotheTOscollection(thisspecifiesthedestinationaddress)objEmail.TOs.Add"[email protected]"
'specifythemessagesubjectobjEmail.Subject="SomeSubject"
'specifyanSMTPserver.DoingthisincreasesthespeedandreliabilityofthemailoperationobjEmail.SMTPRelayServers.Add"somesmtpserver.com"
'setthemessagebodyobjEmail.Body="Thisisthemessagebody"
'nowloopthroughalluploadedfiles(uploadedviafileinputboxes),andadd'eachuploadedfiletotheMailcontrol'sAttachmentscollection'NOTE:youcanuseeitheraForEachlooporastandardForloophereForEachIteminobjUpload.Files'Note:weareusingtheOriginalPathpropertyoftheUploadedFileobject'(whichcomposestheFilescollection)fortheContentNameargumentofeachAttachment'object.Thisletstherecipientoftheemailseetheoriginalfilenameoftheattachment,'(e.g.SomePicture.jpg)insteadofthenamebywhichtheattachmentwassavedas.Allfiles'whicharesavedtodiskhaveaGUIDprecedingtheoriginalfilenameusedforuniqueidentification.objEmail.Attachments.AddItem.Path,Item.OriginalPathNext
'nowsendtheemailobjEmail.SendMail
'testforsuccess/failureoftheSendMailoperationusingVBScript'sErrobjectIfErr.Number<>0Then'anerroroccurredsooutputtherelevanterrorstringResponse.Write"Thefollowingerroroccurred:"&Err.DescriptionElse'successful,sooutputasuccessmessagetouserResponse.Write"TheemailwassuccessfullyforwardedtothespecifiedSMTPserver."EndIf
SetobjEmail=Nothing'releaseresourcesSetobjUpload=Nothing%>
Tutorial2:SendinganHtmlEmailwithanEmbeddedImage
Overview|Properties|Methods
Filestobeembeddedareuploadedbytheuserviafileinputelementsinaform(withanEncTypeof"multipart/form-data").ThentheDundasUploadControlisusedtosaveuploadedfilestodiskwithitsSavemethod(wecouldalsosavedirectlytomemoryaswell).OncethisisdonewecantheniteratethroughalluploadedfilesviatheUploadcontrol'sFilescollectionandchecktoseeifvalidfiletypeswereuploadedforeachfileinputelement(letsassumethattherearetwofileinputboxes,oneforanimagefileandtheotherforanaudiofile).IfavalidfiletypewasuploadedweaddthefiletotheMailercontrol'sHtmlEmbeddedObjscollection,andthenembedtheobjectintotheMailercontrol'sHtmlBodyproperty.WhenweembedtheobjectintotheHtmlBodypropertywe"wrap"theappropriatetagsaroundtheobjecttobeembeddedandidentifyitbyusingthecontentID(cid).WethencontinueloopingthroughtheFilescollection.OncetheobjectshavebeenaddedtotheHtmlEmbeddedObjscollectiontheemailissentviatheSendMailmethodoftheMailercontrol.
PleasenotethatyouCANNOTuseASP'sRequestobjecttoretrieveformelementvalueswhentheENCTYPEoftheformis"multipart/form-data".ToretrieveformvaluesyouMUSTcalltheSavemethodoftheUploadcontrol.NotonlydoesthissavetheuploadedfilestodiskbutitalsopopulatestheUploadcontrolscollections,therebylettingyouaccessformelementswiththeUploadcontrol'sFormcollection(e.g.strToAddress=objUpload.Form("txtTO")).
Assumptions
AformwithanENCTYPEof"multipart/form-data"isPOSTINGdatatothisASPpage.
Theformcontainstwo(2)fileinputelementsnamed"txtAudio"and"txtImage"(e.g.<inputtype="file"name="txtAudio">).
<%DimobjUpload'storesanUploadcontrolobjectDimobjEmail'storesaMailercontrolobjectDimstrPath'storespathtoadirectorywecreateatsamelevelasthisASPpage
'TheSendMailfunctionwillthrowanexceptioniftheoperationis'unsuccessful,soweenableinlineerrortrappingOnErrorResumeNext
SetobjUpload=Server.CreateObject("Dundas.Upload")'UploadobjectSetobjEmail=Server.CreateObject("Dundas.Mailer")'Mailerobject
'createadirectoryatsamelevelasthisASPpage'thisdirectoryisusedtostoretheuploadedfiles(whicharerenamedwithaGUIDpreceding'theoriginalfilename)'NOTE:todeletethesefilesyouwouldhavetousetheImpersonateUser'theUploadcontrolsincetheIUSR_accountSHOULDNOThavepermissiontodeletefilesstrPath=Server.MapPath(".")&"\temp"objUpload.DirectoryCreatestrPath
'savetheuploadedfiles.THISPOPULATESTHEUPLOADCONTROL'SCOLLECTIONS!objUpload.SavestrPath
'specifytherecipientofthismessageobjEmail.TOs.Add"[email protected]"
'specifythesubjectoftheemailobjEmail.Subject="Thisisthesubject."
'specifythesenderofthemessageobjEmail.FromAddress="[email protected]"
'specifyanSMTPRelayserver.ThisincreasesthespeedandreliabilityoftheoperationobjEmail.SMTPRelayServers.Add"SomeSmtpServer.com"
'initializetheHtmlBodyproperty,we'llthrowaheaderintoitobjEmail.HTMLBody="<Html><Head></Head><Body><H2>Thisisthebody.</H2><BR><BR>"
'nowletsloopthroughtheuploadedfilestobeembedded.ForEachIteminobjUpload.Files'wewillchecktoseewhichfileinputelementisresponsiblefortheuploadedfileIf(Item.TagName="txtAudio")Then'wenowknowthefilecamefromthetxtAudiobox,butletsmakesurethat'theuseractuallyuploadedsomesortofaudiofilebyusingInStrandtheContentTypepropertyIfInStr(1,Item.ContentType,"audio")Then'thefileisactuallyanaudiotype,soaddittotheHtmlEmbeddedObjscollection'andembeditintotheHtmlBodyproperty.NotethatwesettheContentNameargument'oftheHtmlEmbeddedObjtotheOriginalPathpropertyoftheuploadedfilesothat'iftheclientemailsoftwaredisplaysthenameofthefilethefilenamewillbeuser-friendly'AlsonotethatweMAKESUREthattheIDfortheembeddedobjectisunique!!objEmail.HtmlEmbeddedObjs.AddItem.Path,1,Item.OriginalPathobjEmail.HtmlBody=objEmail.HtmlBody&"<BGSoundsrc=cid:1></BGSound>"EndIfEndIfIf(Item.TagName="txtImage")Then'letsmakesureuseruploadedavalidimagefileIfInStr(1,Item.ContentType,"image")ThenobjEmail.HtmlEmbeddedObjs.AddItem.Path,2,Item.OriginalPathobjEmail.HtmlBody=objEmail.HtmlBody&"<IMGSRC=cid:2>"EndIfEndIfNext
'finishhtmlbodybyaddingclosinghtmltagsobjEmail.HTMLBody=objEmail.HTMLBody&"</body></html>"
'sendtheemailobjEmail.SendMail
'testforsuccess/failureIfErr.Number<>0Then'anerroroccurredsooutputerrormessage
Response.Write"Sorry,thefollowingerroroccurred:"&Err.DescriptionElse'success!Response.Write"Thehtmlemailwassuccessfullysent."EndIf
'releaseresourcesSetobjEmail=NothingSetobjUpload=Nothing%>
Tutorial3:PostingtoaNewsgroup
Overview|Properties|Methods
Thefollowingsourcecodedemonstrateshowtopostanarticletoaspecifiednewsgroupatanewsserver.
WecreateaninstanceoftheDundasMailerControl,settheFromAddressproperty(usedastheReplyToaddressiftherearenoAddressobjectsintheReplyTOscollection)andthensettheBodypropertywhichconstitutesthearticlebody.Forthisdemonstrationwewillpostanarticleinreplytoanexistingarticlewhichweread.Topostourarticleunderneathanexistingarticle(asopposedtopostingtotherootdirectory)wewilladdacustomheadernamed"References"totheMailercontrol'sCustomHeaderscollection,andsetitsvaluetotheIDofthearticlewearerespondingto.
<%DimobjEmail'storesinstanceofMailerobject
'PostArticlethrowsanexceptionifitisnotsuccessfulsoweuse'inlineerrortrappingwithanOnErrorResumeNextstatementOnErrorResumeNext
'createinstanceofMailercontrolSetobjEmail=Server.CreateObject("Dundas.Mailer")
'specifyanSMTPservertoincreasethespeedandreliabilityoftheoperationobjEmail.SMTPRelayServers.Add"SomeSmtpServer.com"
'setthesubjectofthearticleobjEmail.Subject="Thisisthearticlesubject."
'addacustomheadernamed"References"totheCustomHeaderscollection,setting'thevalueoftheheadertotheIDofthearticletopostbeneath(respondto)objEmail.CustomHeaders.Add"References","TheArticleID"
'setthebodyofthearticleobjEmail.Body="Thisisthebodyofthearticle."
'settheFromAddress(ThisisusedastheReplyToaddressifarenoAddress'objectsintheReplyTOscollection)objEmail.FromAddress="[email protected]"
'nowattempttopostthearticle(wewilluseapublicMicrosoftnewsgrouphere)objEmail.PostArticle"msnews.microsoft.com","microsoft.a.test"
'nowtrapforsuccess/failureofthearticlepostingIfErr.Number<>0Then'PostArticlefailed.Response.Write"Thefollowingerroroccurred:"&Err.DescriptionElse'PostArticlesucceededResponse.Write"Thearticlewassuccessfullyposted."EndIf
SetobjEmail=Nothing%>
ObjectHierarchy(DundasMailerControl1.0)
Overview|Properties|Methods
NOTE:Theyellowrectanglesrepresentcollectionswhilethebluerectanglesrepresentobjects.
SeeAlso:Overview(DundasMailerControl1.0)|HowtoUsetheDundasMailerControl
TroubleshootingtheMailerControlDemos
TheuninstalldoesnotremovetheUploadControl.dllandDSMailer.dll
Theinetinfo.exeprocessmaybereferencingthedllsduringtheuninstallprocess.Rebootyourcomputerandremovethedllsmanually.
Objectvariablenotset
Thiswilloccurasaresultofreferencingacollectionitemwhichdoesnotexist(e.g.usingtheFormcollectiontoreferenceacheckboxwhichisnotchecked).
Torectifythiserrorchecktomakesurethattheitemyouarereferencinginthecollectionhasthecorrectspelling.Totestforanemptycheckboxusethefollowinglineofcode:"IfobjUpload.Form("chkMyCheckbox")IsNothingThen...Else...EndIf".
TherelevantErr.Numberwillbe"91".
Server.CreateObjectfailed.Invalidclassstringspecified
ThespecifiedProgIDofeithertheMailerorUploadcontrolisincorrect.TheProgIDoftheMailercontrolis"Dundas.Mailer",andtheProgIDoftheUploadcontrolis"Dundas.Upload".
Thiscanalsobecausedbyacontrolwhichisnotregistered.Registerthecontrolinquestionbyusingregsvr32.exe.
HTTPError403Forbidden:ExecuteAccessForbidden
YouhavenotsetupthepermissionsforyourASPfilescorrectly.UseWindowsExplorertosetupproperNTFSdirectorypermissionsifyouarerunningWinNTorWin2000(Readaccessisrequired),andalsomakesurethattheWebpermissionssetinMMC(MicrosoftManagementConsole)areatleastReadwithScriptExecuterights.AlsomakesurethattheSamples/ImagesfolderhasReadpermissionsaswell.
HTTPError404FileNotFound
TheURLyouarespecifyinginyourbrowserisincorrect.DeterminewhereyourASPpagesareandentertheappropriateURL(e.g.http://127.0.0.1/RelativePathFromRootWebDirectory/PostArticle.ASP).
AccessisDenied
Theappropriatepermissionshavenotbeensetupforthedeletionoffilesorfolders.Youneedtoeithergivethedefaultwebaccount(usuallyIUSR_MACHINENAME)FullControlNTFSpermissionforthefolderinquestionoryoucanusetheImpersonateUsermethodoftheUploadcontroltoutilizeauseraccountwhichdoeshavetherighttodeletefiles/folders.
VBSCriptRunTimeError"800a01ad"ActiveXcomponentcannotcreateobject
EithertheUploadControl.dllorDSMailer.dlldoesnothavetheappropriatepermissions.MakesurethatthedefaultwebaccounthasFullControlrightsforbothdll's.
Error"800a001e"Arequiredpriviledgeisnotheldbytheclient
ThisisprobablycausedbycallingtheImpersonateUsermethodoftheUploadcontrolinconjunctionwiththe"RuninSeparateMemorySpace"boxbeingcheckedinyourHomeDirectoriespropertypage(foundintheMicrosoftManagementConsole,orMMC).Togetaroundthisyoucaneithergrantthedefaultwebaccount"ActasPart
oftheOperatingSystem"priviledgesoralternativelyyoucanjustturnoffthe"RuninSeparateMemorySpace"option.RefertoeithertheMSDNortheFreeProgramsDocumentation(examinetheImpersonateUsertopic)fordetailsonhowtograntoperatingsystempriviledges.
DundasMailerControl1.0Properties
Copyright©DundasSoftwareLtd.2000,AllRightsReserved.
Overview|Properties|Methods
Body Thetext-basedbodyoftheemail.NotusedwiththeQuickSendmethod.
BodyCharSet Thecharactersettobeusedfortheemail'stext-basedbody.
ConfirmRead IfthisissettoTRUEandtherecipient'sserversupportsthisfeaturethenaconfirmationemailwillbesenttothesuppliedFromaddresswhentheemailisreadbytherecipient.
FromAddress Theemailaddressofthepersonsendingtheemail.
FromName Thenameoftheemailsender.ThisisthenamewhichsometimesappearsbeforetheemailaddressofthesenderintheFromfield.
HtmlBody Usethispropertytospecifythebodyoftheemailinhtmlformat.NotusedwiththeQuickSendmethod.
HtmlBodyCharSet Thecharactersettobeusedfortheemail'shtml-basedbody.
Organization Theorganizationsendingtheemail.
Priority Thepriorityratingoftheemail.
ReturnReceipt IfthisissettoTRUEandtherecipient'sserversupportsthisfeaturethenaconfirmationemailwillbesenttothesuppliedFromaddresswhentheemailisretrievedbytherecipient.
Subject Thesubjectfieldoftheemail.NotusedwiththeQuickSendmethod.
TimeOutConnect Theconnectiontimeoutvalue.
TimeOutReceive Thereceivetimeoutvalue.
TimeOutSend Thesendtimeoutvalue.
CollectionProperties
Attachments CollectionofAttachmentobjects,specifyingtheattachmentstobesentwiththeemail(notusedbytheQuickSendmethod).
CustomHeaders CollectionofCustomHeaderobjects,specifyingthecustomheaderstobeaddedtotheemail(notusedbytheQuickSendmethod).
DNSServers CollectionofDNSServerobjects,specifyingtheDNSserver(s)tobeused.Improvesthespeedandefficiencyofthemailoperation.
HtmlEmbeddedObjs CollectionofHtmlEmbeddedObjobjects,specifyingtheobjectswhichareembeddedintotheHtmlBodyoftheemail.Notusedbythe
QuickSendmethod.
SMTPRelayServers CollectionofSMTPRelayServerobjects,specifyingtheSMTPserver(s)tobeused.Improvesthespeedandefficiencyofthemailoperation.IfnoSMTPserversareusedthentheemailissentusingDirectSend.
TOs CollectionofAddressobjects,specifyingtherecipientsoftheemail(notusedbytheQuickSendmethod).
CCs CollectionofAddressobjects.ThisspecifiestheCCrecipientsoftheemail.NotusedbytheQuickSendmethod.
BCCs CollectionofAddressobjects.ThisspecifiestheBCCrecipientsoftheemail.NotusedbytheQuickSendmethod.
ReplyTOs CollectionofAddressobjects.Thisspecifiestheaddressestobeusedformessagereplies.NotusedbytheQuickSendmethod.
Body(DundasMailerControl1.0)
Overview|Properties|Methods
Determinesthebodyoftheemail(unlessyouarecallingtheQuickSendmethod).
Syntax
MailerObject.Body=[string]
TheBodypropertysyntaxhasthefollowingparts:
Part Description
string Astringexpressionwhichdeterminesthebodyoftheemail.
Remarks
Setthispropertytospecifythebodyofanemailmessage.
TheQuickSendmethoddoesnotusethisproperty.
Pleasenotethatthemaximumallowablesizeoftheemailbodyis32Kb.
NOTE:ifyousetboththeBodypropertyandtheHtmlBodypropertybeforesendingthemessagethenthetypeofbodydisplayedisdependentonthedefaultsettingsoftherecipient'semailsoftware.IftherecipientdefaultstohtmlemailthenthebodydisplayedwillbedeterminedbytheHtmlBodyproperty.However,iftherecipient'semailprogramdefaultstotext-basedemailthentheBodypropertydeterminesthebodyofthemessage.
SeeAlso:SendMail
BodyCharSet(DundasMailerControl1.0)
Overview|Properties|Methods
Thispropertydeterminesthecharactersettobeusedforthetext-basedbodyoftheemail.
Syntax
MailerObject.BodyCharSet=[string]
TheBodyCharSetpropertysyntaxhasthefollowingparts:
Part Description
string Anyvalidcharacterset.Defaultsto"US-ASCII".
Remarks
Usethispropertytoselectacharactersetforthemessagebody.ThevalueofBodyCharSetisusedinconjunctionwiththeBodypropertywhichdeterminesthetext-basedbodyoftheemail.AlternativelyyoucansettheBodyCharSetpropertyandloadthemessagebodyfromfileviatheLoadBodyFromFilemethod.
Toselectacharactersetforanhtml-basedemailusetheHtmlBodyCharSetproperty.
SeeAlso:Body
ConfirmRead(DundasMailerControl1.0)
Overview|Properties|Methods
IfthispropertyissettoTRUEandtherecipient'suseragent(emailsoftware)supportsthisfeaturethenaconfirmationemailwillbesentwhentheemailisreadbytherecipient.
Syntax
MailerObject.ConfirmRead=[boolean]
TheConfirmReadpropertysyntaxhasthefollowingparts:
Part Description
boolean SetthistoTRUEtorequestconfirmationthattheemailhasbeenread.DefaultstoFALSE.
Remarks
IfConfirmReadissettoTRUEandthisfeatureisalsosupportedbytheclient'suseragentthenanoticewillbesentbacktotheaddressintheemail'sFromheaderconfirmingthattheemailhasbeenread.
NOTE:MakesureyousupplyavalidemailaddressfortheFromfieldwhensendingthemessage,sinceitistheaddressintheFromheaderwhichdetermineswheretheconfirmationreplyissent.IfyouareusingSendMailthenensurethattheFromAddresspropertyhasbeensetbeforesendingtheemail.IfyouareusingtheQuickSendmethodmakesurethatyousupplythecorrectemailaddressfortheFromargument.
Thispropertycanbeusedinconjunctionwithallmethodswhichsendanemail.
ThePostArticlemethoddoesnotutilizetheConfirmReadproperty.
Microsoft'sOutlooksupportsthisfeature,whileOutLookExpressdoesnot.
SeeAlso:ReturnReceipt
FromAddress(DundasMailerControl1.0)
Overview|Properties|Methods
Theemailaddressofthemessagesender.
Syntax
MailerObject.FromAddress=[string]
TheFromAddresspropertysyntaxhasthefollowingparts:
Part Description
string Theemailaddressthemessageisbeingsentfrom.Defaultstoazero-lengthstring.
Remarks
IftheFromNamepropertyisazero-lengthstringthenthisFromAddresspropertydeterminesthecontentsoftheFromheader,andwhentheclientreadsthemessagethisemailaddresswillbewhatappearsintheclientsoftware'sFromfield([email protected]).
IftheFromNamepropertyhasbeensetthenboththeFromNameandFromAddresspropertiesmakeuptheFromheaderoftheemail.WhentheclientreadsthemessagetheFromfieldwillthencontaineitherbothproperties(e.g.JohnDoe<[email protected]>)orjusttheFromNamevalue,dependingontheclient'suseragent.
AlthoughthispropertydoesnothavetobesetwhenusingSendMail(thefunctioncallswillnotfail)wehighlyrecommendthatyoudospecifyavalidemailaddressforFromAddress.
NOTE:YouMUSTsetthispropertyifyouwanttouseeithertheConfirmReadpropertyortheReturnReceiptproperty.
IftheReplyTocollectionhasnoitemsinitthentheaddressusedforrepliesisretrievedfromthisFromAddressproperty.YouMUSTSETtheFromAddresspropertywhenpostinganarticlewiththePostArticlemethod.
SeeAlso:FromName
FromName(DundasMailerControl1.0)
Overview|Properties|Methods
Thenameoftheemailsender.
Syntax
MailerObject.FromName=[string]
TheFromNamepropertysyntaxhasthefollowingparts:
Part Description
string Nameofthepersonsendingthemessage.Defaultstoazero-lengthstring(optional).
Remarks
TheFromAddresspropertyMUSTbesetifyouwanttouseFromName.
IftheFromNamepropertyisazero-lengthstringthentheFromAddresspropertydeterminesthecontentsoftheFromheaderoftheemail,andwhentheclientreadsthemessagethisemailaddresswillbewhatappearsintheclientsoftware'sFromfield([email protected]).
IftheFromNamepropertyhasbeensetthenboththeFromNameandFromAddresspropertiesmakeuptheFromheaderoftheemail.WhentheclientreadsthemessagetheFromfieldwillthencontaineitherbothproperties(e.g.JohnDoe<[email protected]>),orthevalueofFromName,dependingontheclient'suseragent.
SeeAlso:FromAddress
HtmlBody(DundasMailerControl1.0)
Overview|Properties|Methods
Thehtmlbodyofthemessage.
Syntax
MailerObject.HtmlBody=[string]
TheHtmlBodypropertysyntaxhasthefollowingparts:
Part Description
string Astringexpressioncontaininghtmlcodewhichconstitutesthebodyoftheemail.
Remarks
Usethispropertytosendthebodyoftheemailinanhtmlformat.
UsinghtmlforthebodyofyouremailallowsyoutoembedhtmlobjectsintoyourmessagebodyviatheHtmlEmbeddedObjscollection.
ItisalsopossibletosettheemailbodybyusingtheLoadBodyFromFilemethod.JustmakesurethattheappropriatehtmltagsareincludedintheASCIIfile.
TheHtmlBodypropertyMUSTCONTAINallstandardhtmlheadersthatanyhtmlpagewouldcontain(e.g.<html><head></head><body></body></html>).ItistheresponsiblityofthedevelopertosupplythesetagswhensettingtheHtmlBodyproperty.
TheQuickSendmethodcanonlysendtext-basedemail.YoumustuseSendMailinordertosendanemailwithanhtmlbody.
IfyousetboththeBodypropertyandtheHtmlBodypropertybeforesendingthemessagethenthetypeofbodydisplayedisdependentonthedefaultsettingsoftheclient'semailsoftware.IftheclientdefaultstohtmlemailthenthebodydisplayedwillbedeterminedbytheHtmlBodyproperty.However,iftheclient'semailprogramdefaultstotext-basedemailthentheBodypropertydeterminesthebodyofthemessage.
Notethatyouwillneedtoreplaceanycarriagereturn/linefeedcharacterswith<br>or<p>tagsfromtextgatheredwithtextboxesifyouwanttodisplaytheemailbodyonmorethanoneline.
ThePostArticlemethodcanalsousehtmlbutwestronglydiscouragethispractice.ManyserversWILLNOTacceptarticlesinanhtmlformat.
Themaximumallowablesizeoftheemailbodyis32Kb.
RefertoTutorial2:SendinganHtmlEmailwithanEmbeddedImageforexamplesourcecodeonsendinganhtmlemail.
SeeAlso:Body|DundasUploadControl|HtmlEmbeddedObjsCollection
HtmlBodyCharSet(DundasMailerControl1.0)
Overview|Properties|Methods
Thispropertydeterminesthecharactersettobeusedforthebodyofanhtml-basedemail.
Syntax
MailerObject.HtmlBodyCharSet=[string]
TheHtmlBodyCharSetpropertysyntaxhasthefollowingparts:
Part Description
string Anyvalidcharacterset.DefaultstoUS-ASCII.
Remarks
Usethispropertytoselectacharactersetforthemessagebody.ThevalueofHtmlBodyCharSetisusedinconjunctionwiththeHtmlBodypropertywhichdeterminesthehtml-basedbodyoftheemail.AlternativelyyoucansettheHtmlBodyCharSetpropertyandloadthemessagebodyfromfileviatheLoadBodyFromFilemethod(makesurethatthetextfilehastheappropriatehtmltagsinit).
Toselectacharactersetfortext-basedemailusetheBodyCharSetproperty.
SeeAlso:HtmlBody
TimeOutConnect(DundasMailerControl1.0)
Overview|Properties|Methods
Retrievesorsetstheconnectiontimeoutvalueinseconds.
Syntax
MailerObject.TimeOutConnect=[long]
TheTimeOutConnectpropertysyntaxhasthefollowingparts:
Part Description
long Anypositivelongexpression.Thetimetowaitforaconnectiontobeestablishedbeforecancellingtheoperation.Defaultsto30seconds.
Remarks
Youcanincreasethisvalueifyourconnectionattemptstotheservercontinuallytimeout.
NotethatthistimeoutvalueismultipliedifyouspecifymorethanoneSMTPorDNSservers.Inotherwords,thetimeoutvalueisappliedonaperconnectionattemptbasis.
SeeAlso:TimeOutReceive|TimeOutSend
Organization(DundasMailerControl1.0)
Overview|Properties|Methods
ThispropertydeterminesthecontentsoftheOrganizationheaderoftheemail,indicatingtheorganizationthemessagewassentfrom.
Syntax
MailerObject.Organization=[string]
TheOrganizationpropertysyntaxhasthefollowingparts:
Part Description
string Theorganizationthemessagewassentfrom.Defaultstoazero-lengthstring.
Remarks
ThismethodaddsanOrganizationheaderwhichdescribestheorganizationtowhichthesenderbelongs,ortowhichthemachinebelongs.Theintentofthisheaderistohelpidentifythepersonpostingthemessage,sincehostnamesareoftensocrypticthatitisdifficulttodeterminetheorganizationwhichsentthemessage.
SeeAlso:FromAddress|FromName
Priority(DundasMailerControl1.0)
Overview|Properties|Methods
Thispropertydeterminesthepriorityofthemessage.
Syntax
MailerObject.Priority=[integer]
ThePrioritypropertysyntaxhasthefollowingparts:
Part Description
integer Prioritylevelofthemessage,rangingfromone(1)tofive(5).Oneisthehighestprioritywhilefiveisthelowestpriority.Defaultsto-1(nopriorityrating).
Remarks
PrioritydeterminesthecontentsoftheX-Priorityheaderoftheemail.Ifthevalueofthispropertyis-1thentheemailmessagewillnotcontaintheX-Priorityheader.
Theuseofthisheaderdependsontheclientemailsoftwarebeingusedbytherecipientofthemessage.Forexample,OutlookExpressassignsspecialiconstomessagesofhighpriorityandlowpriority.
Usuallyapriorityof1or2willbeindicatedashighprioritywhile4or5willbeindicatedasalowpriority.
ReturnReceipt(DundasMailerControl1.0)
Overview|Properties|Methods
IfthispropertyissettoTRUEandtheclient'suseragent(emailsoftware)supportsthisfeaturethenconfirmationwillbesenttotheaddressintheemail'sFromheaderwhentheemailisretrievedbytherecipient.
Syntax
MailerObject.ReturnReceipt=[boolean]
TheReturnReceiptpropertysyntaxhasthefollowingparts:
Part Description
boolean SetthistoTRUEtorequestconfirmationthattheemailhasbeenretrievedbytherecipient.DefaultstoFALSE.
Remarks
IfReturnReceiptissettoTRUEandthisfeatureisalsosupportedbytheclient'suseragentthenanoticewillbesentbacktotheaddressintheemail'sFromheaderconfirmingthattheemailhasbeenretrievedbytherecipient.
NOTE:MakesureyousupplyavalidemailaddressfortheFromfieldwhensendingthemessage,sinceitistheaddressintheFromheaderwhichdetermineswheretheconfirmationreplyissent.IfyouareusingSendMailensurethattheFromAddresspropertyhasbeensetbeforesendingtheemail.IfyouareusingtheQuickSendmethodmakesurethatyousupplythecorrectemailaddressfortheFromargument.
ThispropertycanbeusedinconjunctionwithALLmethodswhichsendanemail.PostArticle,however,doesnotutilizetheReturnReceiptproperty.
Microsoft'sOutlooksupportsthisfeature,whileOutLookExpressdoesnot.
SeeAlso:ConfirmRead
Subject(DundasMailerControl1.0)
Overview|Properties|Methods
UsethispropertytosettheSubjectfieldofyourmessageifyouarenotusingtheQuickSendmethodtosendtheemail.
Syntax
MailerObject.Subject=[string]
TheSubjectpropertysyntaxhasthefollowingparts:
Part Description
string Astringexpressiondescribingthesubjectmatteroftheemail.
Remarks
UsethispropertytosettheSubjectfieldoftheemailifyouareusingtheSendMailmethodtosendtheemailmessage.TheQuickSendmethodsetstheSubjectfieldviaitsSubjectargument.
Westronglyrecommendthatyousetthispropertybeforesendinganemail.
SeeAlso:Body|HtmlBody
TimeOutReceive(DundasMailerControl1.0)
Overview|Properties|Methods
Usethispropertytoretrieveorsetthereceivetimeoutvalue.
Syntax
MailerObject.TimeOutReceive=[long]
TheTimeOutReceivepropertysyntaxhasthefollowingparts:
Part Description
long Theamountoftime(inseconds)towaitforareplyfromtheSMTPserver.Defaultsto30seconds.
Remarks
Youcanincreasethispropertyifarequestedmailoperationcontinuallytimesoutonyou.
SeeAlso:TimeOutConnect|TimeOutSend
TimeOutSend(DundasMailerControl1.0)
Overview|Properties|Methods
Usethispropertytoretrieveorsetthesendtimeoutvalue.
Syntax
MailerObject.TimeOutSend=[long]
TheTimeOutSendpropertysyntaxhasthefollowingparts:
Part Description
long Theamountoftime(inseconds)thatamessagewillwaittobesentbeforetheoperationtimesout.
Remarks
Thispropertysettingdetermineshowlongthemessagewillwaitinthequeuebeforethesendmailoperationtimesout.
SeeAlso:TimeOutConnect|TimeOutReceive
DundasMailerControl1.0Methods
Copyright©DundasSoftwareLtd.2000,AllRightsReserved.
Overview|Properties|Methods
EncodeHeader Usethismethodtoencodeanhtmlheader.Usefulfornon-ASCIIheadervalues.
LoadBodyFromFile Loadsthemessagebodyfromafile.
QuickSend Sendsanemailwithouthavingtosetanypropertiesorcollections.
PostArticle Callthismethodtopostanarticletoanewsgroup.
SendMail Sendsanemail.UnlikeQuickSendthisdoesnotuseanyarguments,soyoumustsetpropertiesandcollectionsbeforecallingthismethod.
ValidateAddress Callthisfunctionifyouwanttovalidateanemailaddress.
EncodeHeader(DundasMailerControl1.0)
Overview|Properties|Methods
Usethismethodtoencodeanhtmlheader.Usefulfornon-US-ASCIIheadervalues.
Syntax
[string]=MailerObject.EncodeHeader(TextAsString,CharSetAsString,[EncodingAsLong=0])
TheEncodeHeadermethodsyntaxhasthefollowingparts:
Part Description
Text Thestringvalueoftheheaderwhichistobeencoded.
CharSet Thecharactersettobeusedfortheheader.
Encoding Optional.Thetypeofencodingtobeused,eitherBASE64(1),orQUOTEDPRINTABLE(0).Defaultsto0.
string Theencodedversionoftheheader.
ReturnValues
AstringexpressionwhichistheencodedvalueoftheTextargument.
Remarks
ThismethodletsyouspecifycharactersetsotherthanthestandardUS-ASCIIcharactersetforthemessageheaders.ThisisparticularlyusefulforsettingtheSubjectheaderandtheFromNamecomponentoftheFromheadertonon-Englishvalues.
Touse"QuotedPrintable"encodingsettheEncodingargumenttozero(0)orusethedefaultvalue.TouseBASE64encodingspecifyavalueofone(1)fortheEncodingargument.
UseeitherBodyCharSetorHtmlBodyCharSettospecifyanon-"US-ASCII"charactersetforthemessagebody.
SeeAlso:CustomHeaderObject|CustomHeadersCollection|AddMethod(CustomHeaderscollection)
LoadBodyFromFile(DundasMailerControl1.0)
Overview|Properties|Methods
Callthismethodtoloadthemessagebodyfromanytextfile.LoadBodyFromFilecanbeusedforbothtext-basedandhtml-basedemails.
Syntax
MailerObject.LoadBodyFromFile(FileNameasstring,[HtmlTextasboolean=False])
TheLoadBodyFromFilemethodsyntaxhasthefollowingparts:
Part Description
FileName Thefullpathnameofthefiletoloadintothemessagebody.
HtmlText IfTRUEthenthefilecontentsareloadedintotheHtmlBodyproperty,otherwisethefilecontentsareloadedintotheBodyproperty(text-based).DefaultstoFALSE.
Remarks
Usethismethodtoloadthemessagebodyfromfile.ThefilecanbeanyvalidASCIIfile(e.g..htmand.txtfiles).
Anexceptionisthrownifanerroroccurs.Trapforthesuccess/failureoftheoperationbyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifanerroroccurred).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
IfyouusethismethodtosettheHtmlBodypropertythenitisuptoyou
tomakesurethattheASCIIfilecontainsallnecessaryhtmltags(e.g.<html>,<body>,etc.).
SeeAlso:Body|HtmlBody
PostArticle(DundasMailerControl1.0)
Overview|Properties|Methods
Callthismethodtopostanarticletoanewsgroup.Youcanposttoeithertherootofthearticlelistingorbeneathanexistingarticle.
Syntax
MailerObject.PostArticle(Serverasstring,[Groupasstring="",UserNameasstring="",Passwordasstring="",Portaslong=119])
ThePostArticlemethodsyntaxhasthefollowingparts:
Part Description
Server Thenameoftheservertopostthearticleto(e.g.msnews.microsoft.com),oritscorrespondingIPaddress.
Group Thenameofthenewsgrouptopostthearticleto.Defaultstoazero-lengthstring.
UserName Usernameofthenewsgroupaccount(usuallynotrequiredbynewsgroups).Defaultstoazero-lengthstring.
Password Passwordofthenewsgroupaccount(usuallynotrequiredbynewsgroups).Defaultstoazero-lengthstring.
Port Theporttobeusedwhenpostingthearticle.Defaultstoport119.
Remarks
Anexceptionisthrownifanerroroccurs.Trapforthesuccess/failureoftheoperationbyexaminingVBScript'sErrobjectimmediatelyaftercalling
thismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifanerroroccurred).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
ThematerialtobepostedisdeterminedbytheBodyproperty(youcanalternativelyusetheHtmlBodypropertybutnotallnewsserverssupporthtml-basedarticles).PostArticleusesallpropertiesoftheMailercontrolexceptfortheoneslistedbelow:
Priority
ReturnReceipt
ConfirmRead
TOscollection
CCscollection
BCCscollection
DNSServerscollection,and
SMTPRelayServerscollection
YouMUSTspecifythenameoftheserverthearticleistobepostedto.YoucanthensettheGroupargumenttothenameofthenewsgrouptoposttooralternativelyyoucanleavethisasazero-lengthstringandthenaddthe"Group"customheadertotheCustomHeaderscollection.Setthevalueofthiscustomheadertothenameofthenewsgrouptopostto.
IftherearenoitemsintheReplyTOscollectionthentheFromAddresspropertydeterminestheaddresstobeusedforreplies.YouwillalsoHAVETOsettheBodypropertybeforesendingthearticle.Ifyoutrytopostan"empty"articleatrappableerrorwilloccur.
YoucanposttomorethanonegroupbyspecifyingmultiplenewsgroupsfortheGroupargumentandthenseparatingthemultipleentrieswithcommas.IfyouareusingtheCustomHeaderscollectiontospecifythe
newsgroupsthenjustaddthenamesofthedesirednewsgroupstothiscollection.
Youalsohavetheoptionofpostingeithertotherootofthenewsarticlelisting(thedefault)oryoucanpostyourarticlesothatitappearsbelowanexistingarticle.TohaveyourarticleappearasanodeofanexistingarticleyouhavetoknowtheMessageIDofthedesired"root"article.IfyouknowtheMessageIDyoucanaddacustomheadernamed"References"totheCustomHeaderscollection.SetthiscustomheadertotheMessageIDofthedesired"root"article.WhenthePostArticlemethodexecutesitlooksintheCustomHeaderscollectionforthe"References:"headerandifthisheaderexiststhearticleispostedbeneaththearticlespecifiedbytheMessageID.
TheUserNameandPasswordargumentsareonlyrequiredifthenewsgroupyoubelongtorequiresauthentication(whichisusuallynotthecase).
Touseanoptionalparameterwithoutspecifyinganyvaluesforpreviousoptionalparametersjustenterconsecutivecommasforthemissingarguments.Forexample,"PostArticle("someserver.com",,,,323)"isavalidfunctioncall.
ForexamplesourcecodeillustratinghowtopostanewsatricleseeTutorial3:PostingtoaNewsgroup.
SeeAlso:CustomHeadersCollection|AddMethod(CustomHeaderscollection)
QuickSend(DundasMailerControl1.0)
Overview|Properties|Methods
Usethismethodtosendanemail.Mostheadersaresetexplicitlyviathemethod'sarguments.
Syntax
[long]=MailerObject.QuickSend(Fromasstring,Toasstring,Subjectasstring,Bodyasstring,[CCasstring,Attachmentsasstring])
TheQuickSendmethodsyntaxhasthefollowingparts:
Part Description
From Thesenderoftheemail.Usuallythisistheemailaddressofthepersonsendingthemessage.Youcanoptionallyprecedethesender'saddresswiththenameofthesender.
To Destinationaddressoftheemail.Youcanoptionallyprecedetheaddresswiththerecipient'sname.
Subject Subjectofthemessage.
Body Bodyofthemessage.
CC Optional.Emailaddress(es)tohavecarboncopiesofthemessagesentto.
Attachments Optional.Acomma-delimitedlistofattachmentstobesentwiththeemail.
Remarks
Anexceptionisthrownifanerroroccurs.Trapforthesuccess/failureoftheoperationbyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifanerroroccurred).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.IfanSMTPrelayserverisbeingusedtosendthemessagethentheindicatedsuccess/failureonlypertainstogettingthemessagetotherelayserver.Themailoperationistheninthehandsoftherelayserver.
Youcanusethismethodtosendanemailwithouthavingtosetanypropertiesorcollections.
YoumustprovidevaluesfortheFrom,To,SubjectandBodyargumentswhencallingthismethod.
Thefollowingisalistingofoptionalproperties/collectionswhichareutilizedbyQuickSend:
Priorityproperty.
Alltimeoutproperties(TimeOutConnect,TimeOutReceive,TimeOutSend).
ReturnReceiptproperty.
ConfirmReadproperty.
SMTPRelayServerscollection.
DNSServerscollection.
NotethatQuickSenddoesnotsupporthtmlemail.TosendamessagewithanhtmlbodycalltheSendMailmethod.
TospecifymultiplevaluesfortheToorCcargumentsseparatethemultipleentrieswithcommas.
ForexamplesourcecodeonhowtousethismethodseeQuickStart.
SeeAlso:SendMail
SendMail(DundasMailerControl1.0)
Overview|Properties|Methods
Usethismethodtosendanemail.
Syntax
MailerObject.SendMail()
Remarks
Anexceptionisthrownifanerroroccurs.Trapforthesuccess/failureoftheoperationbyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifanerroroccurred).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.IfanSMTPrelayserverisbeingusedtosendthemessagethentheindicatedsuccess/failureonlypertainstogettingthemessagetotherelayserver.Themailoperationistheninthehandsoftherelayserver.
TosendanemailwiththismethodyouMUSTspecifythemessagerecipient(s)byusingeithertheTOs,CCsorBCCscollections.TosetthebodyoftheemailusetheBodypropertyand/ortheHtmlBodyproperty.TospecifytheSubjectusetheSubjectproperty.
SendMailusesALLpropertiesandcollectionsoftheDundasMailercontrol.
TheadvantageofusingSendMailasopposedtoQuickSendisthatSendMailincorporatesallfeaturesoftheDundasMailercontrol.
UnliketheQuickSendmethodSendMailiscapableofsendingamessagewithanhtmlbody.
ForexamplesourcecodeillustratingtheuseofSendMailseeoneofthe
followingtutorials:
QuickStart
Tutorial1:SendinganEmailwithanAttachment
Tutorial2:SendinganHtmlEmailwithanEmbeddedImage
SeeAlso:QuickSend
ValidateAddress(DundasMailerControl1.0)
Overview|Properties|Methods
Callthismethodtovalidateanemailaddress.
Syntax
[long]=MailerObject.ValidateAddress(Addressasstring)
TheValidateAddressmethodsyntaxhasthefollowingparts:
Part Description
Address Astringexpressionspecifyingtheaddresstobevalidated.
long Thereturnvalueofthemethodcallsignifyingthevalidityofthesuppliedaddress.
ReturnValues
Thisfunctionwillreturnzero(0)ifthesuppliedemailaddressisvalid.Anon-zeroreturnvalueindicatesaninvalidaddress.Thefollowingisalistingofreturnvaluesandtheirmeanings:
One(1):Thespecifiedaddresswasempty.
Two(2):Thespecifiedaddresswastoolarge.
Three(3):TheSMTPsendoperationfailed.
Four(4):Thespecifieduserwasnotfound.
Five(5):TheMXrecordwasnotfound.
Six(6):Theaddressvalidationoperationfailed.
NOTE:unliketheotherMailercontrolmethodsValidateAddressWILL
NOTraiseanexceptionifanerroroccurs.
Remarks
IMPORTANT:IfyoudonotspecifyaDNSserverbeforecallingthismethodthenitwilltakeasubstantialamountoftimetoperformthevalidation.MakesureyouuseaDNSserver!
ValidateAddressusestheDNSServerscollectionstoperformmailexchangelookups,soitishighlyrecommendedthatyouaddmultipleDNSserverstothiscollection.IfnoDNSservershavebeenaddedtotheDNSServerscollectionthenthefollowingdefaultserverswillbetriedintheirrespectiveorder:"A.ROOT-SERVERS.NET","B.ROOT-SERVERS.NET"and"C.ROOT-SERVERS.NET".Iftheseserversarenotavailablethenthemethodcallwillfailandreturnanerrorcode.
Tovalidateanaddressthismethodfirstdeterminesifthespecifieddomainnameexists(rememberthatanemailaddressconsistsofusername@domainname)byperformingaDNSlookupofmailexchangerecords.Ifthedomainnameexistswetheninitiatesendingamessagetothespecifiedusernameforthedomainwhoseexistencewasjustverified.IftheserverforthespecifieddomainnamethenrefusestoacceptanydatafortheusernameValidateAddressreturnsFALSE,indicatingthattheaddressdoesnotexist.However,iftheserverrequestsdataweassumethatthespecifiedusernameexistsandthefunctioncallreturnsTRUE.
NOTE:IncertaininstancestheValidateAddressmethodmayreturnerroneousinformationconcerningtheexistenceofanemailaddress.Thismayoccurasaresultof:
Themailserverbeingdowntemporarily.
TheSMTPprotocolimplementationoftheserver.
YoucanincreasetheefficiencyandspeedofValidateAddressbyaddingDNSserverstotheDNSServerscollection.
SeeAlso:DNSServersCollection
AddressObject(DundasMailerControl1.0)
AnAddressobjectstoresdetailsaboutaparticularemailaddress.
Remarks
ThisobjectisusedintheTOs,CCs,BCCsandReplyTOscollections.ToaddAddressobjectstothesecollectionsusetheirAddmethods.
TheAddressobjectconsistsofthefollowingtwo(2)properties:
Addressasstring.Anyvalidemailaddress([email protected]).
Nameasstring.AnoptionalnamewhichwillprecedetheAddressproperty(e.g."JimmySmith")
Ifwespecifyanaddressandanamethenthenamewillprecedetheaddresspropertyorbetheonlythingdisplayed,dependingonthetypeofemailsoftwarebeingusedbytheclient.Forexample,ifthespecifiedAddresspropertyis"[email protected]"andtheNamepropertyhasbeensetto"JimmySmith"thentheaddressdisplayedbytheclient'semailsoftwarewillbeeither"JimmySmith"<[email protected]>orjust"JimmySmith".
TheNamepropertydefaultstoazero-lengthstring.
SeeAlso:BCCscollection|CCscollection|ReplyToscollection|TOscollection
AttachmentObject(DundasMailerControl1.0)
Thisobjectisusedtostoredetailsaboutafileattachmenttobesentwiththeemail.NotusedbytheQuickSendmethod.
Remarks
ThisobjectcomprisestheAttachmentscollection.ToaddAttachmentobjectstotheAttachmentcollectionusethecollection'sAddmethod.ToremoveasingleattachmentcalltheRemovemethodofthecollection.ToclearallAttachmentobjectsfromthecollectionusetheClearmethod.
TheAttachmentobjectconsistsofthefollowingsix(6)properties:
FileNameasstring.Thefullpathnameofthefiletobeattachedtothemessage.
ContentNameasstring.Nametobedisplayedintheclientemailsoftware.DefaultstothespecifiedFileNameargument.
ContentTypeasstring.Specifiesthecontenttypeoftheattachment.Defaultsto"Application/Octet-stream".
EncodingTypeasstring.ThetypeofMIMEencodingused.Thisdefaultsto"BASE64".
CharSetasstring.Specifiesthecharactersettobeusedfortheattachment.Defaultsto"US-ASCII".
CustomHeadersasstring.Usedtoaddcustomheaderstothefileattachment.Defaultstoazero-lengthstring.
IfyoudonotspecifyavaluefortheContentNamepropertythentheclientemailsoftwarewillreferencetheattachmentbyusingtheFileNameparameter.
TheContent-Typeheaderfield(representedbytheContentTypeproperty)isusedtospecifythenatureofthedataintheattachment.Itusestypeandsubtypeidentifiersintheformatof"type/sub-type"(e.g.
text/html,text/plain,etc.)andalsoprovidesauxiliaryinformationthatmayberequiredforcertaintypes.Afterthetypeandsubtypenamestheremainderoftheheaderfieldissimplyasetofparameters,specifiedinanattribute/valuenotation.Theseparametersdifferfordifferenttypes,andtheorderingoftheparametersisnotimportant.Amongthedefinedargumentsisa"charset"parameterwhichdeterminesthecharactersettobeusedfortheattachment.CommentsareallowedinaccordancewithRFC822,andtherulesforstructuredheaderfieldsmaybefoundinRFC2046.
TheCharSetpropertydeterminesthecharactersettobeusedfortheattachment.
Thetwosupportedencodingtypes(asspecifiedbytheEncodingTypeargument)are"BASE64"and"QUOTEDPRINTABLE".IfyouwanttoexplicitlysettheEncodingTypeparameterthenkeepinmindthatitmustbeuppercase,andthevalueofthisargumentisusedforthevalueofthe"Content-Transfer-Encoding"header.Ifaninvalidtypeisspecifiedthen"BASE64"isused.Formoreinformationaboutthe"Content-Transfer-Encoding"headerrefertoRFC2045.
NotethattheQuickSendmethodDOESNOTutilizetheAttachmentscollection.
IfyouareusingtheDundasUploadcontrolyoucanloopthroughallitemsinthetheUploadcontrol'sFilescollectionandaddeachUploadedFileobjecttotheAttachmentscollection.Theuploadedfileswillthenbesentalongwiththeemailasattachments.NotethattheContentTypeoftheUploadedFilewillbeusedfortheContentTypeoftheAttachmentobject,unlessyousetthisargumentexplicitly.SeeTutorial1:SendinganEmailwithanAttachmentforsamplecodewhichdemonstratesusingtheUploadcontrolinconjunctionwiththeMailercontrol.
SeeAlso:AttachmentsCollection|AddMethod|RemoveMethod|ItemMethod|CountProperty
AttachmentsCollection(DundasMailerControl1.0)
TheAttachmentscollectionis0-basedandstoresAttachmentobjects.ThiscollectiondetermineshowmanyattachmentswillbesentwiththeemailifyouusetheSendMailmethod.
Remarks
TospecifytheattachmentstobesentwiththeemailaddAttachmentobjectstothiscollection(unlessyouareusingtheQuickSendmethodtosendthemail).
TheAttachmentscollectionsupportsthefollowingmethodsandproperties:
Add(FileNameasstring,[ContentNameasstring=FileName,ContentTypeasstring="Application/Octet-stream",EncodingTypeasstring="BASE64",CharSetasstring="US-ASCII",CustomHeadersasstring=""]).Addsanattachmenttothecollection.
Remove(Index).Removesanattachmentfromthecollection.
Count(read-onlyproperty).ThenumberofAttachmentobjectsstoredinthecollection.
Item(Index).UsedtoretrieveanAttachmentobjectfromthecollection.
Clear().Removesallobjectsfromthecollection.
TheIndexargumentcanbeeitherazero-basednumericalindexorastringkey.ThestringkeyisdefinedbytheFileNamepropertyoftheAttachmentobject.
IfyouareusingtheDundasUploadcontrolyoucanloopthroughallitemsinthetheUploadcontrol'sFilescollectionandaddeachUploadedFileobjecttotheAttachmentscollection.Theuploadedfileswillthenbesentalongwiththeemailasattachments.NotethattheContentTypeoftheUploadedFilewillbeusedfortheContentTypeoftheAttachmentobject,unlessyousetthisargumentexplicitly.SeeTutorial1:SendinganEmailwithanAttachmentforsamplecodewhichdemonstratesusingtheUploadcontrolinconjunctionwiththeMailercontrol.
TheQuickSendfunctiondoesnotusethiscollection.
SeeAlso:AttachmentObject|AddMethod|RemoveMethod|ClearMethod|ItemMethod|CountProperty
CustomHeaderObject(DundasMailerControl1.0)
ThisobjectisusedwiththeCustomHeaderscollection.
Remarks
ToaddCustomHeaderobjectstotheCustomHeaderscollectionusethecollection'sAddmethod.ToremoveoneitemcalltheRemovemethodofthecollection.ToclearallobjectsfromthecollectionusetheClearmethod.
TheCustomHeaderobjectconsistsofthefollowingtwo(2)properties:
Nameasstring.Thenameofthecustomheadertobeaddedtothemessage.
Valueasstring.Thevalueofthespecifiedcustomheader.
Iftheheaderisspecificforyourapplicationthenbyconventiontheheadernameshouldstartwiththecharacters"X-".
TheQuickSendmethoddoesnotutilizetheCustomHeaderscollection.
SeeAlso:CustomHeadersCollection|AddMethod|RemoveMethod|ItemMethod|CountProperty
CustomHeadersCollection(DundasMailerControl1.0)
StoresCustomHeaderobjects.Thiscollectionis0-basedanddeterminesthecustomheaderstobeaddedtotheemailmessage(unlessyouareusingtheQuickSendmethod).
Remarks
Thiscollectionspecifiesthecustomheaderstobeaddedtotheemail.
TheCustomHeaderscollectionsupportsthefollowingmethodsandproperties:
Add(Nameasstring,Valueasstring).AddsaCustomHeaderobjecttothecollection.
Remove(Index).Removesaparticularobjectfromthecollection.
Count(read-onlyproperty).ThenumberofCustomHeaderobjectsstoredinthecollection.
Item(Index).Usedtoretrieveaparticularobjectfromthecollection.
Clear().RemovesallCustomHeaderobjectsfromthecollection.
Iftheheaderisspecificforyourapplicationthenbyconventiontheheadernameshouldstartwiththecharacters"X-".
CustomheadersareveryhelpfulifyouwanttoautomateyourInternetmessagingapplication,sinceheadersareatthetopofmessagesandrequirelessreadingascomparedtothewholemessage.
TheQuickSendfunctiondoesnotusethiscollection.
SeeAlso:CustomHeaderObject|AddMethod|RemoveMethod|Clear
Method|ItemMethod|CountProperty
DNSServerObject(DundasMailerControl1.0)
ThisobjectisusedwiththeDNSServerscollection.
Remarks
ToaddDNSServerobjectstotheDNSServerscollectionusethecollection'sAddmethod.ToremoveoneitemcalltheRemovemethodofthecollection.ToclearallobjectsfromthecollectionusetheClearmethod.
TheDNSServerobjectconsistsofthefollowingproperty:
Nameasstring.ThenameoftheDNSservertobeused,oritscorrespondingIPaddress.
TCPIPRetryCountaslong.ThemaximumnumberoftimestoattempttoconnecttotheserverusingtheTCP/IPprotocol.Defaultsto1.
UDPRetryCountaslong.ThemaximumnumberoftimestoattempttoconnecttotheserverusingtheUDPprotocol.Defaultsto3.
IftheSMTPRelayServerscollectionisemptythentheemailmessageissentdirectlytothedestinationserver,soaDNSserverisrequiredtodeterminewherethemessageistobesent.However,iftheSMTPRelayServerscollectionisnotemptythenthemessageissentusingthespecifiedrelayserver,andtheDNSServerscollectionisignoredsincetherelayserverisresponsiblefordeterminingwherethemessageisbeingsentto.IfboththeSMTPRelayServersandDNSServerscollectionsareemptytheDNSservertobeuseddefaultsto"A.ROOT-SERVERS.NET".Ifthisfails"B.ROOT-SERVERS.NET"willbetried.Ifthistoofailsthen"C.ROOT-SERVERS.NET"willbetried.Ifallofthesefailthenthemailoperationwillfailaswell.
Therearetwo(2)methodsofconnectingtoaDNSserver:usingtheTCP/IPprotocolandusingtheUDPprotocol.DifferentDNSserversmay
supporteitherprotocolorbothprotocols.BydefaulttheTCP/IPmethodistriedfirst.IfthisfailswethenattempttocontacttheserverusingUDP.IfyouknowwhatprotocolsyourspecifiedDNSserversuseyoucanoptimizetheDNSlookupoperationsbyspecifyingwhichprotocoltousewhenworkingwiththeDNSserver(s).
SpecifyingmultipleDNSservers(whennotusingSMTPrelays)increasesthereliabilityandperformanceofyourmailoperation.
Thiscollectioncanbeusedbyallmailsendingfunctions(aswellasPostArticle),dependingonwhetherSMTPrelayserversarebeingusedornot.
SeeAlso:CustomHeadersCollection|AddMethod|RemoveMethod|ItemMethod|CountProperty
DNSServersCollection(DundasMailerControl1.0)
StoresDNSServerobjects.Thiscollectionis0-basedanddeterminestheDNSserver(s)whichwillperformtheDNSlookupsnecessarytosendtheemailmessageifSMTPrelayserversarenotbeingused.
Remarks
ThiscollectionspecifiestheDNSserver(s)tobeusediftheemailisbeingsentdirectlytothedestinationserver.
TheDNSServerscollectionsupportsthefollowingmethodsandproperties:
Add(Nameasstring,TCPIPaslong,UDPaslong).AddsaDNSServerobjecttothecollection.
Remove(Index).Removesaparticularobjectfromthecollection.
Count(read-onlyproperty).ThenumberofDNSServerobjectsstoredinthecollection.
Item(Index).Usedtoretrieveaparticularobjectfromthecollection.
Clear().Removesallobjectsfromthecollection.
TheIndexargumentcanbeeitherazero-basednumericalindexorastringkey.ThestringkeyisdefinedbytheNameargument.
IftheSMTPRelayServerscollectionisemptythentheemailmessageissentdirectlytothedestinationserver,soaDNSserverisrequiredtodeterminewherethemessageistobesent.However,iftheSMTPRelayServerscollectionisnotemptythenthemessageissentusingthespecifiedrelayserver,andtheDNSServerscollectionis
ignoredsincetherelayserverisresponsiblefordeterminingwherethemessageisbeingsentto.IfboththeSMTPRelayServersandDNSServerscollectionsareemptytheDNSservertobeuseddefaultsto"A.ROOT-SERVERS.NET".Ifthisfails"B.ROOT-SERVERS.NET"willbetried.Ifthistoofailsthen"C.ROOT-SERVERS.NET"willbetried.Ifallofthesefailthenthemailoperationwillfailaswell.
Notethatthefirstserverinthecollectionwillbetriedfirst.IfitisnotavailablethenextDNSServerobjectwillbetried,andsoonandsoforth.
Therearetwo(2)methodsofconnectingtoaDNSserver:usingtheTCP/IPprotocolandusingtheUDPprotocol.DifferentDNSserversmaysupporteitherprotocolorbothprotocols.BydefaulttheTCP/IPmethodistriedfirst.IfthisfailswethenattempttocontacttheserverusingUDP.However,ifyouknowwhatprotocolsyourspecifiedDNSserversuseyoucanoptimizetheDNSlookupoperationsbyspecifyingwhichprotocoltousewhenworkingwiththeDNSserver(s).
Thiscollectionmaybeusedbyallsendmailfunctions(aswellasPostArticle),dependingonwhetherSMTPrelayserversarebeingusedornot.
SeeAlso:DNSServerObject|AddMethod|RemoveMethod|ClearMethod|ItemMethod|CountProperty|SMTPRelayServersCollection
HtmlEmbeddedObjObject(DundasMailerControl1.0)
ThisobjectisstoredintheHtmlEmbeddedObjscollection.
Remarks
ToaddHtmlEmbeddedObjobjectstotheHtmlEmbeddedObjscollectionusethecollection'sAddmethod.ToremoveasingleobjectcalltheRemovemethodofthecollection.ToclearallobjectsfromthecollectionusetheClearmethod.
TheHtmlEmbeddedObjobjectconsistsofthefollowingfour(4)properties:
FileNameasstring.Thenameofthefiletobeembedded.
ContentIDasstring.AuniqueIDwhichisusedtoidentifyeachembeddedobject.
ContentNameasstring.Optional.Thenewnameofthefileattachment.IfyoudonotusethisargumentthentheFileNameargumentisusedinstead.
CustomHeadersasstring.
AddHtmlEmbeddedObjobjectstotheHtmlEmbeddedObjscollectiontoembedaudiofiles,graphicsfilesetc.tothehtmlbodyoftheemailmessage.
Toembedobjectsintoanhtmlemailyouwillneedto"wrap"theappropriatetagsaroundtheHtmlEmbeddedObjobjectsbeingembeddedintotheHtmlBodyproperty.AudioelementscanbeinsertedastheBGSOUNDattributeoftheBODYtag,whilegraphicsfilesarecommonlyinsertedusing<IMG>tags.RefertoTutorial2:SendinganHtmlEmailwithanEmbeddedImageforexamplesourcecodeofthis.
WhenyouaddHtmlEmbeddedObjobjectstotheHtmlEmbeddedObjscollectionMAKESUREthatthevaluesyousupplyfortheContentID
argumentareunique.ThisContentIDisreferencedwithinhtmltagswith"cid:theuniquenumber".Itisalsoimportanttouselower-casewhenspecifying"cid".Microsoft'sOutlookwillnotembedobjectsifyouuse"CID".
Iftheclientemailsoftwaresupportshtmlemailitmightnotsupportembeddedhtmlobjects.InthiscasetheContentNameargumentwillbedisplayedintheemailbodyinsteadoftheembeddedobject'scontent.
NOTE:TheQuickSendmethodcannotsendanhtml-basedemail.
SeeAlso:HtmlEmbeddedObjsCollection|AddMethod|RemoveMethod|ItemMethod|CountProperty|Tutorial2:SendinganHtmlEmailwithanEmbeddedImage
HtmlEmbeddedObjsCollection(DundasMailerControl1.0)
StoresHtmlEmbeddedObjobjects.Thiscollectionis0-basedanddeterminestheobjectswhichcanbeembeddedintothehtmlbodyoftheemail.
Remarks
Thiscollectionstoresanyobjectstobeembeddedintothehtmlbodyoftheemail.Objectswhichcanbeembeddedintothehtmlbodyofthemessageareaudiofiles,graphicsfiles,etc.
TheHtmlEmbeddedObjscollectionsupportsthefollowingmethodsandproperties:
Add(FileNameasstring,ContentIDasstring,[ContentNameasstring,CustomHeadersasstring]).AddsanHtmlEmbeddedObjobjecttothecollection.
Remove(Index).Removesaparticularobjectfromthecollection.
Count(read-onlyproperty).Thenumberofobjectsstoredinthecollection.
Item(Index).Usedtoretrieveaparticularobjectfromthecollection.
Clear().Removesallobjectsfromthecollection.
TheIndexargumentcanbeeitherazero-basednumericalindexorastringkey.ThestringkeyisdefinedbytheFileNameargument.
Toembedobjectsintoanhtmlemailyouwillneedto"wrap"theappropriatetagsaroundtheHtmlEmbeddedObjobjectwhenaddingtheobjectstotheHtmlBodyproperty.Audioelementscanbeinsertedasthe
BGSoundattributeoftheBodytag,whilegraphicsfilesarecommonlyinsertedusing<IMG>tags.RefertoTutorial2:SendinganHtmlEmailwithanEmbeddedImageforexamplesourcecodeofthis.
ToembedobjectsintoanemailyouwillneedtoiteratethroughtheFilescollectionoftheDundasUploadcontrol.
WhenyouaddobjectstothiscollectionMAKESUREthatthevaluesyousupplyfortheContentIDargumentareunique.ThisContentIDisreferencedwithinhtmltagswith"cid:theuniquenumber".Itisalsoimportanttouselower-casewhenspecifying"cid".Microsoft'sOutlookwillnotembedobjectsifyouuse"CID".
TheQuickSendmethoddoesnotutilizethiscollection.
NotethatiftheHtmlBodypropertyisazero-lengthstring(thedefault)thentheitemsinthiscollectionwillbeignored.ItemswillalsobeignoredifboththeHtmlBodyandBodypropertiesaresetandtheclient'semailsoftwaredisplaystext-basedemailbydefault.
RefertoTutorial2:SendinganHtmlEmailwithanEmbeddedImageforexamplesourcecodeonhowtosendanhtmlemailwithembeddedobjects.
SeeAlso:HtmlEmbeddedObjObject|AddMethod|RemoveMethod|ClearMethod|ItemMethod|CountProperty
SMTPRelayServerObject(DundasMailerControl1.0)
ThisobjectisusedbytheSMTPRelayServerscollection.
Remarks
ToaddSMTPRelayServerobjectstotheSMTPRelayServerscollectionusethecollection'sAddmethod.ToremoveoneitemcalltheRemovemethodofthecollection.ToclearallobjectsfromthecollectionusetheClearmethod.
TheSMTPRelayServerobjectconsistsofthefollowingproperties:
Nameasstring.ThenameoftheSMTPrelayserver.
Portaslong.Theportnumbertobeusedwiththeserver.Defaultsto25.
Localhostasstring.Thelocalcomputer'snameorit'sIPaddress.UsedwiththeHELOcommand,thisdefaultsto"local.com".
Userasstring.Avalidusername(iftheSMTPserverrequiresauthentication).Defaultstoazero-lengthstring.
Passwordasstring.Avalidpassword(iftheSMTPserverrequiresauthentication).Defaultstoazero-lengthstring.
SMTPrelayserversareusedtorelayamessagetoadestinationserver.
IftheSMTPRelayServerscollectionisemptythentheemailmessageissentdirectlytothedestinationserver,soaDNSserverisrequiredtodeterminewherethemessageistobesent.However,iftheSMTPRelayServerscollectionisnotemptythenthemessageissentusingthespecifiedrelayserver,andtheDNSServerscollectionisignoredsincetherelayserverisresponsiblefordeterminingwherethemessageisbeingsentto.IfboththeSMTPRelayServersandDNSServerscollectionsareemptytheDNSservertobeuseddefaultsto"A.ROOT-SERVERS.NET".Ifthisfails"B.ROOT-SERVERS.NET"willbe
tried.Ifthistoofailsthen"C.ROOT-SERVERS.NET"willbetried.Ifallofthesefailthenthemailoperationwillfailaswellandreturnanerrorcode.
SpecifyingmultipleSMTPrelayserversincreasesthereliablityandperformanceofyourmailoperation.
Allmailsendoperations(includingPostArticle)utilizetheSMTPRelayServercollection.
SeeAlso:SMTPRelayServersCollection|AddMethod|RemoveMethod|ItemMethod|CountProperty
SMTPRelayServersCollection(DundasMailerControl1.0)
ThiscollectionstoresSMTPRelayServerobjects,anddeterminestheSMTPrelayserverstobeusedwhensendingtheemail(ifany).Notethatitis0-based.
Remarks
TheSMTPRelayServerscollectionsupportsthefollowingmethodsandproperties:
Add(Nameasstring,[Portaslong=25,LocalHostasstring="local.com",Userasstring="",Passwordasstring="").AddsanSMTPRelayServerobjecttothecollection.
Remove(Index).Removesaparticularobjectfromthecollection.
Count(read-onlyproperty).Thenumberofobjectsstoredinthecollection.
Item(Index).Usedtoretrieveaparticularobjectfromthecollection.
Clear().Removesallobjectsfromthecollection.
IftheSMTPRelayServerscollectionisemptythentheemailmessageissentdirectlytothedestinationserver,soaDNSserverisrequiredtodeterminewherethemessageistobesent.However,iftheSMTPRelayServerscollectionisnotemptythenthemessageissentusingthespecifiedrelayserver,andtheDNSServerscollectionisignoredsincetherelayserverisresponsiblefordeterminingwherethemessageisbeingsentto.IfbothofthesecollectionsareemptythentheDNSservertobeuseddefaultsto"A.ROOT-SERVERS.NET".Ifthisfails"B.ROOT-SERVERS.NET"willbetried.Ifthistoofailsthen"C.ROOT-SERVERS.NET"willbetried.Ifallofthesefailthenthemailoperation
willfailaswell.
Itishighlyrecommendedthatyouspecifyatleastonerelayserver.Usingarelayincreasesthespeedoftheoperation,andarelaywillalsoattempttosendamessagemultipletimesifitcannotbesentwiththefirstattempt.ADirectSendmailoperation(performedwhennoSMTPservershavebeenspecified)willonlyattempttosendtheemailone(1)time.
Allmailsendoperations(includingPostArticle)utilizethiscollection.
SeeAlso:SMTPRelayServerObject|AddMethod|ClearMethod|CountProperty|ItemMethod|RemoveMethod|DNSServersCollection
TOs,CCs,BCCsandReplyTOscollections(DundasMailerControl1.0)
ThesecollectionsstoreAddressobjects,anddeterminetherecipient(s)oftheemail.Theyareall0-based.
Remarks
Thesecollectionssupportthefollowingmethodsandproperties:
Add(Addressasstring,[Nameasstring]).AddsanAddressobjecttothecollection.
Remove(Index).Removesaparticularobjectfromthecollection.
Count(read-onlyproperty).ThenumberofAddressobjectsstoredinthecollection.
Item(Index).Usedtoretrieveaparticularobjectfromthecollection.
Clear().RemovesallAddressobjectsfromthecollection.
TheQuickSendmethoddoesnotusethesecollections.Allothermailsendmethods(aswellasPostArticle)usethesecollections.
YoucansendanemailtomultiplerecipientsbyaddingmorethanoneAddressobjecttothesecollections.Youcanalsospecifymultipleaddresseswithjustone(1)Addressobjectbyseparatingthemultipleentrieswithcommas.However,ifyouusejustone(1)AddressobjecttospecifymultipleaddressesthenyouCANNOTprecedetheaddresswiththenameofthemessagesender(e.g."FirstnameLastname"[email protected]).
TheReplyTOscollectionisusediftherecipientoftheemaildecidesto
replytotheemailmessage.IftherearenoitemsinthiscollectionthentheReplyToaddressistakenfromtheFromAddressproperty.NotethatallAddressobjectswillbeusedforthereplymessage.
TohavemultipleaddressesappearintheTofieldoftheresultingemailjustaddmultipleAddressobjectstotheReplyTOscollection.
SeeAlso:AddressObject|AddMethod|RemoveMethod|ClearMethod|ItemMethod|CountProperty
CountProperty(AllDundasMailercollections)
Usethisread-onlypropertytodeterminethenumberofelementscurrentlystoredinanyDundasMailercollection.
Syntax
AnyMailerCollection.Count
Remarks
UsethispropertytofindouthowmanyelementsarecurrentlybeingstoredinanyDundasMailercollection.Thisisusefulfordeterminingtheupperloopdelimiterwheniteratingthroughallofacollection'sitems.NotethatyoucanalsoiteratethroughanyDundasMailercollectionwithFor...Eachloops.
SeeAlso:RemoveMethod|ItemMethod|ClearMethod
AddMethod(Attachmentscollection)
AddsanAttachmentobjecttotheAttachmentscollection.
Syntax
AttachmentsCollection.Add(FileNameasstring,[ContentNameasstring=FileName,ContentTypeasstring="Application/Octet-stream",EncodingTypeasstring="BASE64",CharSetasstring="US-ASCII",CustomHeadersasstring=""])
TheAddmethodsyntaxhasthefollowingparts:
Part Description
FileName Thefullpathnameofthefiletobeadded.
ContentName Thenamebywhichtheattachmentwillbereferredtointheclient'semailsoftware.
ContentType Specifiesthemediatypeandsubtypeofdatainthebodyofthemessage.
EncodingType Thetypeofencodingtobeusedfortheattachment.Mustbeuppercase.
CharSet Thecharactersettobeused.
CustomHeaders Anycustomheadertobeaddedtotheattachment.
Remarks
UsethismethodtoaddanAttachmentobjecttotheAttachmentscollection.ToremoveanAttachmentusetheRemovemethod.ToremoveallAttachmentsfromthecollectioncalltheClearmethod.
TosendmultipleattachmentsjustaddthedesiredfileattachmentstothiscollectionandcalltheSendMailmethod.
IfyoudonotspecifyavaluefortheContentNamepropertythentheclientemailsoftwarewillreferencetheattachmentbyusingtheFileNameparameter.
ToaddacustomheadertotheattachmentusetheCustomHeadersargument.
TheContent-Typeheaderfield(representedbytheContentTypeargument)isusedtospecifythenatureofthedataintheattachment.Itusestypeandsubtypeidentifiersintheformatof"type/sub-type"(e.g.text/html,text/plain,etc.)andalsoprovidesauxiliaryinformationthatmayberequiredforcertaintypes.Afterthetypeandsubtypenamestheremainderoftheheaderfieldissimplyasetofparameters,specifiedinanattribute/valuenotation.Theseparametersdifferfordifferenttypes,andtheorderingoftheparametersisnotimportant.Amongthedefinedargumentsisa"charset"parameterwhichdeterminesthecharactersettobeusedfortheattachment.CommentsareallowedinaccordancewithRFC822,andtherulesforstructuredheaderfieldsmaybefoundinRFC2046.
TheCharSetargumentdeterminesthecharactersettobeusedfortheattachment.Thisparameterisnotcasesensitive.
Thetwosupportedencodingtypes(asspecifiedbytheEncodingTypeargument)are"BASE64"and"QUOTEDPRINTABLE".IfyouwanttoexplicitlysettheEncodingTypeparameterthenkeepinmindthatitmustbeuppercase,andthevalueofthisargumentisusedforthevalueofthe"Content-Transfer-Encoding"header.Ifaninvalidtypeisspecifiedthen"BASE64"isused.Youmaywanttouse"QUOTEDPRINTABLE"iftheattachmentcontentcanberepresentedwithASCIIcharacters.Formoreinformationaboutthe"Content-Transfer-Encoding"headerrefertoRFC2045.
IfyouareusingtheDundasUploadcontrolyoucanloopthroughallitemsinthetheUploadcontrol'sFilescollectionandaddeachUploadedFile
objecttotheMailercontrol'sAttachmentscollection.Theuploadedfileswillthenbesentalongwiththeemailasattachments.TheContentTypeoftheUploadedFilewillbeusedfortheContentTypeoftheAttachmentobjectunlessyousetthisargumentexplicitly.SeeTutorial1:SendinganEmailwithanAttachmentforsamplecodewhichdemonstratesusingtheUploadcontrolinconjunctionwiththeMailercontrol.YoucanalsorefertotheUploadcontrol'stutorialsforfurthercodesamplesandinstructions.
SeeAlso:AttachmentsCollection|ClearMethod|CountProperty|ItemMethod|RemoveMethod
AddMethod(CustomHeaderscollection)
AddsaCustomHeaderobjecttotheCustomHeaderscollection.
Syntax
CustomHeadersCollection.Add(Nameasstring,Valueasstring)
TheAddmethodsyntaxhasthefollowingparts:
Part Description
Name Thenameofthecustomheadertobeadded.
Value Thevalueofthecustomheadertobeadded.
Remarks
UsethismethodtoaddaCustomHeaderobjecttotheCustomHeaderscollection.ToremoveaCustomHeaderobjectusetheRemovemethod.ToremoveallCustomHeaderobjectsfromthecollectioncalltheClearmethod.
PleasenotethattheQuickSendmethoddoesnotutilizethiscollection.
SeeAlso:CustomHeadersCollection|ClearMethod|CountProperty|ItemMethod|RemoveMethod
AddMethod(DNSServerscollection)
AddsaDNSServerobjecttotheDNSServerscollection.
Syntax
DNSServersCollection.Add(Nameasstring,[TCPIPaslong=1,UDPaslong=3])
TheAddmethodsyntaxhasthefollowingparts:
Part Description
Name ThenameoftheDNSserver,oritscorrespondingIPaddress.
TCPIP ThemaximumnumberofconnectionattemptsusingtheTCP/IPprotocol.Defaultstoone(1).
UDP ThemaximumnumberofconnectionattemptsusingtheUDPprotocol.Defaultstothree(3).
Remarks
UsethismethodtoaddaDNSServerobjecttotheDNSServerscollection.ToremoveaDNSServerobjectusetheRemovemethod.ToremoveallobjectsfromthecollectioncalltheClearmethod.
TomakesurethataDNSserverisavailabletoprocessemailsitisrecommendedthatyouspecifymorethanoneserver.
Notethatthefirstserverinthecollectionwillbetriedfirst.IfitisnotavailablethenextDNSServerobjectwillcontacted,andsoon.
Therearetwo(2)methodsofconnectingtoaDNSserver:usingtheTCP/IPprotocolandusingtheUDPprotocol.DifferentDNSserversmaysupporteitherprotocolorbothprotocols.BydefaulttheTCP/IPmethodis
triedfirst.IfthisfailswethenattempttocontacttheserverusingUDP.However,ifyouknowwhatprotocolsyourspecifiedDNSserversuseyoucanoptimizetheDNSlookupoperationsbyspecifyingwhichprotocoltousewhenworkingwiththeDNSservers(i.e.settheprotocolargumentwhichisn'tusedbyyourDNSservertozero).
SeeAlso:DNSServersCollection|ClearMethod|CountProperty|ItemMethod|RemoveMethod
AddMethod(HtmlEmbeddedObjscollection)
AddsanHtmlEmbeddedObjobjecttotheHtmlEmbeddedObjscollection.
Syntax
HtmlEmbeddedObjsCollection.Add(FileNameasstring,ContentIDasstring,[ContentNameasstring,CustomHeadersasstring])
TheAddmethodsyntaxhasthefollowingparts:
Part Description
FileName Thefilenameoftheobjecttobeembedded.
ContentID AuniqueIDwhichisusedtoidentifyeachembeddedobject.
ContentName Thenamewhichwillbedisplayedintheemail.IfthisisnotsetthentheFileNamewillbedisplayed.
CustomHeaders Anycustomheader.
Remarks
UsethismethodtoaddanHtmlEmbeddedObjobjecttotheHtmlEmbeddedObjscollection.ToremoveanobjectusetheRemovemethod.ToremoveallobjectsfromthecollectioncalltheClearmethod.
Objectswhichcanbeembeddedaregraphicsfiles,audiofiles,etc.
MAKESUREthatthevaluesyousupplyfortheContentIDargumentareunique.ThisContentIDisreferencedwithinhtmltagswith"cid:uniquenumber"(seethesamplesourcecodebelowforanexample
ofthis).Itisalsoimportanttouselower-casewhenspecifying"cid".Microsoft'sOutlookwillnotembedobjectsifyouuse"CID".
UsetheDundasUploadcontroltoallowtheusertospecifyobjectstobeembeddedintheemail.TheUploadcontrolexposesaFilescollectionwhichconsistsofUploadedFileobjectswhichcanthenbeusedastheembeddedobjects.ToembedtheuploadedfilesloopthroughtheFilescollectionandaddthemtotheHtmlEmbeddedObjscollection,andthenembedtheobjectbywrappingtheappropriatehtmltagsaroundtheobjectintheMailercontrol'sHtmlBodyproperty.YoucanusetheUploadedFileobject'sTagNamepropertytodeterminewhichfileinputboxtheobjectoriginatedfrom,andyoucanalsouseVBScripts'sInStrmethodinconjunctionwiththeUploadedFileobjectsContentTypepropertytodeterminethetypeoftheobject.Thisletsyoumakesurethatanobjectisnotembeddedintothehtmlbodyoftheemailwiththewrongtagsaroundit(seethecodesamplebelow).YoucanalsorefertoTutorial2:SendinganHtmlEmailwithanEmbeddedImageforsamplesourcecodewhichdemonstratesusingtheUploadcontrolinconjunctionwiththeMailercontroltoembedobjectsintoanemail.
Pleasenotethatitisuptoyoutowraptheappropriatetagsaroundtheembeddedobjects.Thisletsyoucontrolwhereintheemailtheobjectswillappear.Thecid(contentID)isusedwithinthehtmltagstoidentifywhichobjectintheHtmlEmbeddedObjscollectionistobeembedded(seetheexamplesourcecodebelow).
SeeAlso:HtmlEmbeddedObjsCollection|ClearMethod|CountProperty|ItemMethod|RemoveMethod
Example
'ThissmallcodesnippetassumesthatthereisaninputelementoftheFiletypecalled'txtBGSoundwhichletstheuseruploadafiletotheserver(tobeusedforthebackground'soundofthehtml-basedemail).Wechecktoseeifafilewasuploadedfromthis'particularfileinputboxandthenwechecktheContentTypepropertyoftheuploaded'filetomakesurethattheuseruploadedavalidaudiofile.'NOTE:itisassumedherethatobjUpload.Savehasalreadybeencalled.
'initializetheHtmlBodypropertyobjEmail.HtmlBody="<html><body>"
'loopthroughallfilesuploadedbyuserfori=0toobjUpload.Files.Count-1
'checktoseeifafilewasuploadedusingafileinputboxnamed"txtBGSound"if(objUpload.Files(i).TagName="txtBGSound")then
'nowmakesurethattheuseractuallyuploadedavalidaudiofileif(InStr(1,objUpload.Files(i).ContentType,"audio"))then
'nowaddtheobjecttotheHtmlEmbeddedObjscollection,andthenembed'theobjectintotheHtmlBodyproperty,wrappingtheappropriatetags'aroundit.NotethatwearesettingtheContentNameargumentofthe'HtmlEmbeddedObjobjecttotheOriginalPathpropertyoftheUploadedFile'object(e.g.c:\MyPic.jpg).Thentheresultingnameoftheobjectinthe'emailwillnotbeprecededwithaguid(alluploadedfileswillbesaved'todiskwithaguidasthefirstpartoftheirfilename).objEmail.HTMLEmbeddedObjs.AddobjUpload.Files(i).Path,1,objUpload.Files(i).OriginalPathobjEmail.HTMLBody=objEmail.HTMLBody&"<BGSoundsrc=cid:1></BGSound>"
endif
endif
next
'nowfinishsettingtheHtmlBodypropertyobjEmail.HtmlBody=objEmail.HtmlBody&"</body></html>"
AddMethod(SMTPRelayServerscollection)
AddsanSMTPRelayServerobjecttotheSMTPRelayServerscollection.
Syntax
SMTPRelayServersCollection.Add(Nameasstring,[Portaslong=25,LocalHostasstring="local.com",Userasstring="",Passwordasstring=""])
TheAddmethodsyntaxhasthefollowingparts:
Part Description
Name ThenameoftheSMTPserver,oritscorrespondingIPaddress.
Port Theporttousewhenconnectingtotheserver.Defaultsto25.
LocalHost Thelocalcomputer'snameoritsIPaddress.UsedwiththeHELOcommand,thisdefaultsto"local.com".
User AvalidusernameiftheNNTPserverrequiresauthentication.ONLYappliestoNNTPservers!
Password Thepasswordcorrespondingtothesuppliedusername(iftheNNTPserverrequiresauthentication).ONLYappliestoNNTPservers!
Remarks
UsethismethodtoaddanSMTPRelayServerobjecttotheSMTPRelayServerscollection.ToremoveanobjectusetheRemovemethod.ToremoveallobjectsfromthecollectioncalltheClearmethod.
Ifthespecifiedserverrequiresauthenticationthenyoumustsupplyavalidusernameandpassword.However,mostSMTPserversdonotrequireauthentication.
Ifyouspecifymorethanone(1)serverthenthefirstserverinthiscollectionwillbeusedtosendtheemail.However,ifthisserverisdownthenthenextserverinthecollectionwillbeusedtosendtheemail,andsoon.Specifyingmorethanoneserverincreasesthechancesofsuccessfullysendingyouremail,andusingarelayserverisalsofasterthansendingthemessagedirectly.
Youcansetanoptionalvaluewithouthavingtoprovidevaluesforpreviousoptionalargumentsbyseparatingtheargumentswithcommas.Forexample,toprovideausernameandpasswordyoucouldcalltheAddmethodwiththefollowingsyntax:SMTPRelayServersCollection.Add"someserver.com",,,"MyUsername","MyPassword".
NOTE:TheusernameandpasswordparametersareonlyimplementedforNNTPservers.Ifyouneedtoimplementausername/passwordforanSMTPserveryouwillhavetopurchasethesourcecodetotheMailercontrol.
SeeAlso:SMTPRelayServersCollection|ClearMethod|CountProperty|ItemMethod|RemoveMethod
AddMethod(TOs,CCs,BCCsandReplyTOscollections)
AddsanAddressobjecttotherelevantcollection.
Syntax
Collection.Add(Addressasstring,[Nameasstring])
TheAddmethodsyntaxhasthefollowingparts:
Part Description
Address Anemailaddresstosendthemessageto.
Name Optional.The"name"oftheemailrecipient.
Remarks
UsethismethodtoaddanAddressobjecttothespecifiedcollection.TheemailwillbesenttoeveryAddressobjectinthecollection.ToremoveanAddressusetheRemovemethod.ToremovealladdressesfromthecollectioncalltheClearmethod.
TheoptionalNameargumentletsyouspecifyauser-friendlynamewhichwillappearintheappropriatefieldoftheemail(i.e.To,CC,BCCorReplyTofields).Forexample,let'sassumethatthespecifiedaddressforJohnDoeis"[email protected]".IfwealsosettheNameargumentto"JohnDoe"thentherecipientoftheemailwillseeeither"JohnDoe"<[email protected]>or"JohnDoe",dependingontheemailprogramtheclientisusing.
NOTE:oneofthesecollectionsneedstohaveanAddressobjectinorderfortheSendMailoperationtoproceed.IfnoneofthesecollectionshavebeenpopulatedthentheSendMailoperationwillimmediatelyfailsincenodestinationaddresshasbeenspecified.
SeeAlso:TOs,CCs,BCCsandReplyTOscollections|ClearMethod|CountProperty|ItemMethod|RemoveMethod
Clear(AllDundasMailercollections)
RemovesallelementsfromaDundasMailercollection.
Syntax
AnyMailerCollection.Clear
Remarks
Usethismethodtoemptyacollectionofallelements.ToremovejustoneelementinacollectionusetheRemovemethod.
SeeAlso:CountProperty|ItemMethod|RemoveMethod
RemoveMethod(AllDundasMailercollections)
Callthismethodtoremoveone(1)elementfromanyDundasMailercollection.
Syntax
AnyMailerCollection.Remove(Index)
TheRemovemethodsyntaxhasthefollowingparts:
Part Description
Index Thisargumentcanbeeitheranumber(integerorlongdatatype)orastringkey.AlloftheDundasMailercollectionsarezero(0)based.
Remarks
Toidentifythecollectionitemtoberemovedyoucanspecifyeitheranumber(integerorlongdatatypes)orastringkeyfortheIndexargument.Ifyouspecifyanumberthentheindexoftheelementwillbeused(theindexbeingzero-based).Forexample,thestatement"TOs.Remove0"willremovethefirstelementintheTOscollection.Ifastringkeyisspecifiedthentheelementtoberemovedwillbeidentifiedbyitskey.Refertothefollowingforalistingofthevariouscollectionkeys:
TOsCollectionstringkey=Addressproperty
CCsCollectionstringkey=Addressproperty
BCCsCollectionstringkey=Addressproperty
AttachmentsCollectionstringkey=FileNameproperty
HTMLEmbeddedObjsCollectionstringkey=FileNameproperty
CustomHeadersCollectionstringkey=Nameproperty
DNSServersCollectionstringkey=Nameproperty
SMTPServersCollectionstringkey=Nameproperty
Forexample,toremoveanemailaddressnamed"[email protected]"fromtheTOscollectionyouwouldenter:TOs.Remove"[email protected]".
SeeAlso:CountProperty|ItemMethod|ClearMethod
ItemMethod(AllDundasMailercollections)
CallthismethodtoretrieveanelementfromanyDundasMailercollection.Thisisthedefaultmemberofallcollections.
Syntax
AnyMailerCollection.Item(Index)
TheItemmethodsyntaxhasthefollowingparts:
Part Description
Index Thisargumentcanbeeitheranumber(integerorlongdatatype)orastringkey.AlloftheDundasMailercollectionsarezero(0)based.
Remarks
IftheIndexargumentisspecifiedasanumberthentheitemisretrievedviatheindexofthecollection(zero-based).Forexample,toretrievethefirstelementintheTOscollectionyoucouldusethefollowingstatement:SetobjAddress=TOsCollection.Item(0).Ifastringisspecifiedthentheelementisretrievedviaitskey.Foralistingofcollectionkeysrefertothefollowing:
TOsCollectionstringkey=Addressproperty
CCsCollectionstringkey=Addressproperty
BCCsCollectionstringkey=Addressproperty
AttachmentsCollectionstringkey=FileNameproperty
HTMLEmbeddedObjsCollectionstringkey=FileNameproperty
CustomHeadersCollectionstringkey=Nameproperty
DNSServersCollectionstringkey=Nameproperty
SMTPServersCollectionstringkey=Nameproperty
Thismethodisthedefaultcollectionmethodsoyoudonothavetoexplicitlydeclareit.Forexample,toretrievethefirstAddressobjectfromtheTOscollectionyoucouldusethisstatement:SetobjAddress=TOs(0).
SeeAlso:CountProperty|ClearMethod|RemoveMethod
DesignedfromthegroundupforASPdevelopers,DundasChartiseasytouse,flexible,andbackedbyDundasSoftware'sawardwinningteamofsoftwareengineers.
DundasChartdeliverspresentation-qualitygraphics,andsupportsboth2Dand3Dcharts.
Withblazingperformance,stunningpresentationqualitygraphics,power,speedandunmatchedflexibility,DundasCharthasallthefeaturesyouneed.
The3Dchartingcontrolwillalsoautomaticallyleverage3Dacceleratedvideohardware(ifpresent)inyoursystemorwebserver.
DundasChart3DFeatures
Stunningpresentationquality
Hardwareacceleration-utilizes3DacceleratedhardwarefromATI,3Dfx,nVidia,andanarrayofothermanufacturers
OpenGL-State-of-the-artOpenGLimplementation
Rotation-youcanrotateyourchartsprogrammatically.
Selection(drilldown)-determinewhatsliceauserclickedonandimplementadrilldownscenariowithease!
Widevarietyofcharttypes
Textureflexibility-useabitmapimageasacustomtexture
Texture/Colorblending-Notonlycanyouusetextures,butyoucanalsochangethetexture'scolor
Grayscaletexturing-Ifcolorsarenotintheplans,grayscalingisalsosupported,givingyouaddedimageflexibility
TemplateCreatortopre-loadtexture/color/sizetypes-savetime
increatingcharttypesbyusingthetemplatecreatortostore/loadpre-madecolourschemes/texturesandsizes
EdgeBeveling-edgescanbebeveledtogiveaddedcustomizationtocharts;makeyouredgesasroundedorassquareasisneeded.
Annotation-addnotesanywhereonthechart-addsingleormultiplenotestothechartinanyposition.
Verticalannotation-textandnotescanbedisplayedverticallyforaddedcustomization.
User-configurableelementpositioning-positionlegends,titles,annotationsandotherelementseitherprogrammaticallyorbyusingsimpledraganddropactions
DundasChartEditions:
ASP/WindowsDNA2000Development
Speciallydesignedforuseinserver-sideprojects,DundasChart(2Dand3D)offersfullsupportforyourASPandWindowsDNAdevelopmenteffortswithafullsetofserversidefeatures.
EnterpriseEdition
DundasChartEnterpriseprovidesthecompleteC++/ATLsourcecode,documentation,projectandworkspacefilesneededtobuildtheproduct.DundasChartEnterpriseoffersunlimitedcustomizationandflexibility.IfyouhaveveryspecializedrequirementsorportingneedsthenlooktoDundasChartEnterpriseforthesolution!
FormoreinformationvisitourwebsiteatDundasChart
DundasPieChartServerControl2.0
Copyright©DundasSoftwareLtd.2000.AllRightsReserved
Overview|Properties|Methods
TheDundasPieChartServerControl2.0allowsyoutoquicklyandpainlesslyadddynamicpiechartstoyourASPapplications.
Features:
Addorremovepiechartslices(elements).
Changethetitleofthepiechart.
Rotatethechartprogammatically.
Implementselectionanddrilldownwithease.
ChangethepieslicelabelsaswellasthelabelsforthepieslicesintheLegend.
Changethesizesofthepieslices.
Changetheminimum"collected"value(seebelowformoredetails).
Changethetexturesand/orcolorsofpieelements.
Explode/collapsepieelements.
TousethiscontrolinwebpagesyouMUSTUSEeitheran<IMG>tag(seethesourcecodeforthetwosuppliedASPpages)oran<A>tag.InthisdemothereisoneASPpage(let'scallitthesecondarypage)whichcreatesaninstanceoftheASPPieChartcontrol,loadsatemplate(createdwiththeTemplateCreator),addsthespecifieddataandthencallsSendJPEGtosendthedatatotheclient.Thefirstpage(letscallitthemainpage)setsuptheuserinterface,retrievespiechartvariables
(likethenumberofslices,whethertheslicesareexploded,etc.)andthenretrievesthepiechartimagebyembeddingthesecondaryASPpageinan<IMG>tagwiththeSRCattributesettothesecondarypage.ThefirstpagecanbeeitheranhtmlorASPfile.
Smalldataelements(pieslices)are"collected"andthendisplayedtogetherasonepieslicecalledthe"collected"element.YoucanchangetheminimumdatavalueatwhichslicesarecollectedwiththeSetCollectedLimitmethod.CallSetCollectedProptomanipulatethepropertiesofthecollectedslice(texture,color,etc.).
TomakesurethatthebrowserneverusesacachedcopyofthejpegsettheExpirespropertyoftheResponseobjecttoeitherzerooranegativevalue.Seeatutorialforanexampleofthis.
Tooutputapiechartjpegperformthefollowingactionsintheirspecifiedorder:
1. CreateaninstanceofanASPPieChartobjectbyusingCreateObject(e.g.CreateObject("Dundas.PieChartServer.2")).
2. Setthedirectorypropertiesofthecontrolwhichspecifyworkingdirectoriesfordifferentaspectsofchartactivity.ThesepropertiesareDirTemplateandDirTexture,anddealwiththedirectoriesusedtostoretemplatesandtextures,respectively.
3. LoadatemplateviatheLoadTemplatemethod.
4. Setthepropertiesofthepiechart(e.g.explodedpieces,collectedelementproperties,etc.)
5. AddpiechartdatawiththeAddDatamethod.
6. SendtheresultingjpegdirectlytoaclientwiththeSendJPEGmethodoralternativelyyoucansavethejpegtodiskwithCreateJPEGFileandthenpresenttheimagetoauserwithastandard<IMG>tag.
7. IfyouwanttogenerateanotherJpegusingthesametemplatethenrepeatSteps4to6.Ifyouwanttocreateanotherjpegwitha
differenttemplaterepeatsteps1to6.
8. DestroythePieChartobjectbysettingittoNothing(e.g.SetobjPieChart=Nothing).
9. MAKESUREthatthereisnohtmlcodeinthisASPpagewhichoutputsthejpeg.
TheProgIDofthecontrolis:Dundas.PieChartServer.2
IMPORTANT:tosuccessfullyoutputapiechartjpegtheIntelcompressionlibrary(ijl15.dll)mustexisteitherinyoursystemdirectoryoratthesamedirectorylevelastheservercontrol(AspPieChart.dll).
TominimizetheamountofwhitespaceinthejpegmakethepiechartimageaslargeaspossibleintheTemplateCreator.
Forinformationconcerningdebugging,aswellasFAQsandtroubleshootinggotoourdevelopersite.
SeeAlso:DundasPieChartOverview|TemplateCreatorOverview
AddData
Overview|Properties|Methods
Callthismethodtoadddataelements(slices)toapiechart.
Syntax
long=PieChartObject.AddData(ValueAsDouble,[DataLabelAsString],[ColorAsLong=&HFFFFFF],[TextureAsString])
TheAddDatamethodsyntaxhasthefollowingparts:
Part Description
Value Thesizeofthepiechartslice(element).
DataLabel Thelabelofthepieslice.Ifthisisnotsetthenyourresultingjpegwillnothavepieslicelabels.
LegendLabel Thelegendtitleofthepieslice.Ifthisisnotsetthenyourresultingjpegwillnothavelabels(text)forthelegend.
Color Thecolorofthepieslice(defaultstowhite).UseeitherahexadecimalvalueorVBScript'sRGBfunction.
Texture Thetextureofthepieslice.
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwisea
non-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursyoucanusethisreturnvalueastheargumentforGetErrorTextinordertoretrievearelevanttexterrormessage,oralternativelyyoucanremoutthe"OnErrorResumeNext"statementandobservethethrownexceptionforadescriptionoftheerror.
Remarks
ThesizeofthepiesliceisdictatedbytheDataargument.Thesizeisnotinanyspecificunits(e.g.degreesorradians),ratheritisrepresentedasapercentageofthetotalnumberofspecifiedsizes.Forexample,iftherearefourslicesandtheyallhaveaDatavalueof10thentheirindividualsizeswillbe:(10/(10+10+10+10))*100%.
Ifyoudonotspecifyacolorortextureforanelementthenthecolorortextureforthatparticularelementwillbeobtainedfromtheloadedtemplate(ifitexists).Ifthesameelementdoesnotexistinthetemplatethenthedefaultcoloriswhiteandthetextureissetto"none".Forexample,assumewehaveloadedatemplatewhichcontainsfour(4)pieslices.Ifweaddpieslice#1withAddDataandwedonotspecifyacolorortexturethenthecolorandtextureforpieelement#1inthetemplatewillbeused.If,however,weaddpieelement#5withoutspecifyingacolorortexturethentherewillbenotextureusedandthecolorofthepieslicewillbewhitesincethetemplateweloadeddoesnothaveafifthpieslice.
TosettheColorargumentyoucanuseeitherahexadecimalvalueorVBScript'sRGBfunction.
Pleasenotethatatemplateonlyprovidestexturesandcolorsforpieslices.YouMUSTSPECIFYthepieslicelabelsandlegendlabelsifyou
wanttodisplaytheminyourjpeg.
IMPORTANT:YouMUSTloadthedesiredtemplateBEFOREcallingAddData,otherwisevaluessetintheAddDatacallwillbeoverwrittenbythepiechartattributesstoredinthetemplate.
SeeAlso:LoadTemplate|Overview(DundasPieChartServerControl)
AddLabel
Overview|Properties|Methods
Callthismethodtosetlegendelements.
Syntax
long=ChartObject.AddLabel(TextAsString)
TheAddLabelmethodsyntaxhasthefollowingparts:
Part Description
Text Thetextforthelegendelement.
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursusethisreturnvalueastheargumentforGetErrorTextinordertoretrievearelevanttexterrormessage.
Remarks
AddLabelletsyousetlegendelementsprogrammatically.
AngleX
Overview|Properties|Methods
SetthispropertytotheamountofrotationaroundtheX-axisforthepreviouslydisplayedchartobjectbeforecallingtheRotatemethod.
Syntax
PieChartObject.AngleX=[double]
TheAngleXpropertysyntaxhasthefollowingparts:
Part Description
double ThedegreeofrotationofthechartobjectaroundtheX-axisthelasttimeitwasdisplayed.
Remarks
Inordertorotateachartyoumustletthechartinstanceknowwhattherotationalangleswereafterthelastrotationoperation(defaultsareusedwhenthefirstrotationoccurs)beforecallingtheRotatemethod.Thismeansthatyoumustpreservestateinformation(e.g.usesession-levelvariables,hiddeninputboxes,etc.)betweenChartobjectcreation/deletion.
OnceyouhavesettheAngleX,AngleYandAngleZpropertiesthechartobjectthenknowsitslocationassetbyapreviousrotationoperation,andyoucanthencalltheRotatemethodtorotatethechart.OncethisisdoneMAKESUREthatyourecordthenewX,YandZanglesforthechart(tobeusedifthechartisrotatedagain).Tosavethechart'snewpositionrecord(e.g.sessionvariables)theAngleX,AngleYandAngleZproperties.
RefertotheRotationTutorialforsamplesourcecodedemonstrating
rotation.
SeeAlso:Rotate|Tutorial:Rotation
AngleY
Overview|Properties|Methods
SetthispropertytotheamountofrotationaroundtheY-axisforthepreviouslydisplayedchartobjectbeforecallingtheRotatemethod.
Syntax
PieChartObject.AngleY=[double]
TheAngleYpropertysyntaxhasthefollowingparts:
Part Description
double ThedegreeofrotationofthechartobjectaroundtheY-axisthelasttimeitwasdisplayed.
Remarks
Inordertorotateachartyoumustletthechartinstanceknowwhattherotationalangleswereafterthelastrotationoperation(defaultsareusedwhenthefirstrotationoccurs)beforecallingtheRotatemethod.Thismeansthatyoumustpreservestateinformation(session-levelvariables,hiddeninputboxes,etc.)betweenChartobjectcreation/deletion.
OnceyouhavesettheAngleX,AngleYandAngleZpropertiesthechartobjectthenknowsitslocationassetbyapreviousrotationoperation,andyoucanthencalltheRotatemethodtorotatethechart.OncethisisdoneMAKESUREthatyourecordthenewX,YandZanglesforthechart(tobeusedifthechartisrotatedagain).Tosavethechart'snewpositionrecord(e.g.sessionvariables)theAngleX,AngleYandAngleZproperties.
RefertotheRotationTutorialforsamplesourcecodedemonstratingrotation.
SeeAlso:Rotate|Tutorial:Rotation
AngleZ
Overview|Properties|Methods
SetthispropertytotheamountofrotationaroundtheZ-axisforthepreviouslydisplayedchartobjectbeforecallingtheRotatemethod.
Syntax
PieChartObject.AngleZ=[double]
TheAngleZpropertysyntaxhasthefollowingparts:
Part Description
double ThedegreeofrotationofthechartobjectaroundtheZ-axisthelasttimeitwasdisplayed.
Remarks
Inordertorotateachartyoumustletthechartinstanceknowwhattherotationalangleswereafterthelastrotationoperation(defaultsareusedwhenthefirstrotationoccurs)beforecallingtheRotatemethod.Thismeansthatyoumustpreservestateinformation(session-levelvariables,hiddeninputboxes,etc.)betweenChartobjectcreation/deletion.
OnceyouhavesettheAngleX,AngleYandAngleZpropertiesthechartobjectthenknowsitslocationassetbyapreviousrotationoperation,andyoucanthencalltheRotatemethodtorotatethechart.OncethisisdoneMAKESUREthatyourecordthenewX,YandZanglesforthechart(tobeusedifthechartisrotatedagain).Tosavethechart'snewpositionrecord(e.g.sessionvariables)theAngleX,AngleYandAngleZproperties.
RefertotheRotationTutorialforsamplesourcecodedemonstratingrotation.
SeeAlso:Rotate|Tutorial:Rotation
CodePage
Overview|Properties|Methods
Setthispropertytoutilizealanguageotherthanenglish.
Syntax
PieChartObject.CodePage=[long]
TheCodePagepropertysyntaxhasthefollowingparts:
Part Description
long RepresentsavalidcodepageforthesystemwhichisrunningtheASPengine.
Remarks
Acodepageisacharactersetwhichisusedtointerpretanddisplaydata.Differinglanguagesandlocalescanbeusedbysettingthispropertytothedesiredcodepage.
SetthispropertyatthebeginningofyourASPcode,beforeyoucallSendJPEG.
PleasenotethattheDundasPieChartServercomponentfullysupportsUnicode.
Refertothetablebelowforalistingofcodepages:
CodePage
Description
1252 ISOCharacterSet(default)
850
Multilingual
437
U.S.English
874
Thai
932
Japanese
936
Chinese(simplified)
949
Korean
950
Chinese(traditional)
1250
CentralEuropean
1251
Cyrillic
1253
Greek
1254
Turkish
1255
Hebrew
1256
Arabic
1257 Baltic
FormoreinformationaboutcodepagesrefertotheMSDNlibrary.
CreateJpegFile
Overview|Properties|Methods
Savestheresultingjpegtodisk.
Syntax
long=PieChartObject.CreateJpegFile(FileNameAsString,WidthAsLong,HeightAsLong,[CompressionAsLong])
TheCreateJpegFilemethodsyntaxhasthefollowingparts:
Part Description
FileName Thefullpathnameofthefiletobesavedtodisk.
Width Widthofthesavedjpeginpixels.
Height Heightofthesavedjpeginpixels.
Compression Amountofcompression(0to100).
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursyoucanusethisreturnvalueastheargumentforGetErrorTextinordertoretrievearelevanttexterrormessage,oralternativelyyoucanremoutthe"OnErrorResumeNext"statementandobservethethrownexceptionforadescriptionoftheerror.
Remarks
Youcanusethisasatestmethodtoseeifthecontrolisactuallyproducingajpeg.
YoucanalsousethismethodinaVB(VisualBasic)applicationandthencallVB'sLoadPicturemethodtoassignthejpegtoaPictureBoxorImagecontrol.
SeeAlso:SendJPEG
DirTemplate
Overview|Properties|Methods
Setsorretrievesthedirectorywheretemplatesarestored.
Syntax
PieChartObject.DirTemplate=[string]
TheDirTemplatepropertysyntaxhasthefollowingparts:
Part Description
string Thefullpathnameofthefolderwhichstoresthetemplates.
Remarks
Thetemplatefolderiswhereallofyourtexturesmustbelocatedinordertobeavailableforloadingintoapiechart.
YouMUSTsetthispropertybeforeloadingatemplate.
SeeAlso:DirTexture
DirTexture
Overview|Properties|Methods
Setorretievesthedirectorywherethetexturesmustbestored.
Syntax
PieChartObject.DirTexture=[string]
TheDirTexturepropertysyntaxhasthefollowingparts:
Part Description
string Thefullpathnameofthefolderwhichstoresthetextures.
Remarks
Yourtexturesmustbelocatedinthisfolder.
NOTE:YouMUSTsetthispropertyBEFOREloadingatemplate.
SeeAlso:DirTemplate
GetErrorText
Overview|Properties|Methods
Outputsarelevanterrorstringbasedonareturnederrorcode.
Syntax
string=PieChartObject.GetErrorText(ErrorCodeAsLong)
TheGetErrorTextmethodsyntaxhasthefollowingparts:
Part Description
ErrorCode Anerrorcodewhichisreturnedfromafunctioncall.
string Anerrorstringwhichdescribestheerrorthatoccurred.
Returns
Anerrorstring.
Remarks
AllfunctionswiththeexceptionofGetErrorTextreturnanerrorcode(along)whichsignifiesthesuccess/failureoftheoperation.Zero(0)isreturnediftheoperationissuccessful,otherwiseanon-zerovalueisreturned.Ifthereturnisnon-zeroyoucanuseGetErrorTexttoretrieveanerrorstring.
NOTE:ThePieChartServercontrolwillalsothrowanexceptionifanerroroccurs,soinsteadofusingtheGetErrorTextmethodyou
canexaminethethrownexceptionforameaningfulerrormessage.
WhenattemptingtoobtainameaningfulerrormessageyouMUSTloadthepageproducingthejpeg(i.e.thepagewiththeSendJPEGcall)directlyintoyourbrowser(i.e.donotloadthispagewithan<IMG>tagfromanotherpage).
GetSelectedPosition
Overview|Properties|Methods
Usethismethodtodeterminewhichdataelementtheuserselected(zero-based).
Syntax
long=PieChartObject.GetSelectedPosition()
Remarks
CallthismethodONLYWHENyouhavesuccessfullycalledtheSelectmethodinsidethepagewhichishandlingtheitemselection,specifiedbytheSRCattributeofthe<A>tagimmediatelyprecedingtheserver-sidechartimagetag(e.g.<AHREFSRC="PageToHandleSelectedItem.asp"><IMGIsMapSRC="MakeJpeg.asp"></A>).Thereturnvaluewillbethedataelementthattheuserclickedon.
Thisisusefulindrilldownscenarioswhereyoucantakeappropriateaction(e.gshowanotherchartimage)basedonthepieslicetheuserselected.
GetSelectedPositioniszero-based,soareturnofzero(0)indicatesthattheuserselectedthefirstelementaddedtothechartwiththeAddDatamethod.
YoushouldfirstcallGetSelectedSeriestomakesurethattheuserclickedonapiesliceoralegenditem.
Iftheuserclicksonalegenditemthenthecorrespondingpieslice'spositionisreturned.
IMPORTANT:ThereturnnumberrepresentstheselectedelementaspertheorderthatthedataelementswereaddedviatheAddDatamethod.Thishascertainramificationssinceapiecharttypescanbesetuptouse
a"collected"element.Ifanelementiscollecteditwillstillbecountedasaposition.Forexample,ifthefirstelementiscollected(andthereforeonlyvisibleasthecollectedelement)thenGetSelectedPositionwillreturnone(asopposedtozero)iftheuserclicksonthefirstvisiblepieslice.
NOTE:EventhoughthepagewhichhandlestheselectiondoesnotoutputajpegweMUSTreproducetheexactsamechartwhichiscreatedbythepagewithinthe<IMG>tag(thepagewhichoutputsthejpegviaSendJPEG).Inordertoguaranteethattheexactsamechartisreproducedwehighlyrecommendusingaserver-sideincludeforthecodewhichcreatesthechart(startingfromtheCreateObjectcallallthewaytosettingtheChartobjecttoNothing).
ForsamplesourceonthisrefertotheTutorial:DrilldownandSelectionofDataElements.YoucanalsoexaminetheSelection,GrandPrixorGrossDomesticProduct(Drilldown)sampleswhicharedistributedwiththeChartServerControlforsamplesourcecodeabouttheSelect,GetSelectedPositionandGetSelectedSeriesmethods.
SeeAlso:GetSelectedSeries|Select
GetSelectedSeries
Overview|Properties|Methods
Usethismethodtodeterminewhichdataseriestheuserselected(zero-based).Notethatpiechartsonlyuseonedataseries.
Syntax
long=PieChartObject.GetSelectedSeries()
Remarks
GetSelectedSeriesiszero-based,andwill:
return-999iftheuserclickedonthecollecteddataelement.
returnanegativenumberiftheuserclickedanywhereexceptadataelementorthelegenditemthatcorrespondstoapieslice.
alwaysreturnzero(0)iftheuserselectedanactualdataelement(i.e.pieslice).
Eventhoughpiechartshaveonlyonedataseriesyoushouldstillcallthismethodtomakesureanactualsliceorlegenditemwasselected!
CallthismethodONLYWHENyouhavesuccessfullycalledtheSelectmethodinsidethepagewhichishandlingtheitemselection(asspecifiedbytheSRCattributeofthe<A>tagimmediatelyprecedingtheserver-sidechartimagetag).Thereturnvaluewillbethedataelementthattheuserclickedoninsideofthechartserver-sideimagemap(<AHREFSRC="PageToHandleSelectedItem.asp"><IMGIsMapSRC="MakeJpeg.asp"></A>).
Important:Eventhoughthepagewhichhandlestheselection(i.ethepagewhichhastheGetSelectedSeriescall)doesnotoutputajpegweMUSTreproducetheexactsamechartwhichiscreatedbythepage
withinthe<IMG>tag(thepagewhichoutputsthejpegviaSendJPEG).Inordertoguaranteethattheexactsamechartisreproducedwehighlyrecommendusingaserver-sideincludeforthecodewhichcreatesthechart(startingfromtheCreateObjectcallallthewaytosettingtheChartobjecttoNothing).
ForsamplesourceonthisrefertotheTutorial:DrilldownandSelectionofDataElements.
SeeAlso:GetSelectedPosition|Select|SetCollectedLimit|SetCollectedProp
LoadTemplate
Overview|Properties|Methods
Loadsatemplateintoapiechart.
Syntax
long=PieChartObject.LoadTemplate(FileNameAsString)
TheLoadTemplatemethodsyntaxhasthefollowingparts:
Part Description
FileName Thenameofthetemplatetoload.
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursyoucanusethisreturnvalueastheargumentforGetErrorTextinordertoretrievearelevanttexterrormessage,oralternativelyyoucanremoutthe"OnErrorResumeNext"statementandobservethethrownexceptionforadescriptionoftheerror.
Remarks
Templatesdefinechartcharacteristicssuchasthetitle,defaulttexturesandcolorsfordataelements(pieslices),labels,lightingproperties,etc.UsetheTemplateCreatortocreateorchangetemplatesforusewiththeDundasPieChartServercontrol.
CallLoadTemplateBEFOREyousettheTitlepropertyoruseanyoftheobject'smethods,otherwisethedefaulttemplatevalueswilloverwriteyourproperties/data.
ForadescriptionofthestepswhichshouldbefollowedtocreateapiechartandtheorderinwhichtheyshouldbeperformedseetheDundasPieChartServerControlOverview.
SeeAlso:TemplateCreatorOverview|DirTemplate
DundasPieChartServerControlMethods
Copyright©DundasSoftwareLtd.2000.AllRightsReserved
Overview|Properties|Methods
AddData Callthismethodtoadddataelements(slices)toapiechart.
AddLabel Setsthelegendtextforapieslice.
CreateJPEGFile Savesapiecharttodiskasajpegfile.
GetErrorText Retrievesanerrorstringbasedonareturnederrorcode.
GetSelectedPosition Returnsthepieslicetheuserselected(clickedon).
GetSelectedSeries Returnsthedataseriestheuserselected(clickedon).
LoadTemplate Loadsatemplateintoapiechartobject.
Select MUSTbecalledbeforeusingGetSelectedPositionandGetSelectedSeries.
SendJPEG Outputsthepiechartobjectinajpegformat.
SetCollectedLimit Setsthelimitatwhichdataelementswillbeincorporatedintothecollecteddataelement.
SetCollectedProp Setsthepropertiesofthecollecteddataelement.
SetExploded Explodesapieslice.
DundasPieChartServerControlProperties
Copyright©DundasSoftwareLtd.2000.AllRightsReserved
Overview|Properties|Methods
AngleX TheamountofrotationaroundtheX-axisforthepreviouslydisplayedchartobject(mustbesetbeforecallingtheRotatemethod).
AngleY TheamountofrotationaroundtheY-axisforthepreviouslydisplayedchartobject(mustbesetbeforecallingtheRotatemethod).
AngleZ TheamountofrotationaroundtheZ-axisforthepreviouslydisplayedchartobject(mustbesetbeforecallingtheRotatemethod).
CodePage Thecodepagetobeused.
DirTemplate Setsorretrievesthefolderwhichstoresthetemplates.
DirTexture Setsorretrievesthefolderwhichstoresthetextures.
Title Setsorretrievesthetitleofthepiechart.
Rotate
Overview|Properties|Methods
Callthismethodtorotateachart.
Syntax
long=PieChartObject.Rotate(AngleAsDouble,AxisAsLong)
TheRotatemethodsyntaxhasthefollowingparts:
Part Description
Angle Thisistheangleatwhichtherotationshouldbesetfortheaxispassedin.Theangleisspecifiedindegrees,andisrelativetothecurrentposition(e.g.thevaluespecifiedinapreviouscalltoRotateoronefoundinthetemplate).
Axis Theaxistohavethechartrotatedaround.Thisvalueshouldbezero(0)fortheX-axis,one(1)fortheY-axis,andtwo(2)fortheZ-axis.
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursusethisreturnvalueastheargumentforGetErrorTextinordertoretrievearelevanttexterrormessage.
Remarks
Makesureyouonlycallthismethodafteraddingalldatatothechartobject.
Inordertorotateachartyoumustletthechartinstanceknowwhattherotationalangleswereafterthelastrotationoperation(defaultsareusedwhenthefirstrotationoccurs)beforecallingtheRotatemethod.Thismeansthatyoumustpreservestateinformation(session-levelvariables,hiddeninputboxes,etc.)betweenChartobjectcreation/deletion.
TosettheinitialrotationanglesuseyourpreservedstateinformationandsettheAngleX,AngleYandAngleZproperties.OnceyouhavesetthepreviousrotationanglesyoucancalltheRotatemethodtorotatethechart.OncethisisdoneMAKESUREthatyourecordthenewX,YandZanglesforthechart(tobeusedifthechartisrotatedagain).Tosavethechart'snewpositionrecord(e.g.sessionvariables)theAngleX,AngleYandAngleZproperties.
NOTE:ifyourepeatedlycallthismethod(torotatearoundallthreeaxis)andyouthencallSendJPEGyoumustremembertheorderofrotationforthedifferentaxis.Inotherwords,ifyourotatearoundtheX,Y,andZ-axisinthatorderthenthenexttimeyourotatethechartyoumustrotatearoundtheX,Y,andZ-axisusingthesameorder.
Notethatrotationoccursinscreencoordinates,notchartcoordinates(e.g.thez-axisisalwaysatrightanglestothescreen).
RefertotheRotationTutorialforsamplesourcecodedemonstratingrotation.
SeeAlso:AngleX|AngleY|AngleZ|Tutorial:Rotation
Select
Overview|Properties|Methods
CallthismethodsothatyoucanutilizetheGetSelectedPositionandGetSelectedSeriesmethodswhenworkingwithaserver-sidechartimagemap(i.e.implementingdrilldownand/orselection).
Syntax
long=PieChartObject.Select(XAsLong,YAsLong,WidthAsLong,HeightAsLong)
TheSelectmethodsyntaxhasthefollowingparts:
Part Description
X TheX-coordinateofthemousepositionwheretheuserclicked.Usethequerystring'sfirstnumber(fromtheimagemap)forthisargument.
Y TheY-coordinateofthemousepositionwheretheuserclicked.Usetheresultingquerystring'ssecondnumberforthisargument.
Width Theheightofthejpegimage(assetintheSendJPEG()call).
Height Thewidthofthejpegimage(assetintheSendJPEG()call).
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursusethisreturnvalueastheargumentforGetErrorTextinordertoretrievearelevanttexterrormessage.
Remarks
Callthismethodinapagewhichisloadedasaresultofaserver-sidechartimagemapbeingclickedoninordertofindoutwhichdataelementwasselected.Thismethodisusedwhenworkingwithadrill-downtypeofscenario.
TosettheXandYargumentsyouwillneedtoparsethepassedquerystringitem(themousepositionwithasyntaxof"201,75")whichresultsfromtheIsMapattributewithinthe<IMG>tag.Toparsethisdata()usetheInStrVBScriptfunction.Thefirstnumberinthequerystringwillbethemouse'X-coordinate,whilethesecondquerystringvalueisthecorrespondingmouse'Y-coordinate.
IMPORTANT:EventhoughthepagewhichhandlestheselectiondoesnotoutputajpegweMUSTreproducetheexactsamechartwhichiscreatedbythepagewithinthe<IMG>tag(thepagewhichoutputsthejpegviaSendJPEG).Inordertoguaranteethattheexactsamechartisreproducedwehighlyrecommendusingaserver-sideincludeforthecodewhichcreatesthechart(startingfromtheCreateObjectcallallthewaytosettingtheChartobjecttoNothing).
TheheightandwidthargumentsshouldmatchthosespecifiedinthecorrespondingSendJPEGcallaswellasthosewhichmayhavebeenspecifiedasHeightandWidthattributesintherelevant<IMG>tag.
ForsamplesourceonthisrefertotheTutorial:DrilldownandSelectionofDataElements.YoucanalsoexaminetheSelection,GrandPrixorGrossDomesticProduct(Drilldown)sampleswhicharedistributedwiththeChartServerControlforsamplesourcecodeabouttheSelect,GetSelectedPositionandGetSelectedSeriesmethods.
SeeAlso:GetSelectedPosition|GetSelectedSeries|Tutorial:Drilldown
andSelectionofDataElements
SendJPEG
Overview|Properties|Methods
OutputsabinarystreaminJPEGformatbyusingtheResponse.BinaryWriteAspmethod.
Syntax
long=PieChartObject.SendJPEG(WidthAsLong,HeightAsLong,[CompressionAsLong=20],[SmoothingAsLong=20])
TheSendJPEGmethodsyntaxhasthefollowingparts:
Part Description
Width Widthofthejpeg(pixels).
Height Heightofthejpeg(pixels).
Compression Theamountbywhichtheoriginalpiechartimageiscompressed.Rangesfrom0to100(nocompressiontomaximumcompression).
Smoothing Theamountofsmoothingthatoccursforthejpegimage.Rangesfrom0to100(nosmoothingtomaximumsmoothing).
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)is
returnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursyoucanusethisreturnvalueastheargumentforGetErrorTextinordertoretrievearelevanttexterrormessage,oralternativelyyoucanremoutthe"OnErrorResumeNext"statementandobservethethrownexceptionforadescriptionoftheerror.
Remarks
OutputsajpegfilebyusingtheResponse.BinaryWriteAspmethod.
TherearetwowaystoembedthisjpegfileintoanAsppage.Thefirstistousean<IMG>tagandsettheSRCattributetothesecondaryAsppagewhichisresponsibleforcreatingtheAspPieChartobjectandcreatingthepiechart(seeOverviewformoredetails).Thesecondmethodisthesameasthefirstexceptweusean<A>taginsteadofan<IMG>tag.ForanexampleofthisseetheAspdemopages.Youcanalsorefertotheoverviewformoreinformation.
IMPORTANT:TheResponse.BinaryWritemethodutilizesHTTPheaders,andasaresultyouCANNOTinsertanyhtmlcodeintotheAsppagebeforecallingthismethod!
SeeAlso:CreateJPEGFile|Overview
SetCollectedLimit
Overview|Properties|Methods
Setsthevalueatwhichadataelement(pieslice)willbecollected.
Syntax
long=PieChartObject.SetCollectedLimit(LimitAsDouble,[LimitTypeAsLong])
TheSetCollectedLimitmethodsyntaxhasthefollowingparts:
Part Description
Limit Thevalueatwhichadataelementwillbecomea"collected"element.
LimitType Thelimittype.Ifthisiszero(0)thenthesizeoftheelementasapercentagewillbeused.Ifthisissettoone(1)thenthesizeofthepieelementwillbeused.
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursyoucanusethisreturnvalueastheargumentforGetErrorTextin
ordertoretrievearelevanttexterrormessage,oralternativelyyoucanremoutthe"OnErrorResumeNext"statementandobservethethrownexceptionforadescriptionoftheerror.
Remarks
Smalldataelementsare"collected"andthendisplayedtogetherasonepieslicecalledthe"collected"element.SetCollectedLimitdeterminesatwhichpointanelementwillbeapartofthecollectedelement.
SeeAlso:Overview|SetCollectedProp
SetCollectedProp
Overview|Properties|Methods
Setsthepropertiesforthecollecteddataelement.
Syntax
long=PieChartObject.SetCollectedProp([LabelAsString],[ColorAsLong=16711680],[TextureAsString])
TheSetCollectedPropmethodsyntaxhasthefollowingparts:
Part Description
Label Thelabelwhichwillbedisplayednexttothecollecteddataelement.
Color Theunderlyingcolortobeusedforthecollectedpieslice.
Texture Thetexturetobeusedforthecollecteddataelement.
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursyoucanusethisreturnvalueastheargumentforGetErrorTextinordertoretrievearelevanttexterrormessage,oralternativelyyoucanremoutthe"OnErrorResumeNext"statementandobservethethrownexceptionforadescriptionoftheerror.
Remarks
Smalldataelementsare"collected"andthendisplayedtogetherasonepieslicecalledthe"collected"element.
SetCollectedPropsetsthepropertiesofthecollectedpieslice.Ifthetemplate(whichMUSTbeloadedbeforecallingthismethod)definesdefaultvaluesforthecollecteddataelementthenthesedefaultvalueswillbeusedifyoudonotspecifyacollectedproperty.Forexample,ifyoucallSetCollectedPropandspecifyalabelandunderlyingcolortobeusedforthecollectedpieslicethenthedefaultvalues(iftheyaredefinedinthetemplate)willnotbeused,butthedefaulttexturewillbeusedsincewedidnotspecifyatextureintheSetCollectedPropcall.
SeeAlso:SetCollectedLimit|LoadTemplate|TemplateCreatorOverview
SetExploded
Overview|Properties|Methods
Callthismethodtoexplodeaparticularpieslice.
Syntax
long=PieChartObject.SetExploded([IndexAsLong=-1])
TheSetExplodedmethodsyntaxhasthefollowingparts:
Part Description
Index Zero(0)basedindexofthedataelements(pieslices)inthepiechart.Setthisto-1(ordonotspecifytheindexatall)toexplodethecollectedpieslice.
long Returnsalongindicatingthesuccessorfailureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.
Returns
Alongwhichindicatesthesuccess/failureoftheoperation.Zero(0)isreturnedifsuccessful,otherwiseanon-zerovalueisreturned.IfanerroroccursyoucanusethisreturnvalueastheargumentforGetErrorTextinordertoretrievearelevanttexterrormessage,oralternativelyyoucanremoutthe"OnErrorResumeNext"statementandobservethethrownexceptionforadescriptionoftheerror.
Remarks
Callthisfunctiontoexplodeapieelementorthecollectedelement.
Ifyouspecifyadataelementtobeexplodedandtheelementendsupbeingcollecteditwillnotbeexploded(unlessthecollecteddataelementissetuptobeexploded).However,ifyouweretodecreasethelimitatwhichelementsarecollectedbycallingSetCollectedLimitandthesamepiesliceisnolongeracollectedelementitwillthenbeexploded.Inotherwords,itremembersthatitissupposedtobeexploded.
YouMUSTcallAddDatabeforeexplodingpieelements.
SeeAlso:SetCollectedLimit|SetCollectedProp
Title
Overview|Properties|Methods
Setsorretrievesthetitleofthepiechart.
Syntax
PieChartObject.Title=[string]
TheTitlepropertysyntaxhasthefollowingparts:
Part Description
string Thetitleofthepiechart.
Remarks
Setsorretrievesthetitleofthepiechart.UsethispropertyAFTERthetemplateisloaded,otherwisethedefaulttitlefromthetemplatewillbeusedinstead.
SeeAlso:LoadTemplate
TemplateCreatorOverview
Copyright©DundasSoftwareLtd.2000,AllRightsReserved
TheTemplateCreatorenableseditingandmanipulationofapiecharttemplate.Atemplateisabinaryfilethatstoresreusablechartinformation,andalltemplateshaveafileextensionof".cuc".YoucanalsocreateanewtemplatewiththeTemplateCreator.
Templatesdefinethecharacteristicsofachart,andareloadedbytheDundasPieChartServercontrolviatheLoadTemplatemethod.
Piechartpropertiesareeditedbypropertypages.Todisplayapropertysheeteitherdouble-clickonapiechartelementorright-clickoveranelementandselect'Properties'.
IMPORTANT:theTemplateCreatorwillonlyfunctioncorrectlyifyourscreenresolutionissetuptodisplayatleast32kcolors.
TheDundasPieChartServercontrolcanloadatemplateandcreateajpegimagefromit.TominimizetheamountofwhitespaceintheresultingjpegmakethepiechartimageaslargeaspossibleintheTemplateCreator.
Bydefaultanewtemplatewillnotdisplaythelastpieslicebecauseitiscollected.Toviewthislastslice(whichiscollectedandthereforenotvisible)openthePieElementpropertypageforANYvisiblesliceandsettheCollectedDataLimittozeropercent.Thismakessurethatnoelementsarecollected(allpiesliceswillbevisible).IfyouwanttodeterminewhichsliceisthecollectedsliceopenthesamepropertypageandsettheCollectedDataLimitto100%,therebycausingallslicestobecollected.Theresultingpiechartwillthendisplayonlythecollectedslice.Tochangethetexture/colorofthecollectedsliceright-clickoverit,selectthePropertiesmenuitemandthenchoosetheTexturespropertypage.
Thevalues(sizes)oftheslicesareindicatedbyTooltipswhichappear
whenyourestthemousecursoroverapieslice.
Thecreatorallowsyoutousegradientcolorsforthetemplatebackground,legends,staticnotes(labels)andthetitle.
SomechartpropertiescanonlybesetbytheDundasPieChartServercontrol(likedatavaluesorlabels),whileotherscanonlybesetbytheTemplateCreator(e.g.backgroundcolorsandtextures,thepieorientationorthelightdirection).SomepropertiescanbesetbyboththecontrolandbytheTemplateCreator(e.g.texturesandcolorsofpieslices).Refertothetablebelowformoredetailedinformation:
PropertyName TemplateCreator DundasPieChartServerControl
Background
allproperties Yes No
Title
position Yes No
fontproperties Yes No
text Yes Yes
Piechartorientation Yes No
Lightparametersanddirection
Yes No
Legend
position Yes No
borderstyle Yes No
fontproperties Yes No
labels No Yes
Piechart
size Yes No
roundingradius Yes No
numberofroundingpoints
Yes No
parametersforcollecteddata
Yes Yes
labelforcollecteddata
Yes Yes
numberofpieslices
Yes(sliceswillhavedefaultvalues)
Yes
sidetexture Yes No
disabletextures Yes No
disablelighting Yes No
Pieslice(element)
value No No
color/texture Yes(savedasthedefaultvalues)
No
exploded Yes(notsaved) No
labeltext Yes(notsaved) No
labelfont Yes Yes
Staticnotes
allproperties Yes No
Pleasenotethatatemplatedoesnotsavedataforachartobject.
ThefilenameoftheTemplateCreatorisPieTEditor.exe.
TobeabletoresizealegendtheAutoSizeoptionMUSTBEselected(intheLablespropertypageforalegendelement).
IMPORTANT:fortheTemplateCreatortoworkcorrectlytheIntelcompressionlibrary(ijl15.dll)mustbelocatedeitherinyoursystemdirectoryoratthesamedirectorylevelastheTemplateCreator.Also,inordertousethedistributedtexturesthe"Textures"folder(whichstoresthesetextures)mustalsoexistatthesamedirectorylevelastheCreator).
SeeAlso:DundasPieChartServer-DemoOverview|Overview(DundasPieChartServerControl)|CollectedData
HowtousetheTemplateCreator
TheTemplateCreatorletsyoucreateand/ormanipulatetemplatestobeusedwiththeDundasPieChartServerControl.TheTemplateCreatorcanbeaccessedviatheStartMenuEntrynamed"PieChartTemplateCreator".
Theapplicationmenuletsyoucreate,open,andsavetemplatestodisk.Thepopupmenuallowsyoutoopenapropertysheetforpropertyediting,switchtoeitherSizeorMovemode,andworkwithstatictextlabels.
Thepropertiesofelementsareavailableforeditingviapropertysheets.Thepossiblepropertypagesare:PieElement;DataLabel;Texture;Size-Move;Light;Labels;LinePatterns;Title;andScene.
Notethatthepropertypagesdisplayeddependsonthetypeofelementyouclickover,soonlysomeofthepageslistedabovewillbeshown.
Torotateachartusethekeyboard'snavigationalkeys.FormoredetailsseeRotatingaChart.
ForalistingofpiechartpropertiesthatcanbeeditedviatheTemplateCreatorseetheoverview.
Bydefaultanewtemplatewillnotdisplaythelastpieslicebecauseitiscollected.Toviewthislastslice(whichiscollectedandthereforenotvisible)openthePieElementpropertypageforANYvisiblesliceandsettheCollectedDataLimittozeropercent.Thismakessurethatnoelementsarecollected(allpiesliceswillbevisible).IfyouwanttodeterminewhichsliceisthecollectedsliceopenthesamepropertypageandsettheCollectedDataLimitto100%,therebycausingallslicestobecollected.Theresultingpiechartwillthendisplayonlythecollected'slice'.Youcanthenchangethetexture/colorofthecollectedslicebyright-clickingoverit,selectingthePropertiesmenuitemandthenchoosingtheTexturespropertypage.
Anewtemplaterandomlysetsthecolorsofthepieslices.
IMPORTANT:fortheTemplateCreatortoworkcorrectlytheIntelcompressionlibrary(ijl15.dll)mustbelocatedeitherinyoursystemdirectoryoratthesamedirectorylevelastheTemplateCreator.Also,inordertousethedistributedtexturesthe"Textures"folder(whichstoresthesetextures)mustalsoexistatthesamedirectorylevelastheTemplateCreator).
SeeAlso:TemplateCreatorOverview|CollectedDataElements
ApplicationMenu-TemplateCreator
Theapplicationmenuletsyouperformthefollowingactions:
File
New Createanewtemplate.Bydefaultthefirstsliceiscollected.
Open Openatemplateforediting.
Save Savethetemplate.
SaveAs Savethetemplatewithanewfilename.
Pie
AddPieSlice Addanotherpieslicetothepiechart.
Add3PieSlices
Addsthreepieslices.
DeletePieSlice Deletethelastpiesliceinthepiechart(eachsliceisidentifiedbyanindex).
Delete3PieSlices
Deletethelastthreepieslicesinthetemplate.
SeeAlso:PopupMenu|CollectedDataElements
CollectedDataElements
Collecteddataconsistsofallpiesliceswhichfallbelowaminmumvalue,andisindicatedtotheuserwithaspecial"collected"pieslicewhichhasitsowncolor/texture.Thiscollectedpiesliceeliminatessituationswheretherearenumeroussliceswhichcannotbedrawnproperly(i.e.iftherearetwentysliceswhichareverysmallthentheresultingpiechartwouldbeverymessyiftherewasnocollectedpieslice).
BydefaultaNEWtemplatewillnotdisplaythelastpieslicebecauseitiscollected.Toviewthislastslice(whichiscollectedandthereforenotvisible)openthePieElementpropertypageforANYvisiblesliceandsettheCollectedDataLimittozeropercent.Thismakessurethatnoelementsarecollected(allpiesliceswillbevisible).IfyouwanttodeterminewhichsliceisthecollectedsliceopenthesamepropertypageandsettheCollectedDataLimitto100%,therebycausingallslicestobecollected.Theresultingpiechartwillthendisplayonlythecollected'slice'.Tochangethetexture/colorofthecollectedsliceright-clickoverit,selectthePropertiesmenuitemandthenchoosetheTexturespropertypage.
Anewtemplaterandomlysetsthecolorsofthepieslices.Thelastsliceiscollected,sothecollectedpiesliceisshowninsteadofthelastslice.
TheCollectedDataLimitdetermineshowsmallaslicemustbebeforeitisaddedtothecollectedslice.Thiscanbeeitherapercentageoftheentirepieoranabsolutevalue.
SeeAlso:HowtousetheTemplateCreator|TemplateCreatorOverview|PieElementPropertyPage
DataLabelPropertyPage-TemplateCreator
Thedatalabelpropertypageisonlyavailableforpieslices.
Todisplaythispropertypageeitherdouble-clickonapiesliceorright-clickoverapiesliceandselect'Properties'.
Thefollowingisadescriptionofwhatyoucandoviathispropertypage:
EditDataLabel Changethelabeltextforthepiesliceyouright-clickedover.
Orientation Settheorientationofthepieelementlabeltoeitherverticalorhorizontal.
Font(allitems) Setthefonttype,fontsize,andfontcolor.
Effects Setthecolorofthelabel.
SeeAlso:HowtousetheTemplateCreator|PopupMenu-TemplateCreator
GradientPropertyPage-TemplateCreator
Thegradientpropertypageisavailableforalltemplateitemsexceptpieslices.
Todisplaythispropertypageeitherdouble-clickonanelementorright-clickoveranelementandselect'Properties'.
Thefollowingisadescriptionofwhatyoucandoviathispropertypage:
Solid Displaystheselecteditemwithauniformlycoloredbackground.
Gradient Displaystheselecteditemwithacoloredgradientbackground.
Transparent Displaystheselecteditemwithatransparentbackground.Notavailableforthebackgroundofthetemplateitself.
ShadingStyles:
Horizontal Shadingoccurshorizontally.
Vertical Shadingoccursvertically.
DiagonalUp Shadingoccursfromthebottomleft-handcornertothetopright-handcorner.
DiagonalDown
Shadingoccursfromthebottomright-handcornertothetopleft-handcorner.
FromCorner Shadingoccursfromonecorneronly.
FromCenter Shadingoccursfromthecenteronoutwards.
Color Determineswhichtwo(2)colorsaretobeusedfortheshading.
FillStyles Determineshowtheshadingstylewillbeimplemented.Youcanchooseanyoneofthefour(4)availablefillstyles.
SeeAlso:HowtousetheTemplateCreator
LabelsPropertyPage-TemplateCreator
Thelabelspropertypageisonlyavailableforlegendelements.
Todisplaythispropertypageeitherdouble-clickonalegendelementorright-clickoveralegendelementandselect'Properties'.
TobeabletoresizethelegendtheAutoSizeoptionMUSTbeselected.
Thefollowingisadescriptionofwhatyoucandoviathispropertypage:
EditLabels Changethetextofaparticularlegenditem.
Font Specifythefonttobeusedforthelegenditem.
FontStyle Specifythefontstyletobeusedforthelegenditem.
Size Specifythefontsizeforthelegenditem.
Effects:
Color ThetextcolorofALLthelegenditems.
AutoSize Automaticallysizesthelegenditems.ThisMUSTbecheckedifyouwanttoresizethelegend.
SeeAlso:HowtousetheTemplateCreator
LightPropertyPage-TemplateCreator
Thelightpropertypageisavailablefortheareaelement(background)aswellaspieslices.Pleasenotethatsettinglightparametersforonechartelementwillchangethelightsettingsfortheentirepiechart.
Todisplaythispropertypageeitherdouble-clickonthebackgroundorpiesliceoralternativelyright-clickoverthebackgroundorapieelementandselect'Properties'.
Thefollowingisadescriptionofwhatyoucandoviathispropertypage:
DirectionalSphere(largeredball)
Usethisitemtosetthedirectionthatthelightwillstrikeyourpiechart.Youcaneitherusethereddirectionalarrowsoralternativelyyoucanleft-click,holdthebuttondownandmovethedirectionalsphereinthedesireddirection.
LightDisabled Disablealllightingeffects.
RotationStep Setstheincrementbywhichthelightdirectionwillchange(e.g.howquicklytheredballwillrotate).
LightParameters:
Ambient ChangetheRGB(Red,Green,Blue)valuesoftheambient(non-directional)light.
Diffuse ChangetheRGBvaluesofthediffuselight.Diffuse
lightisreflected,anditsintensityvariesdependingontheanglebetweenthepixel'snormalvectorandthedirectionofthelightsource.
Specular ChangetheRGBvaluesofthespecularlight.Specularlightisalsoreflected,butitsintensityvarieswiththeanglebetweentheviewerandthedirectionofthereflectedlight.
SeeAlso:HowtousetheTemplateCreator
LinePatternsPropertyPage-TemplateCreator
Thelinepatternspropertypageisonlyavailableforlegendelements.
Todisplaythispropertypageeitherdouble-clickonalegendelementorright-clickoveralegendelementandselect'Properties'.
Thefollowingisadescriptionofwhatyoucandoviathispropertypage:
DefaultPatterns
Youmayselectoneofseveralpre-definedlinepatternsforthelegend'soutline.
Pattern Usetheradiobuttonstodefineyourowncustomlegendoutline.
LineParameters:
LineWidth Setsthewidthofthelegend'soutline.
Color Setsthecolorofthelegend'soutline.
Factor Magnifiesthespecifiedlinepattern.Forexample,iftheoutlineconsistsofdot-space-dotandyoumagnifybyafctoroftwothentheresultingoutlinewillthenbe:dot-dot-space-space-dot-dot.
SeeAlso:HowtousetheTemplateCreator
PieElementPropertyPage-TemplateCreator
Thepieelementpropertypageisonlyavailablewhenyouclickoverapieslice.
ThepropertiesexposedbythispageapplytoALLpieelementsexceptfortheExplodedoption(onlyappliedtotheslicewhichwasclickedover).
Todisplaythispropertypageeitherdouble-clickonapiesliceorright-clickoverapiesliceandselect'Properties'.
Thefollowingisadescriptionofwhatyoucandoviathispage:
PieParameters:
NumberofPoints
Thenumberofpointsusedtodrawthecircumferenceofthepiechart.
VerticalRadius Theradiusofthepieedge.Imaginethepiechartwhenitisrotatedtothepointwhereyoucanonlyseeitsedge.Theroundingofthepieatbothendsisdeterminedbythisvalue.
VerticalNumberofPoints
Thenumberofpointstobeusedtodefinethecircumferenceofthepiechart'sedge(e.g.thickness).ThispropertydeterminesthenumberofpointsusedtodrawthatpartofthepiewhoseradiusisdeterminedbytheVerticalRadius.
Exploded Explodes/collapsestherelevantpieslice.
CollectedData: Thereisonlyonecollectedpieelement.YoumaysetthecollectedpropertieslistedbelowbyclickingoverANYpieelement.Tosetothercollectedproperties(e.g.texture)clickoverthecollectedpieelementitself.
Absolute Thevalueusedtodetermineifasliceiscollectedwillbeanabsolutevalue.
Percentage Thevalueusedtodetermineifasliceiscollectedwillbeapercentageoftheentirepiechart.
Limit Thevalue(eitherabsoluteorapercentage)atwhichapieslicewillbecollected.
SeeAlso:HowtousetheTemplateCreator|TemplateCreatorOverview
PopupMenu-TemplateCreator
Thepopupmenuletsyouperformthefollowingactions:
Properties Displaysthepropertysheetappropriatefortheelementwhichyouright-clickedover.
GetAnotherElement
Youcanselectanareaelement(background),legendelementortitleelement.Anotherpopupmenuwillappear,allowingyoutoedittheelement.
AddNotes Letsyouinsertastaticnoteselement(agenerictextelement)whenyouclickoverthebackground.
SwitchtoSize/SwitchtoMove
Togglesbetweensizingmodeandmovingmode.
Delete Deletethestaticnoteselementwhichyouclickedover.Onlyforstaticnotes.
Todisplaythepopupmenuright-clickoveranypiechartelement.
NOTE:theitemsdisplayedbythepopupmenuaredependentonwhereyouright-clickinthepiechart,sonotalloftheprecedingitemsmaybedisplayed.
SeeAlso:ApplicationMenu-TemplateCreator
RotatingaChart-TemplateCreator
TorotateachartobjectintheTemplateCreatorusethekeyboard'snavigationalkeys.Refertothefollowingtableforadetaileddescriptiononhowthedifferentkeysrotateapiechart:
Key Description
UpArrow Rotatesthetopofthechartawayfromtheuser.
DownArrow Rotatesthetopofthecharttowardstheuser.
LeftArrow Rotatesthechartclockwisearounditsverticalaxis.
RightArrow Rotatesthechartcounter-clockwisearounditsverticalaxis.
Home Rotatesthechartcounter-clockwisearounditshorizontalaxis.
End Rotatesthechartclockwisearounditshorizontalaxis.
PageUp SameastheEndkey.
PageDown SameastheHomekey.
SeeAlso:HowtousetheTemplateCreator
ScenePropertyPage-TemplateCreator
Thescenepropertypageisonlyavailablewhenyouright-clickoverapieslice.
Todisplaythispropertypageeitherdouble-clickonapiesliceorright-clickoverapiesliceandselect'Properties'.
Thefollowingisadescriptionofwhatyoucandoviathispropertypage:
Rotation Torotatethepiechartobjectuseeitherthereddirectionalarrowsorleft-clickontheobjectandrotateitwhileholdingtheleftmousebuttondown.
RotationStep Determinestheincrementbywhichthescenewillberotated.
Reset Resetsthepiecharttoitsdefaultposition.
SeeAlso:HowtousetheTemplateCreator|TemplateCreatorOverview
Size-MovePropertyPage-TemplateCreator
Thesize-movepropertypageisavailableforeverypiechartelementexceptthebackground(whichisanareaelement).
Todisplaythispropertypageeitherdouble-clickonanelementorright-clickoveranelementandselect'Properties'.
Everyelementhasanassociatedboundingrectangle(youcanseethisifyouclickontheelementinquestion).Whenyouviewthesize-movepagenoticethattherearetwosetsofarrows:aninnersetandanoutersetseparatedbytheoutlineofasquare.Thissquarerepresentstheboundingrectangleoftheelementthatisbeingsized/moved.Arrowsinsideandoutsideofthesameedgeforthesquareoutlinewillmovetheassociatedboundingrectanglesideinthedirectionindicatedbythearrow.
Thedifferencebetweenmovingandresizingisthis:ifsizingmodeisonthenchangingonesideoftheboundingrectangleWILLNOTresultinanyoftheothersidesoftheboundingrectanglebeingmovedaswell.IfmovingmodeisselectedthenadjustingoneboundingedgeWILLresultintherestoftheboundingedgesbeingmovedaswell,sincewearemovingthepiechartelementandnotresizingit.
Tosize/moveanobjectclickontheobjectwiththeleftmousebuttonandsize/moveitbydraggingthemouse.
Thefollowingisadescriptionofwhatyoucandoviathispropertypage:
Object:
Element Selectsoneelementtomove/resize.
Group Usedtomove/sizeagroupofpiechartelements.ThisisactuallyusedwithotherDundasChartcharttypesandisnotapplicableforthissample.
Chart Move/resizethechartobject.
Operation:
Size Sizetheselectedpiechartobject.
Move Movetheselectedobject.
Steps:
Horizontalstep Setsthehorizontalincrementbywhichthepiechartorpiechartobjectwillbemoved/resized.
Verticalstep Setstheverticalincrementbywhichthepiechartorpiechartobjectwillbemoved/resized.
SeeAlso:HowtousetheTemplateCreator
TexturePropertyPage-TemplateCreator
Thetexturepropertypageisavailableforpieslices,legends,andthebackground.Itletsyouspecifytexturesandcolorsandalsoletsyouimporttextures(jpegorbitmapformats).
Notethattheelementsforthispropertypagemaydiffer,dependingonthechartelementtheTexturespageappliesto.
Todisplaythispropertypageeitherdouble-clickonanappropriateelementorright-clickovertheelementandselect'Properties'.
Thefollowingisadescriptionofwhatyoucandoviathispropertypage:
Type
NoTexture Notexturewillbeused.
Texture Usethetextureselectedfromthetexturewindow(thewindowtotheimmediaterightoftheTexturebutton).Whenthisoptionisselectedyoucannotspecifyacolor.
ColoredTexture
Enabledforpieslices.Thisletsyouspecifyatextureandacolor.
Tile Enabledforlegendsandthebackground.Ifthisischeckedthentheselectedtexturewillbetiled.Ifitisnotselectedthetexturewillbeenlargedtofilltherelevantwindowarea.
SideTexture Onlyavailableforpieslices.Setsthetexturetobeusedforthesidesofapieslice.Thisisusefulforexplodedpiesegments.
Group UsedforotherDundasChartcharttypes.Notapplicabletothepiechart.
BacktoSeries UsedforotherDundasChartcharttypes.Notapplicabletothepiechart.
TexturesDisabled Disablestheuseoftextures.Notethattheelementsstillownthetextures.
Color Selectacolorfortheelement.YoucanspecifyacolorANDatextureforapieelement.
ImportTexture Importatexturetobeusedfortheelement.Thetextureshouldbeajpegorbitmap,andthemaximumsizeoftheimageis1024X1024pixels.Thewidthandheightoftheimagemustalsobetothebase2(e.g.2^m=Widthand2^n=Heightinpixels).
Texturesorcolorsforalegendelementwillbeappliedtothebackgroundoftheentirelegend.
IMPORTANT:Themaximumsizeofanimportedtexture(jpegorbitmap)is1024X1024pixels.Also,thewidthandheightoftheimagemustbeto
thebase2(e.g.2^m=Widthand2^n=Heightinpixels,wherenandmarewholenumbers).
SeeAlso:HowtousetheTemplateCreator
TitlePropertyPage-TemplateCreator
Thetitlepropertypageisavailablefortitleelementsonly.
Todisplaythispropertypageeitherdouble-clickonatitleelementorright-clickovertheelementandselect'Properties'.
Thefollowingisadescriptionofwhatyoucandoviathispage:
EditTitle Determinesthetextofthetitleelement.
Orientation
Horizontal Thehorizontalorientationcanbechangedforstaticnoteselements.
Vertical Theverticalorientationcanbechangedforstaticnoteselements.
Effects
AutoSize Automaticallysizesthetitleinitsboundingrectangle.
VerticalCenter Centersthetitleverticallywithinitsboundingrectangle.OnlyavailableifAutoSizeisnotselected.
HorizontalCenter Centersthetitlehorizontallywithinitsbounding
rectangle.OnlyavailableifAutoSizeisnotselected.
Color Setsthecolorofthetitletext.
Font Setsthefonttobeusedforthetitle.
FontStyle Setsthefontstyletobeusedforthetitle.
Size Thesizeofthefonttobeused.
SeeAlso:HowtousetheTemplateCreator
DundasPieChartOverview
Copyright©DundasSoftwareLtd.2000.AllRightsReserved
ThisfreeASPcomponentconsistsoftwoparts-theTemplateCreatorandtheDundasPieChartServercontrol(implementedviaASPpages).
Atemplateisabinaryfilethatstoresreusablechartinformation,andtheTemplateCreatorletsyoucreatenewtemplatesandalsomodifyexistingones.TheDundasPieChartServercontrolloadsatemplate,addsdataandthencreatesapiechartimageinajpegformat.Thisimagecanthenbesavedtofileortransferreddirectlytoawebpage.
NotethattheDundasPieChartServercontrolandtheTemplateCreatorbothuseOpenGLlibraries(OpenGL32.dllandglu32.dll).TheselibrariesareinstalledbydefaultwithWindows98andWindowsNT.Inadditiontheyalsodependonthepresenceoftheijl15.dllIntelCompressionlibrary,whichMUSTexistatthesamedirectorylevelasboththeservercontrolandtheTemplateCreator(unlessitisinyoursystemdirectory).
SeeAlso:PieChartControlOverview|TemplateCreatorOverview
Tutorial:CreatingaBasicPieChart
Tousethiscontrolinawebsiteyouwillneedtousetwo(2)webpages.OneASPpage(let'scallitthesecondarypage)createsaninstanceoftheASPPieChartcontrol,loadsatemplate,addsthespecifieddataandthencallsSendJPEGtosendthedatatotheclient.Theotherpage(letscallitthemainpage)retrievesthepiechartimagebyembeddingthesecondaryASPpageinan<IMG>tagor<A>tagwiththeSRCattributesettothesecondarypage.ThemainpagecanbeeitheranhtmlorASPfile.
IfyoudonotknowhowtocreateatemplateusingtheTemplateCreatorthenclickhereforinstructionsonhowtodoso.ThistutorialDOESNOTcoverhowtomakeyourpiecharttemplates,itassumesyoualreadyhaveatemplatereadytobeloaded.
IMPORTANT:theIntelcompressionlibrary(ijl15.dll)MUSTbelocatedineitheryoursystemdirectoryoratthesamedirectorylevelasboththechartservercontrolandtheTemplateCreator,otherwiseboththecontrolandtheCreatorwillnotfunctioncorrectly.
ClickhereforinstructionsonhowtodebugthePieChartServer.Forfurtherinformationconcerningdebugging,aswellasFAQs,andtroubleshootinggotoourdevelopersite.
Tooutputapiechartjpegperformthefollowingactionsintheirspecifiedorder:
1. Createthemainpage(ASPorhtml)andembedthesecondarypage(ASP)intoitwitheitheran<IMG>tagor<A>tag.
2. Createthesecondarypage(ASP)andperformthefollowingactionsintheirindicatedorder:
ThePieChartServerwillthrowanexceptionifanerroroccurs,soenableerrorhandlingwithan"OnErrorResumeNext"statement.
CreateanASPPieChartobjectbyusingCreateObject(e.g.CreateObject("Dundas.PieChartServer.1")).
Setthedirectorypropertiesofthecontrolwhichspecifyworkingdirectoriesfordifferentaspectsofchartactivity.ThesepropertiesareDirTemplateandDirTexture,anddealwiththedirectoriesusedtostoretemplatesandtextures,respectively.
LoadatemplateviatheLoadTemplatemethod.
Setthepropertiesofthepiechart(e.g.explodedpieces,collectedelementproperties,etc.)
AddpiechartdatawiththeAddDatamethod.
SendtheresultingjpegdirectlytoaclientwiththeSendJPEGmethodoralternativelyyoucansavethejpegtodiskwithCreateJPEGFileandthenpresenttheimagetoauserwithastandard<IMG>tag.
IfyouwanttogenerateanotherJpegusingthesametemplatethenrepeatSteps4to6.Ifyouwanttocreateanotherjpegwithadifferenttemplaterepeatsteps1to6.
DestroythePieChartobjectbysettingittoNothing(e.g.SetobjPieChart=Nothing).
MAKESUREthatthereisnohtmlcodeinthisASPpagewhichoutputsthejpeg.
TheProgIDofthecontrolis:Dundas.PieChartServer.2
Example
'Displaysapiechartinanhtmlpage
'letsmakethemainpage,andcallitMain.htm<Html><Body><IMGSRC="MakeJpeg.asp"></Body></Html>
'nowmakethesecondarypagewhichoutputsthejpeg'let'scallitMakeJpeg.asp<%'makesurebrowserneverusescachedcopyofjpegResponse.Buffer=TrueResponse.CacheControl="Private"Response.Expires=-100
'enableerrorhandling,sinceanexceptionwillbethrownifanerroroccurs.Todebugthispage'disabletheResumeNextstatementandloadthispagedirectlyintoyourbrowser,andobserve'theraisedexception.OnErrorResumeNext
'retrievethephysicaldirectorywhereASPpagesarelocatedstrPath=Server.MapPath(".")
'createaninstanceofthecontrolSetobjPieChart=Server.CreateObject("Dundas.PieChartServer.1")
'settheTemplatedirectoryofthecontrolobjPieChart.DirTemplate=strPath&"\Templates\"
'settheTexturesdirectoryofthecontrolobjPieChart.DirTexture=strPath&"\Textures\"
'loadanytemplate(madewiththeTemplateEditor)ret=objPieChart.LoadTemplate("Textures.cuc")'checkforanerror.Ifthemethodcallisnotsuccessfulthenthe'returnederrorcodewillnotbezero(0)andinadditionanexceptionwillbethrown.'Seethe"Debugging"sectionatthebottomofthispageforinformationonhowtodebugyourpiecharts.Ifret<>0ThenResponse.WriteobjPieChart.GetErrorText(ret)EndIf
'add3slicestothepiechartandspecifyvalues(sizes),slicelabelsandlegendlabels
ret=objPieChart.AddData(25,"Label1","Slice1")ret=objPieChart.AddData(25,"Label2","Slice2")ret=objPieChart.AddData(25,"Label3","Slice3")'checkforanerror.Ifmethodnotsuccessfulthenoutputthe'correspondingerrorstring.Seethe"Debugging"sectionbelowfor'moredetailsconcerningdebuggingthepiechartserverIfret<>0ThenResponse.WriteobjPieChart.GetErrorText(ret)EndIf
'outputgraphics,specifyingthewidthandheightoftheimageinpixelsret=objPieChart.SendJPEG(450,350)Ifret<>0ThenResponse.WriteobjPieChart.GetErrorText(ret)EndIf
'destroyAspPieChartobjectSetobjPieChart=Nothing%>
NoticethatthereisNOHTMLCODEinthispagewhichoutputsthejpeg!
DebuggingthePieChartServer
Ifanerroroccursthenanexceptionwillberaisedandthereturnederrorcodewillnotbezero(0).SinceanexceptionwillberaisedMAKESUREthatthepagewhichoutputsthejpeghasan"OnErrorResumeNext"statement.
TodebugthePieChartServercontrolyoushouldloadthepagewhichcontainsthe"SendJPEG"calldirectlyintoyourbrowser,andyoucanthenuseeitherthecontrol'sGetErrorTextmethod(explainedindetailbelow)oryoucanmerelyexaminetheexceptionthrownbythecontrol(makesurethe"OnErrorResumeNext"
statementisdisabled).
IfanerroroccursandapiechartimageisnotproducedyoucanalsoretrievearelevanterrorstringbyloadingthepagewhichproducestheJPEGdirectlyintoyourbrowserandobservingtheerrorstringgeneratedbythecontrol'sGetErrorTextmethod.Forexample,intheprecedingsamplecodeyoucouldloadtheMakeJpeg.asppagedirectlyintoyourbrowserandthenseewhatGetErrorTextreturns.
NotethatthismethodofretrievingrelevanterrorstringswillonlyworkifthepagethatproducestheJPEGimagecontainsNOhtmlcode(e.g.thepageonlycontainsserver-sideASPcode).
SeeAlso:Tutorial:DrilldownandSelectionofDataElements|Tutorial:Rotation
Tutorial:DrilldownandSelectionofDataElements
Drilldownandtheselectionofchartitemsisaccomplishedbyusingachartimageasahyperlinkedserver-sideimagemap.Touseachartimageasaserver-sideimagemapspecifytheIsMapattributeinsidetherelevant<IMG>tag.
UsethefollowingsyntaxintheASPpagewhichdisplaysachartbeingusedastheimagemap:<AHREF="TheAspPageToHandletheSelectedItem.asp"><IMGSRC="MakeTheJpeg.aspIsMap></A>.NotethatthespecifiedAsppageinthe<A>tagisthepagewhichmustdeterminewhichseries/dataelementtheuserselected.
Todeterminewhatdataseries/dataelementtheuserselected(clickedon)calltheSelectmethodandthenexaminethereturnsfromtheGetSelectedSeriesandGetSelectedPositionmethods.
Onceyouhavedeterminedwhattheuserselectedyoucanperformtheappropriateaction,givingyou"drilldown"capabilities.
Notethatclickingonaserver-sideimagemapwillallowthepagehandlingtheselecteditemtoretrievethemousecoordinatesoftheclicked-onpositionsincethemousecoordinatesareavailableviatheresultingquerystring.UseVBSCript'sInStrmethodtoparsethequerystringandretrievethemouseX,Y-coordinates.ThenusetheseXandYvalueswhencallingtheSelectmethod.
IMPORTANT:theEXACTsamechartmustbereproducedinthepagewhichhandlestheselectionascomparedtotheChartgeneratedbythepagespecifiedwithinthe<IMG>tag.Thereforeitishighlyrecommendedthatyouuseaserver-sideincludeforthesourcecodewhichactuallyproducesthechartimage(startingfromtheCreateObjectcallallthewaytosettingtheChartobjecttoNothing).Thiswillensurethatthechartproducedinthepagewhichhandlestheselection(usingtheSelect,GetSelectedPosition,andGetSelectedSeriesmethods)will
beexactlythesameasthechartproducedbythepagewhichoutputsthechartjpeg(usingtheSendJPEGmethod).
Refertothesamplesourcecodebelowforfurtherclarification.
IfyoudonotknowhowtocreateatemplateusingtheTemplateCreatorthenclickhereforinstructionsonhowtodoso.ThistutorialDOESNOTcoverhowtomakeyourpiecharttemplates,itassumesyoualreadyhaveatemplatereadytobeloaded.
Example
Scenario-Wewilluseapiechartasanimagemap(with4pieslices)inthemainpage(Main.asp).-Whentheuserselectsanelementwewillexplodetheselectedelement.-NotethatweareusingSession-levelvariables.-AsecondarypagenamedMakeJpeg.aspwillcreateandoutputtheresultingjpegtothemainpage.-Toseeifafunctioncallwassuccessfulyoucanexaminethereturnederrorcode(zeroequalssuccess).TogetarelevanterrorstringusetheGetErrorTextmethod.
Main.asp<%@Language=VBScript%><%Response.Buffer=True%><HTML><HEAD></HEAD><BODY><%DimQString'thequerystringresultingfromtheuserclicking'ontheChartserver-sideimagemapDimPosition'thedataelementtheuserselectedDimXPosition'themouseX-coordinatewheretheuserclickedDimYPosition'themouseY-coordinatewherretheuserclickedDimret'returnederrorcodefromfunctioncall
DimobjChart'DundasChartServerobjectDimstrErrorCode'stringerrormessage
'retrievethequerystringwiththemousecoordinatesQString=Request.QueryString()
'initializetheselectedpositionto-1sothattheSetExplodedcalldoesnot'initiallyexplodeadataelement.Session("Position")=-1
'thefollowingcodeonlyexecutesiftheuserclickedonapiesliceIfQString<>""ThenPosition=InStr(1,QString,",",1)XPosition=CInt(Mid(QString,1,Position-1))YPosition=CInt(Mid(QString,Position+1))
'createinstanceoftheChartcontrolSetobjChart=CreateObject("Dundas.ChartServer")
'NOTE:EventhoughthispagedoesnotoutputajpegweMUST'reproducetheexactsamechartwhichisproducedbythepagewithin'the<IMG>tag.Inordertoguarenteethattheexactsamechartis'reproducedwehighlyrecommendusingaserver-sideincludeforthe'codewhichcreatesthechart(startingfromtheCreateObject'callallthewaytosettingtheChartobjecttoNothing).
'nowsetthecontrol'sdirectorypropertiesobjChart.DirTexture="c:\dschart\dschart_local\Textures\"objChart.DirTemplate="c:\dschart\dschart_local\Templates\"
'loadapiecharttemplatemadewiththeTemplateCreator'notethatareturnvalueofzeroindicatessuccessret=objChart.LoadTemplate("selection.cuc")
'nowaddsomedatatothepiechart
ret=objChart.AddData(3.2)ret=objChart.AddData(2.8)ret=objChart.AddData(9.1)ret=objChart.AddData(4.5)
'nowcalltheSelectmethodsowecandeterminetheselectedelement'notethatthewidthandheightspecifiedintheSelectmethodcall'shouldbethesameasthatspecifedinthe<IMG>tagfound'atthebottomofthispage.ret=objChart.Select(XPosition,YPosition,300,300)'letscheckreturnvalue(usefulfordebugging)Ifret<>0ThenstrErrorCode=objChart.GetErrorText(ret)EndIf
'NOTE:ifyouareusingachartotherthanasphereorpiechart'fortheimagemapyouwouldthenneedtocallGetSelectedSeries'aswellascallingGetSelectedPosition.Ifyouareusingasphereorpie'chartandareusingthe"collected"dataelementyouwillstillneed'tocallGetSelectedSeriesinordertodetermineiftheuserclickedon'thecollecteddataslice(returnvaluewillbe-999).Position=objChart.GetSelectedPosition()'thissession-levelvariableletstheMakeJpeg.asppageknowwhatwasselectedSession("Position")=Position
'releaseresourcesSetobjChart=Nothing
EndIf%><!--MaketheDundasChartserver-sideimagemap--><center><ahref="Main.asp"><center><IMGheight=300width=300src="MakeJpeg.asp"ID=PictureISMAP></a></center></BODY>
</HTML>
MakeJpeg.asp<%@Language=VBScript%><%OptionExplicit%><%'disablecachingsothatimageisalwaysretrievedfromserverResponse.Buffer=TrueResponse.CacheControl="Private"Response.Expires=-1000
DimPosition'itemselectedbytheuserDimret'returnederrorcodefromfunctioncallsDimobjChart'DundasChartServerinstanceDimstrError'errorstring
'retrievetheselectedelementasdeterminedbythemainpagePosition=Session("Position")
'createaninstanceofthecontrolSetobjChart=CreateObject("Dundas.ChartServer")
'setupthecontrol'sdirectorypropertiesobjChart.DirTexture="c:\dschart\dschart_local\Textures\"objChart.DirTemplate="c:\dschart\dschart_local\Templates\"
'loadthepiecharttemplate,createdintheTemplateCreatorret=objChart.LoadTemplate("selection.cuc")
'nowadddatatothepiechartret=objChart.AddData(3.2)ret=objChart.AddData(2.8)ret=objChart.AddData(9.1)ret=objChart.AddData(4.5)
'nowwewillexplodethedataelementselectedbytheuserobjChart.SetExploded(Position)
'nowoutputthechartjpeg.Notethatyoucanstepthroughyourcode'andcheckthestrErrorvariableifSendJPEGwasunsuccessfulret=objChart.SendJpeg(300,300)Ifret<>0ThenstrError=objChart.GetErrorText(ret)EndIf
'releaseresourcesSetobjChart=Nothing%>
SeeAlso:Tutorial:CreatingaBasicPieChart|Tutorial:Rotation
Tutorial:RotationExample
Inordertorotateachartyoumustletthechartinstanceknowwhattherotationalangleswereafterthelastrotationoperation(defaultsareusedwhenthefirstrotationoccurs)beforecallingtheRotatemethod.Thismeansthatyoumustpreservestateinformation(session-levelvariables,hiddeninputboxes,etc.)betweenChartobjectcreation/deletion.
TosettheinitialrotationanglesuseyourpreservedstateinformationandsettheAngleX,AngleYandAngleZproperties.OnceyouhavesetthepreviousrotationanglesyoucanthencalltheRotatemethodtorotatethechart.BeforethechartobjectisdestroyedMAKESUREthatyoustorethenewrotationangles(tobeusedforthenextrotationoperation).thiscanbedoneusingsessionvariables,hiddeninputboxes,etc.
Refertothesamplesourcecodebelowforfurtherclarification.
Example
IfyoudonotknowhowtocreateatemplateusingtheTemplateCreatorthenclickhereforinstructionsonhowtodoso.ThistutorialDOESNOTcoverhowtomakeyourpiecharttemplates,itassumesyoualreadyhaveatemplatereadytobeloaded.
Scenario-Wewillallowtheusertorotateapiechartclockwise.-Theamountofrotationwillbehard-codedto20degrees.-Stateinformationconcerningthelastdisplayedpositionofthechartwillbepreservedbyusingsession-levelvariables.-Main.aspwilldisplaythechart,whileMakeJpeg.aspwillactuallycreatethechartjpeg.
Main.asp<Html><Head></Head>
<Body><Center><IMGheight="300"src="MakeJpeg.asp"width="300"></Center><formaction="Main.asp"method="post"id="form1"name="form1"><inputtype="submit"name="cmdRotate"id="cmdRotate"value="Rotate"></form></Body></Html>
MakeJpeg.asp<%'disablecachingsothatimageisalwaysretrievedfromserverResponse.Buffer=TrueResponse.CacheControl="Private"Response.Expires=-1000
'createaninstanceofthecontrolSetobjChart=Server.CreateObject("Dundas.ChartServer")
'setrequireddirectorypropertiesobjChart.DirTexture="c:\dschart\dschart_local\Textures"objChart.DirTemplate="c:\dschart\dschart_local\Templates"
'loadapiecharttemplate,madewiththeTemplateCreatorret=objChart.LoadTemplate("Rotation.cuc")
'nowaddsomedatatothepiechartret=objChart.AddData(900)ret=objChart.AddData(1900)ret=objChart.AddData(200)ret=objChart.AddData(400)
'ifonerotationoperationhasalreadyoccurredthenweneedto'letthechartknowitspreviouslocationIfSession("AngleX")<>""ThenobjChart.AngleX=Session("AngleX")IfSession("AngleY")<>""ThenobjChart.AngleY=Session("AngleY")
IfSession("AngleZ")<>""ThenobjChart.AngleZ=Session("AngleZ")
'nowrotatethechart20degreesclockwise(aroundthewindow'sz-axis)ret=objChart.Rotate(-20,2)
'nowsetsession-levelvariablessowecansetthechartobject's'previouslocationthenexttimewerotatethechartSession("AngleX")=objChart.AngleXSession("AngleY")=objChart.AngleYSession("AngleZ")=objChart.AngleZ
'nowoutputthepiechartjpegret=objChart.SendJpeg(300,300)'letscheckthereturnvalue(usefulfordebugging)Ifret<>0ThenstrErrorCode=objChart.GetErrorText(ret)EndIf
'releaseresourcesSetobjChart=Nothing%>
SeeAlso:Tutorial:CreatingaBasicPieChart|Tutorial:DrilldownandSelectionofDataElements
DistributedSamples
ThedistributedASPsamplesareimplementedwithtwo(2)ASPpageseach.Thefirstpage(PieChart1.aspandPieChart2.aspforsamples1and2,respectively)setsuptheuserinterfaceanddisplaysthechart,whilethesecondpage(MakeJPEG1.aspandMakeJPEG2.aspforsamples1and2,respectively)loadstheselectedtemplate,addsthespecifieddatatothepiechartandthenoutputstheimageasajpeg.Thesecondpageisembeddedintothefirstusingan<IMG>tag(youcanalsousean<A>tag).
ToruntheASPdemosyoumustbesetuptohostwebpageswitheitherMicrosoftInternetInformationServer(IIS)orMicrosoftPersonalWebServer.
ThefirstdemousesfourtemplateswhicharedisplayedtoauserviaalistboxinthemainASPpage.NotethatyoucanmodifythesetemplatesbyusingtheTemplateCreatoranytimeyouwish.ThesecondASPdemorandomlyselectsoneoffivetemplatesandalsoexplodespieslicesatrandom.
Tosuccessfullyrunthesedemosmakesurethatthe"Templates"and"Textures"foldersexistatthesamelevelastheASPpagesthatmakeupthesamples.TheTemplateCreatorshouldalsobelocatedhere.
DundasUploadControl2.0
Copyright©DundasSoftwareLtd.2000,AllRightsReserved.
Overview|Properties|Methods
TheDundasUploadControl2.0isafree,fullytestedcommercialMTScomponentwhichallowsyoutoaccept,saveandmanipulatefilesuploadedviaawebbrowserwhichiscompliantwithRFC1867(e.g.Netscape3.0+andMicrosoft'sIE4.0+).ItisdesignedtobeusedinActiveServerPages(ASP)whicharehostedwithMicrosoft'sIIS(WindowsNTorWindows2000).
TheUploadcontrolalsoshipswiththeUploadProgresscomponentandtheDundasStateServer.TheUploadProgresscomponentworksinconjunctionwiththeStateServerandUploadcontrolandenableswebdeveloperstoquicklyandpainlesslyutilizeprogressbarstodisplaytheprogressofanuploadoperation.TheStateServercomponentcanrunanywhereonyournetwork,soitis"web-farm"ready,andmaybeusedtostoreanystateinformation.
YoucanalsousetheUploadcontrolalongwithourfreeDundasMailerControlinordertogiveyourapplicationsweb-basedemailcapabilitieswhichcanhandlemultiple-fileuploadoperations.TheMailercontrol,liketheUploadcontrol,isalsoafullydevelopedandtestedcommercialproductwhichisfree.
FeaturesListInstallation/RedistributionHowtousetheDocumentation
FeaturesList
ThefollowingarejustsomeofthefeaturesoftheDundasUploadControl2.0:
Itshipsweb-farmready.
MTSsupport(objectpooling).
ADOsupportviasafe-array-of-bytesvariants,allowingyoutopersistuploadedfilesasBLOBs.
Handlesuploadingofmultiplefiles.
Uploadformdataeitherallatonceorincrementally.Incrementalretrievalofdataallowsthedevelopertoaccesssomeoftheformdatapriortotheuploadaswellasskipfilestobeuploaded.
Letsyouspecifyamaximumallowablelimitforuploadeddata,amaximumnumberoffilestobeuploadedaswellasamaximumallowablefilesize.
ImplementaprogressbarviatheProgressBarandStateServercomponents.
Saveuploadedfileseithertodiskortomemory.
Capableofperformingnumerousfileanddirectoryoperations.
ImpersonateuseraccountsotherthantheIUSR(ordefault)account,therebyallowingyoutoperformoperationsforwhichthedefaultaccountdoesnothavepermissions.
COMregistration.
MacBinarysupport(forMacintoshclientmachines).
UploadedfilesACL,ownerandattributemanipulation.
InstallationandRedistribution
ApreviousversionoftheUploadcontrol(version1.0)wasshippedwiththefreeDundasMailercontrol.Thisfirstcontrolalloweduserstouploadmultiplefilesandalsosupportedotherbasicuploadoperations.ItisrecommendedthatyouuninstallthispreviousversionifyouinstalledtheDundasMailercontrol.
ControlsandSamplesInstall
Thenameoftheinstallfileis:"AspUpload.exe".
Thewindowsaccountunderwhichtheinstallrunsneedstohaveadministrativepriviledgesforasuccessfulinstallation.
TheDundasStateServer(StateServer.exe)wheninstalledissetuptorunasanormalexecutable.ThishastheadvantageofgivingyouaGUIwhichdisplaystheoperationswhichhaveoccurredorareoccurring.Pleasenote,however,thatyoucanruntheStateServerasaservice.Runningtheexecutableasaservicecanincreaseitsperformanceuptofivetimes(fivehundredpercent).
Startmenuentriesareasfollows:
DundasSoftware|FreeProducts|AspUploadControl|ReadMe
DocumentationInstall
Touninstallthisdocumentationruntheinstallfileagain(FPDocInst.exe)andchooseeither"RemoveFromMSDN"ifyouintegratedintotheMSDNor"RemoveAll"ifyoudidnotintegrateintotheMSDN.
HowtousetheDocumentation
DocumentationfortheUploadcontrolconsistsofthefollowing:
1. Compiledhtmlhelp(optionallyintegratedintotheMSDN).Thehtmlhelpprovidesdetailedexplanationsforallmembersofthecontrolaswellasacontroloverviewandtutorials.Topicswhichshouldbeespeciallyusefulare:
HowtoUsetheDundasUploadControl
Overview(DundasUploadControl2.0)
QuickStart(DundasUploadControl2.0)
Tutorial1:UploadingMultipleFilesandUsingtheFormandFilesCollections
Tutorial2:RetrievingFormDataIncrementallyUsingtheGetNextFileMethod
Tutorial3:ADOSupportandSavingaFileasaBLOB
Tutorial4:ImplementingaProgressBar
2. ReadMe.htm.ThisfileisdistributedwiththeUploadcontrol,andconsistsofinstallationinformation,releasenotesandatroubleshootingsectionforyourconvenience.
Overview(DundasUploadControl2.0)
Copyright©DundasSoftwareLtd.2000,AllRightsReserved.
Overview|Properties|Methods
TheDundasUploadControlisanMTScomponentwhichallowsyoutoaccept,saveandmanipulatefilesuploadedviaawebbrowser.ItisusedinActiveServerPages(ASP)whicharehostedwitheitherMicrosoft'sIIS(WindowsNTorWindows2000)orMicrosoft'sPWS(Windows9X).
DundasUploadControl2.0Features:
Webfarmready.
MTSsupport(objectpooling).
ADOsupportviasafe-array-of-bytesvariants.AllowsyoutopersistuploadedfilesasBLOBs.
Handlesuploadingofmultiplefilesandformdata.
Uploadformdataeitherallatonceorincrementally.Incrementalretrievalofdataallowsthedevelopertoaccesssomeoftheformdatapriortotheuploadaswellasskipfilestobeuploaded.
Letsyouspecifyamaximumallowablelimitforuploadeddata,amaximumnumberoffilestobeuploadedaswellasamaximumallowablefilesize.
ImplementaprogressbarviatheProgressBarcomponentandtheDundasStateServer.
Saveuploadedfileseithertodiskortomemory.
Performsnumerousfileanddirectoryoperations.
ImpersonateuseraccountsotherthantheIUSR(ordefault)account,
therebyallowingyoutoperformoperationsforwhichthedefaultaccountdoesnothavepermissions.
COMregistration.
MacBinarysupport(forMacintoshclientmachines).
UploadedfilesACL,ownerandattributemanipulation.
Disableorsetthedefaultvaluesofcertainfeaturesviatheregistry.
Handlesfiledownloading.
Optionallysaveuploadedfileswithuniquefilenames.
TocreateaninstanceoftheUploadcontrolusetheCreateObjectmethodwithaProgIDofeither"Dundas.Upload"or"Dundas.Upload.2".
Toutilizenamedconstantsinyourcodeuseaserver-sideincludefortheDSUpload.incfile,whichdefinestheconstantsforyou.
Mostmethodsofthecontrolwillthrowanexceptionifanerroroccurs.Trapforthesuccess/failureofthevariousoperationsbyusinganOnErrorResumeNextstatementandthenexaminetheErrobjectafteramethodcall.
Youshouldfindthefollowingtopicsespeciallyuseful:
HowtoUsetheDundasUploadControl
Tutorial1:UploadingMultipleFilesandUsingtheFormandFilesCollections
Tutorial2:RetrievingFormDataIncrementallyUsingtheGetNextFileMethod
Tutorial3:ADOSupportandSavingaFileasaBLOB
Tutorial4:ImplementingaProgressBar
SeeAlso:ProgressBarComponentOverview|StateServerComponentOverview
HowtoUsetheDundasUploadControl
Overview|Properties|Methods
TousetheDundasUploadcontroltheclientmustbeusingabrowserwhichiscapableofhtmlform-baseduploading(asperRFC1867).Netscape3.0+andMicrosoft'sInternetExplorer4.0+bothsupportthis.
ThePOSThtmlformMUSTusean"EncType"of:"Multipart/Form-Data"(i.e.<formmethod="POST"name="SomeName"EncType="Multipart/Form-Data">.
ClickhereforlistofstepstobefollowedwhenimplementingtheUploadcontrol.
FilestobeuploadedaredeterminedthroughtheuseoffileinputboxesinthePOSTform.
TheFormandFilescollectionsofthecontrolareespeciallyimportant.TheFormcollectionisusedtoaccessformdatasuchasinputelements,selectelements,etc....Thiscollectionalsoallowsyoutoretrievethevaluesofmultiple-entryformitems(e.g.multi-selectlistbox).TheFilescollection(consistingofUploadedFileobjects)isusedtoaccessandmanipulateuploadedfiles.
TodeterminethefileinputboxwhichcorrespondstoaparticularuploadedfileusetheTagNamepropertyoftheUploadedFileobject(theTagNamepropertyisthesameastheNameattributeofthecorrespondingfileinputbox).YoucaniteratethroughalluploadedfileswitheitherastandardForlooporaForEachloop.TodeterminethefiletypethatwasuploadeduseVBScript'sInStrmethodwiththeContentTypepropertyofanUploadedFileobject.NotethattheNextFileobjectalsoexposestheContentTypeandTagNameproperties.RememberthatcallingtheSaveorSaveToMemorymethodsoftheNextFileobjectwillalsoupdatetheFilescollection.
Toretrievethevaluesofformelementsotherthanfileinputboxesusethecontrol'sFormcollection(youcannotretrieveformelementswiththeASPRequest.Formobjectwhentheencodingtypeoftheformis"Multipart/Form-Data").Toretrieveparticularformvaluesusethenameoftheformelement(e.g.strVariable=objUpload.Form("txtSomeTextbox")).Youcanalsoretrieveitemsbytheirnumericalindex.Forexample,toretrievethevalueofthefirstformelementyoucanuse:strVariable=objUpload.Form(0).
Formdataiseitherretrievedallatonceorincrementally.Toretrievealloftheformdatawithonemethodcallyoumustuseeitherthecontrol'sSaveorSaveToMemorymethods.TheSavemethodsavesalluploadedfilestodisklocally,whileSaveToMemorysavesuploadedfilestomemory.IrregardlessofwhichmethodisuseditisVERYIMPORTANTtoknowthateithermethodpopulatestheFilescollectionwithALLuploadedfilesaswellasthecontrol'sFormcollectionwithALLformdata.
YoucanretrieveformdataincrementallybyrepeatedlycallingtheGetNextFilemethod(asopposedtousingeitherSaveorSaveToMemory).GetNextFilereturnsNextFileobjects,witheachNextFileobjectcontainingtheheaderinformationforoneuploadedfile.ThefirstNextFileobjectwillcorrespondtothefirstfileuploadedbytheuser,thenextNextFileobject(obtainedbycallingGetNextFileagain)willcontaintheheaderinformationforthenextpopulatedfileinputboxinthePOSTform,etc....ItisIMPORTANTtorealizethateachcalltotheGetNextFilemethodwillpopulatethecontrol'sFormcollectionwithallformdatawhichappearsBEFOREtheform'spopulatedfileinputboxwhichcorrespondstothecurrentNextFileobject.TheNextFileobject(likethecontrolitself)exposesbothSaveandSaveToMemorymethods.UseeitherofthesemethodswhileloopingthroughallNextFileobjectstooptionallysaveuploadedfilesintheirentirety.Youcanusewhateverdecidingcriteriayouwant,buttheTagNameandContentTypepropertiesinparticularcanbeveryusefulwhendecidingwhetherornottosavefilesuploadedbytheuser(seetheparagraphbelow).ToskipuploadingafilejustcalltheGetNextFilemethodagainwithoutfirstcallingtheobject'sSaveorSaveToMemorymethods.NotethatifyouchoosetoretrievethefileinitsentiretybycallingeitherSaveorSaveToMemorythentheFiles
collectionofthecontrolwillbepopulatedwiththeuploadedfileinquestion.
IfaformelementwasnotpopulatedbytheuserthentherewillbenocorrespondingFormItemobjectinthecontrol'sFormcollection(e.g.ifyouloopthroughtheFormcollectionwithaFor...EachlooptherewillbenoFormItemobjectfortheformelementsleftemptybytheuser).Ifyouretrievethevalueofaparticularformelementwhichwasleftemptybytheuserthereturnwillbe"Empty".Youcantesttoseeiftheuserleftaformelementblank,orempty,byusingVBScript'sIsEmptymethod.
Tofindouthowtoimplementaprogressbar(viatheProgressBarandStateServerComponents)clickhere.
YoucandisableorpresetcertainfeaturesoftheUploadcontrolthroughtheuseofregistrykeys.Clickhereformoreinformation.
NOTE:toutilizenamedconstantsinyourASPcodeuseaserver-sideincludeandincludetheUploadControl.incfile(distributedwiththeapplication).
MostmethodswillthrowanexceptionifanerroroccurssomakesurethatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatement.ExamineVBScript'sErrobjectafterafunctioncalltocheckforthesuccess/failureoftheoperation.
TheDundasUploadControl2.0providesmanymethodsforperformingfileoperations,suchasFileCopy,FileMove,etc....
YoucanalsotemorarilyassumeavalidWindowsaccountotherthanthedefaultwebaccountbycallingtheImpersonateUsermethod.Youmightwanttousethismethodifthedefaultwebaccountdoesnothavetherightstoperformaparticularoperation.OnceyouhavefinishedusingtheimpersonatedaccountyoucanrevertbacktothedefaultaccountbycallingtheImpersonationTerminatemethod.Othermethodsofthecontrolwhicharerelatedtorights/permissionsare:AllowAccess,DenyAccess,RevokeAccessandSetOwner.
PerformthefollowingstepswhenutilizingtheUploadcontrol:
1. MakesurethattheformwhichisPOSTINGthedataisusinganEncTypeof"Multipart/Form-Data".Youwillalsoneedtousefileinputelements(<inputtype="file">)inthisformsotheusercanbrowseforfilestobeuploaded.
2. EnableinlineerrortrappinginthepagebeingPOSTEDtowithan"OnErrorResumeNext"statement.Mostmethodsofthecontrolwillthrowanexceptionifunsuccessful,soyoucanperformerrortrappingusingVBScript'sErrobject.
3. CreateaninstanceoftheUploadcontrolinthepagewhichtheformisPOSTINGto.TodothisusetheServer.CreateObjectmethodwithaProgIDofeither"Dundas.Upload"or"Dundas.Upload.2".
4. YoucaneitherretrieveALLformdata(uploadedfilesaswellasforminputelements)atoncebyusingtheSaveorSaveToMemorymethodsofthecontrol.AlternativelyyoucanretrieveformdataincrementallybyusingtheGetNextFilemethod.PleasenotethatretrievingformdataincrementallywillresultintheFormandFilescollectionsalsobeingpopulatedincrementally.
5. Retrieveanyformelementvaluesviathecontrol'sFormcollection.NotethatemptyformelementsWILLNOTbeinsertedintotheFormcollection,andattemptingtoretrievethevalueofaformelementwhichwasleftemptybytheuserwillresultinanexceptionbeingthrown(whichyoucantrapfor).
6. ManipulatefilessavedtoeitherdiskormemoryviatheFilescollection.ThiscollectionispopulatedwitheitheroneSaveorSaveToMermorycallofthecontrol,unliketheSaveandSaveToMemorymethodsoftheNextFileobject(NextFileobjectsarereturnedbyGetNextFilecalls)whichpopulatestheFilescollectiononefileatatime.
7. SettheUploadobjecttonothing.
SeeAlso:Overview(DundasUploadControl2.0)|Tutorial1:UploadingMultipleFilesandUsingtheFormandFilesCollections|Tutorial2:
RetrievingFormDataIncrementallyUsingtheGetNextFileMethod|Tutorial3:ADOSupportandSavingaFileasaBLOB|Tutorial4:ImplementingaProgressBar
DisablingandSettingFeaturesviatheRegistry
Overview|Properties|Methods
SomeoftheUploadControl'sfeatures(i.e.methods)canbedisabled/enabledthroughtheuseofregistryvaluesinthe"HKEY_LOCAL_MACHINE\SOFTWARE\DundasSoftware\DundasUpload"key.
Anexceptionwillbethrownifadisabledmethodiscalled.
Ifaregistryvaluedoesnotexistoritissettozero(0)thenthemethodisenabled.However,settingaregistryentrytoanynon-zerovaluewillcausethecorrespondingmethodtobedisabled.
YoucanalsopresetthevalueofanyUploadcontrolpropertytoberead-onlyaswellashavingaspecificvalue.Toaccomplishthisjustcreatearegistryvalue(underthesamekey)withtheexactsamenameastherelevantpropertyandsetittothedesireddefault.Thetypeofthevaluedependsonthedatatypeoftheproperty.IfthepropertyinquestionisabooleanoranumericdatatypethenthecorrespondingregistrytypeshouldbeaDWORD.Astringpropertyequatestoastringregistrydatatype.Iftheuserattemptstochangethevalueofapropertywhichhasbeensettoread-onlyviatheregistrythenanexceptionwillberaised.
Refertothetablebelowforalistingofpossibleregistryentriesandtheircorrespondingmethods:
Value CorrespondingMethod(s)
DisableImpersonation ImpersonateUser,ImpersonationTerminate
DisableSecurity AllowAccess,DenyAccess,RevokeAccess
DisableRegisterServer RegisterServer
DisableSend SendBinary
DisableDirectoryDelete DirectoryDelete
DisableDirectoryCreate DirectoryCreate
DisableFileCopy FileCopy
DisableFileMove FileMove
DisableFileDelete FileDelete
DisableMemoryUpload SaveToMemory
DisableProgressBar UploadProgressComponentcreation
NameOfRelevantProperty Defaultvalue.YoucansetthedefaultvalueofANYUploadcontrolpropertybycreatingakeywiththesamenameastherelevantpropertyandthensettingitsvaluetothedesireddefaultvalue.
QuickStart(DundasUploadControl2.0)
Overview|Properties|Methods
ThefollowingcodedemonstrateshowtopopulatetheUploadcontrol'scollections,saveuploadedfilestodiskandretrieveformdata.Pleasenotethatforbrevitywedonotperformanyerrorchecking(donewithVBScript'sErrobjectandraisedexceptions).
Wewillassumethataformwithanencodingtypeof"Multipart/Form-Data"isPOSTINGtotheASPpagewhichcontainsthefollowingcode:
<%@Language=VBScript%><%'mostcontrolmethodsthrowanexceptionifanerroroccurssowewillusean'OnErrorResumeNextstatementOnErrorResumeNext
'createinstanceofUploadcontrolSetobjUpload=Server.CreateObject("Dundas.Upload.2")
'saveuploadedfilestotodisk.Notethatwecouldalsosavethe'uploadedfilestomemory.ThispopulatestheFormandFilescollectionsobjUpload.Save"c:\temp\"
'retrievethevalueofaformelementcalledtxtNamestrName=objUpload.Form("txtName")
'retrievethesizeofthefirstuploadedfilestrSize=objUpload.Files(0).Size
'releaseresourcesSetobjUpload=Nothing%>
Tutorial1:UploadingMultipleFilesandUsingtheFormandFilesCollections
Theobjectivesofthistutorialareto:
DemonstratehowtosaveuploadedfilesandpopulatetheFilesandFormcollections.
ShowhowtoaccesstheitemsintheFilesandFormcollections.
DemonstratehowtouseContentTypepropertytocheckforthetypeoffileswhichwereuploaded.
ShowhowtoretrievethenameofthefileinputboxesresponsiblefortheuploadsbyusingtheTagNameproperty.
WeareassumingthataformwithanEncTypeof"Multipart/Form-Data"isPOSTINGdatatotheASPpagewhichcontainsthefollowingcode.
Example
<%'mostcontrolmethodsthrowanexceptionifanerroroccurssowewillusean'OnErrorResumeNextstatementforerrortrappingpurposesOnErrorResumeNext
'createaninstanceoftheUploadcontrolSetobjUpload=Server.CreateObject("Dundas.Upload.2")
'wewillsavealluploadeddata(formdataaswellasanyuploadedfiles)todisk.'notethatwecouldalsosavetheuploadedfilestomemorywiththeSaveToMemorymethod.'alsonotethatboththeSaveandSaveToMemorymethodspopulatetheFormand'Filescollectionswithonemethodcall.'itsalsoimportanttorealizethatbydefaultfilessavedtodiskwillhaveuniquefilenames,but'thiscanbechangedwiththeUseUniqueNamespropertyobjUpload.Save"c:\temp\"
'checktoseeifmethodcallwassuccessfulusingVBScript'sErrobject,if'anerroroccurredwewillredirectusertoafictitiouserrorpageIfErr.Number<>0ThenResponse.Redirect"Error.asp"Else'useaForEachloopandchecktoseeiftheuploadedfileisan'executable(utilizingVBScript'sInStrmethod),ifitisdeleteitfromdisk.'butfirstwewilloutputthenameofthefileinputbox(es)responsibleforuploadsForEachobjUploadedFileinobjUpload.FilesResponse.Write"The""&objUploadedFile.TagName&""fileinputboxwasusedtouploadafile.<br>"IfInStr(1,objUploadedFile.ContentType,"octet-stream")Then'ifthedefaultwebaccountdoesnothavetherighttodeletefiles'forthefolderyousaveuploadedfilesto(inthiscasec:\temp)thenyoucaneitherset'therequiredrightsmanuallyoryoucouldusetheImpersonateUsermethodobjUploadedFile.DeleteEndIfNext
'wewilljustoutputthenameofthepopulatedformelementsandtheirvaluesForEachobjFormItemInobjUpload.FormResponse.Write"<br>Thenameoftheformitemis:"&objFormItemResponse.Write"<br>Thevalueoftheformitemis:"&objFormItem.Value&"<br>"Next
EndIf
'ReleaseresourcesSetobjUpload=Nothing%>
Tutorial2:RetrievingFormDataIncrementallyUsingtheGetNextFileMethod
Theobjectivesofthistutorialareto:
DemonstratehowtooptionallyuploadfilesusingtheGetNextFilemethod(retrievesformdataincrementally).
ShowhowtheFormcollectionispopulatedbyGetNextFilemethodcalls.
DemonstratehowtousetheTagNamepropertytocheckwhichuploadedfilesoriginatedfromwhichfileinputboxes.
DemonstratehowtousetheContentTypepropertytodeterminethetypeoffiletheuserwishestoupload.
WeareassumingthataformwithanEncTypeof"Multipart/Form-Data"isPOSTINGdatatoanASPpagewhichcontainsthefollowingcode.
Example
<%'mostcontrolmethodsthrowanexceptionifanerroroccurssowewilluseanOnError'ResumeNextstatementforerrortrappingpurposesOnErrorResumeNext
'createaninstanceoftheUploadcontrolSetobjUpload=Server.CreateObject("Dundas.Upload.2")
'retrievethefirstNextFileobject,whichcontainsheaderdataonlyfor'thefirstfileuploadedbyuser.NotethattheFormcollectionwillbe'populatedwithallformdatawhichoccursuptothefirstpopulated'fileinputbox(whichresultsinthisfirstNextFileobject)SetobjNextFile=objUpload.GetNextFile'checktoseeifmethodcallwassuccessfulusingVBScript'sErrobject,if'anerroroccurredwewillredirectusertoafictitiouserrorpage
IfErr.Number<>0ThenResponse.Redirect"Error.asp"
'wewillretrieveNextFileobjectsuntiltherearenomoreuploadedfiles'toprocess(eachNextFileobjectcorrespondstoapopulatedfileinputbox)'ifthefileisnotanexecutablewewillsavetheuploadedfiletomemory,if'itisanexecutablethenwewillnotsaveitatall(byjustcallingGetNextFileagain)DoUntilobjNextFileIsNothing
'NOTE:youcanretrieveanyformdatahereaslongasitoccursinthehtmlPOSTform'BEFOREthepopulatedfileinputboxwhichcorrespondstothecurrentNextFileobjectstrSomestring=objUpload.Form("SomeFormElement")
'nowsavefileifnotan*.exe,andfordemonstrationpurposeswewilloutput'thenameofthefileinputboxfromwhichtheuploadedfileoriginatedIfInStr(1,objNextFile.ContentType,"octet-stream",1)=0ThenobjNextFile.SaveToMemoryResponse.WriteobjNextFile.TagName&"<br>"EndIf
'callNextFileagain,toretrievetheheaderdataforthenextuploadedfile'onceagainitshouldbenotedthatthiswillpopulatetheFormcollection'withalldatauptothecorrespondingpopulatedfileinputboxSetobjNextFile=objUpload.GetNextFile
Loop
'releaseresourcesSetobjUpload=Nothing%>
Tutorial3:ADOSupportandSavingaFileasaBLOB
Theobjectivesofthistutorialareto:
DemonstratehowtoworkwithanADOrecordsetwithaDSNlessconnection.
ShowhowtosaveanuploadedfileasaBLOB.
WeareassumingthataformwithanEncTypeof"Multipart/Form-Data"isPOSTINGdatatotheASPpagewhichcontainsthefollowingcode.
Assumptions
1. ASQLServer7.0databasenamed"Temp"existswithaSQLusernameandpasswordof"sa"and"",respectively.
2. Thisdatabasehasatablecalled"Test".
3. Thetablehasan"image"columnnamed"Picture".
4. Thenameoftheserveris"SOMESERVER".
5. ThePOSTformusesoneormorefileinputboxes.
Example
<%'useinlineerrortrappingsothatanyexceptionsraisedbytheUploadcontrolarecaughtOnErrorResumeNext
'createaninstanceoftheUplaodcontrolSetobjUpload=Server.CreateObject("Dundas.Upload.2")
'wewilltemporarilysaveuploadedfilestodiskobjUpload.Save"c:\temp"
'settheconnectionstringstrConnect="Driver={SQLServer};Server=SOMESERVER;Database=Temp;UID=sa;PWD="
'createanADOrecordsetSetrs=Server.CreateObject("ADODB.Recordset")
'openarecordsetusingtheconnectionstringrs.Open"Test",strConnect,2,3
'loopthroughalluploadedfilesandsavetothedatabaseasBLOBsif'animagewasactuallyuploaded(weusetheContentTypepropertyof'theUploadedFileobjecttoaccomplishthis)ForEachobjFileInobjUpload.Files
IfInStr(1,objFile.ContentType,"image")<>0Then
'addanewrecordandinserttheimagefilers.AddNewrs("Picture").Value=objFile.Binary
EndIf
Next
'savechangesandcloserecordsetrs.Updaters.Close
'releaseresourcesSetrs=NothingSetobjUpload=Nothing%>
Tutorial4:ImplementingaProgressBar
Theobjectiveofthistutorialisto:
DemonstratehowtoutilizetheUploadcontrol,UploadProgresscomponentandtheStateServerinordertoimplementaprogressbar.
Toimplementaprogressbaryouwillneedtohavethreeelements:anhtmlInputForm;aProgressBarASPpage;andaSubmitActionASPpage.TheseelementsutilizetheDundasUploadcontroltogathertheuploaddataandPOSTtheuploadoperationdetailstotheStateServer.TheStateServer(StateServer.exe)isresponsibleforstoringuploadprogressinformationwhichcanthenbeupdatedandretrievedusinganinstanceofeithertheUploadProgresscomponentortheUploadcontrol.ThepurposeoftheUploadProgresscomponentistocreateuniqueProgressIDs,retrievetheprogressinformationfromtheStateServerandalsodeleteinformationstoredattheStateServerwhenanuploadisfinished.
Touseaprogressbaryoumustperformthefollowingactionsforthesethreerequireditems:
1. InputForm
1. BeforesubmittingtheformdatathedevelopermustcreateaninstanceoftheUploadProgresscomponent(theProgIDis"Dundas.UploadProgress)andrequestanewProgressID.
2. OpentheProgressBarwindowandpassthisProgressIDasaparameter.
3. Submittheformdata,onceagainpassingthisProgressIDasaparametertotheSubmitActionASPpage.
2. ProgressBarASP
1. Thispageshouldberefreshed(e.g.everytwoseconds).
2. TheprogressinformationisaccessedbyusinganinstanceoftheUploadProgresscomponentalongwiththeProgressIDpassedtothispagebytheInputForm.ToaccesstheuploaddatasettheProgressIDpropertyoftheUploadProgressinstancetothepassedProgressID,calltheGetProgressmethodandthenutilizetheTotalSize,UploadedSizeandPercentCompletedproperties.
3. Thestateinformationmustbedeletedwhentheuploadoperationiseithercompletedoranerroroccurs(anexceptionwillbethrown).TodeletetheuploadinformationattheStateServerjustcalltheDeleteProgressmethodoftheUploadProgressinstance.
4. Thewindowmaybeclosedwhentheuploadreacheseither100%oranerroroccurs.
3. SubmitActionASP
1. WhileuploadingthedatatheUploadcontrol(theProgIDis"Dundas.Upload.2")needstoposttheprogressstatusoftheuploadoperationtotheStateServer.ToaccomplishthisjustsettheProgressIDpropertyofthecontrolinstancetothepassedProgressID.
Howyouimplementthesestepsistotallyuptoyou.Ifyourequiremoredetailedinstructionsonutilizingaprogressbarthenrefertothefollowingorseethefullycommentedsamplecode.
NOTE:YouMUSTUSEan<%@ENABLESESSIONSTATE=FALSE%>statementatthetopoftheseASPpagessothatmorethanoneASPpagewillbeprocessedatthesametime.
DetailedInstructions
1. CreateamainASPpage(wewillcallthispage"main.asp").This
pagemust:
1. HaveaformwithanEncTypeof"multipart/form-data".Thisformneedstohaveoneormorefileinputboxesfortheuploadingofdata.
2. POSTthedatatoasecondarypage(wewillcallthispage"process.asp").
3. CreateaninstanceoftheUploadProgresscomponentbeforePOSTINGthedata(theProgIDis"Dundas.UploadProgress)."OncethisisdoneyoumustthenobtainanewProgressID(whichuniquelyidentifieseachuploadoperation)bycallingtheGetNewProgressIDmethodoftheUploadProgresscomponent.
4. PassthisProgressIDtoprocess.aspwhenPOSTINGthedata(howthisisdoneisuptoyou).Inthefollowingexampleweaccomplishthisbyusingastandardformbutton(insteadofa"submit"button)andwespecifyaclient-sidefunctionfortheOnClickevent.Inthisfunctionweuse"document.form.action"and"document.form.submit"statementstosubmittheformdatatoprocess.asp(afteropeningtheprogressbar.aspwindow-->seethenextstep).Notethatthe"actionstatement"usesaquerystringtopasstheProcessIDtoprocess.asp.
5. Createtheprogressbarwindow(beforePOSTINGthedata).ThiswindowisanASPpage(let'scallit"progressbar.asp")andonceagainyouHAVEtoletthispageknowwhattheProgressIDis(whichyouobtainedfromtheUploadProgresscomponent).Weaccomplishthisbyusinga"window.open"statementinourformbutton'sOnClickevent.Notethatthis"window.open"statementusesaquerystringtopassthisProgressID.
2. Createthepagewhichwillprocessthedata(process.asp).Thispagemust:
1. UtilizethepassedProgressIDandsettheProgressIDpropertyoftheUploadcontroltothisProgressIDBEFOREcallingeithertheSave,SaveToMemoryorGetNextFilemethod.Oncethisis
doneyoucanproceedwiththeuploadingofdata.BysettingthispropertytheUploadcontrolinstancewillcontinuouslyupdatetheStateServerwithuploadoperationdetails,whichcanthenberetrievedviatheProgressUploadcomponentintheprogressbar.asppage.
3. CreatetheprogressbarwindowviaanASPpage("progressbar.asp").Thispagemust:
1. Beabletodisplaytheamountofdatawhichhascurrentlybeenuploaded.Howyouaccomplishthisisuptoyou.Notethatthefollowingsamplecodeusesembeddedtableswithdifferingcolorstoaccomplishthis.
2. Berefreshed,forexample,everytwo(2)seconds.Youcanuseametarefreshtagforthis.
3. Retrievedetailsconcerningtheuploadoperation.ThisisaccomplishedbycreatinganinstanceoftheUploadProgresscomponent,settingitsProgressIDpropertytotheProgressIDpassedbymain.asp,callingtheGetProgressmethodandthenutilizingtheTotalSize,UploadedSizeandPercentCompletedproperties.Everytimethepageisrefreshedyoucanusethesepropertiestoupdateyour"progessbar".
4. IftheStateServer(StateServer.exe)islocatedonanothermachinecomparedtothisASPpagethenyoumustsettheStateServerpropertyoftheUploadProgressandUploadobjectstotheIPaddressofthemachinewheretheStateServerislcoated.Ifyouhavesetthe"Port"propertyoftheStateServertosomethingotherthanthedefaultthenyoumustsettheStateServerPortpropertyoftheUploadProgressandUploadobjectstothesameport.
5. Deletetheprogressinformationoncetheuploadoperationiscancelledorcompleted.ThisisdonebycallingtheDeleteProgressmethodoftheUploadProgresscomponent.
6. Youcanclosethewindowoncetheuploadiscompletedorcancelled.Howyoudothisisuptoyou.Notethatthefollowing
samplecodeaccomplishesthisthroughclient-sidescript.
NOTE:YouMUSTUSEan<%@ENABLESESSIONSTATE=FALSE%>statementatthetopoftheseASPpagessothatmorethanoneASPpagewillbeprocessedatthesametime.
AssumptionsforthefollowingSampleCode
1. Therearethreepagestothissample:main.asp,progressbar.aspandprocess.asp(asdescribedabove).
2. Theforminmain.aspisPOSTINGdatatoprocess.aspwithanEncTypeof"mulitpart/form-data".Itisassumedthatthisformhasonefileinputboxnamed"file1".
main.asp<%@ENABLESESSIONSTATE=FALSE%>'turnoffsessionstatesupportsothatmorethan'oneASPpagecanbeprocessedatthesametime.<html><head></head><bodycolor="black"bgcolor="white"><%dimobjUploadProgress'UploadProgresscomponentinstancedimProgressID'newprogress(state)id-uniquelyidentifiesthisuploadoperation
'createaninstanceoftheUploadProgresscomponentsetobjUploadProgress=server.CreateObject("Dundas.UploadProgress")
'wemustretrieveanewprogressid,whichispassedtobothprocess.aspandprogressbar.aspProgressID=objUploadProgress.GetNewProgressID%><Scriptlanguage="javascript"><!--//retrievetheState(Progress)IDtobepassedtoprogressbar.asp//andprocess.aspProgressID=<%=ProgressID%>;
functionUpload()//thisjavascriptfunctionrunswhentheuserclicksontheform'sbutton.//itopenstheprogressbar.aspwindowandthensubmitstheformdatatoprocess.asp{if(ProgressID!=-1){//onlyopenprogressbar.aspwindowifthereisavalidid.Wewillcenterthisprogressbaraswell.Param="SCROLLBARS=no,RESIZABLE=no,TOOLBAR=no,STATUS=no,MENUBAR=no,WIDTH=400,HEIGHT=100";Param+=",TOP="+String(window.screen.Height/2-50);Param+=",LEFT="+String(window.screen.Width/2-200);//notethatwepasstheProgressIDtoprogressbar.aspwindow.open("ProgressBar.asp?ProgressID=<%=ProgressID%>",null,Param);}
//nowthatprogressbarwindowisopensubmittheformdatatoProcess.asp,passing//theProgressIDasaquerystringparameterdocument.frmMain.action="Process.asp?ProgressID=<%=ProgressID%>"document.frmMain.submit();}//--></Script><formname="frmMain"action="process.asp"enctype="multipart/form-data"method="post">Pleasechooseafiletobeuploaded:<inputtype="file"name="File1"><br><br><!--Notethatweuseastandardbuttonandnotasubmitbutton.Wedothissothatwecanopentheprogressbarwindow(Progress.asp)aswellaspassthesubmitteddatatothepagewhichprocessesthesubmittedformdata--><inputtype="button"name="submit1"value="UploadFile"OnClick="Upload()"></form></body></html>
process.asp<%@ENABLESESSIONSTATE=FALSE%>
<%'wejustdisabledsessionstatesothatmorethanoneasppagecanbeprocessedatonce
OnErrorResumeNext
'createaninstanceoftheUploadcomponentDimobjUploadSetobjUpload=Server.CreateObject("Dundas.Upload.2")
'settheProgressIDpropertyofthecontroltothestate(progress)IDwhich'wasobtainedinmain.aspandpassedasaquerystring.Bysettingthisproperty'theUploadcontrolinstancewillcontinuouslyupdatetheStateServerwith'informationconcerningthisparticularuploadoperation.objUpload.ProgressID=Request.QueryString("ProgressID")
'setmaximumfilesizeto2MByteobjUpload.MaxFileSize=200000000
'saveuploadeddatatomemory,andthencheckforerrorsobjUpload.SaveToMemory'ifanerroroccurredwewillclosetheprogressbar.aspwindowby'deletingthestateinformationattheStateServerIfErr.Number<>0ThendimobjUploadProgresssetobjUploadProgress=server.CreateObject("Dundas.UploadProgress")objUploadProgress.ProgressID=Request.QueryString("ProgressID")objUploadProgress.DeleteProgressEndIf
'releaseresourcesSetobjUpload=Nothing%>
progressbar.asp<%@ENABLESESSIONSTATE=FALSE%><html><head>
<metahttp-equiv=refreshcontent="1,ProgressBar.asp?ProgressID=<%=Request.QueryString("ProgressID")%>"></head><%
OnErrorResumeNext
'forcethispagetoexpireimmediatelyResponse.Expires=-10000
'createaninstanceoftheUploadProgresscomponentSetobjUploadProgress=Server.CreateObject("Dundas.UploadProgress")
'iftheStateServerisrunningonadifferentmachinecomparedtotheseASPpages'thenthisiswhereyouwouldhavetosettheStateServer'sIPaddress'objUploadProgress.StateServer="127.0.0.1"
'retrieveprogressdatafromtheStateServerobjUploadProgress.ProgressID=Request.QueryString("ProgressID")objUploadProgress.GetProgressPercentage=objUploadProgress.PercentCompletedTotalSize=objUploadProgress.TotalSizeUploadedSize=objUploadProgress.UploadedSize
'ifthereisnodatayetforthisparticularuploadoperationthentheseproeprtieswill'besettonegativeone(-1)IfTotalSize=-1ORUploadedSize=-1Then'ifnodatayetsettozero,sincewedonotwanttodisplaynegativeoneTotalSize=0UploadedSize=0EndIf
'Ifanerroroccurssetthepercentagevalueto-1.Theclient-sidescriptbelow'willclosetheprogressbarwindowwhenthisoccurs.Notethatanegativeonewill'beencounteredsincewedeletethestateinformationforthisparticularupload'operationwhen100%isreached,sothenextcalltotheGetProgressmethodwill
'resultinanexceptionbeingraised,therebyresultinginthiswindowbeingclosed.IfErr.number<>0ThenPercentage=-1EndIf
'deleteprogressdatawhenwehit100%IfobjUploadProgress.PercentCompleted=100ThenobjUploadProgress.DeleteProgressEndIf
'releaseresourcesSetobjUploadProgress=Nothing%>
<script><!--setavariabletothepercentcomplete-->varval=<%=Percentage%>;
//Ifthereareanyerrorsoruploadiscompletethenclosewindowif(val==-1){top.close();}</script><body><!--useembeddedtableswithdifferentcolortosimulateaprogressbar--><tableborder="1"width="100%"><tr><td><tableID="Prog"border="0"width="<%=Percentage%>%"bgcolor="#FF0000"><tr><tdwidth="100%"> </td></tr></table></td>
</tr></table></body><Palign="center"><FONTsize="2"><%=Percentage%>%(Uploaded<%=UploadedSize%>of<%=TotalSize%>bytes)</FONT></P></html>
Properties(DundasUploadControl2.0)
Overview|Properties|Methods
CheckMacBinary YoucansetthispropertytoTRUEbeforeuploadingsothateachuploadedfileischeckedforaMacBinaryformat.
MaxFileCount Themaximumnumberoffileswhichcanbeuploaded.
MaxFileSize Themaximumsizeofanyfileuploadedbytheuser(inbytes).
MaxUploadSize Themaximumamountofdatathatcanbeuploadedtotheserver(inbytes).Thisincludesformdataaswellasuploadedfiles.
ProgressID SetthispropertytoauniqueID(obtainedbytheUploadProgresscomponentfromtheDundasStateServer)whenprocessinganuploadwhichutilizesaprogressbarwindow.
StateServer SetthispropertytotheIPaddressoftheDundasStateServerwhenprocessinganuploadwhichutilizesaprogressbarwindow.
StateServerPort SetthispropertytotheportthattheStateServerislisteningonwhenprocessinganuploadwhichutilizes
aprogressbarwindow.
UseUniqueNames Storesuploadedfileswithuniquefilenames.ThisisdonebyprecedingtheoriginalfilenamewithaGUIDand"_".
UseVirtualDir SetthispropertytoTRUEsothatvirtualdirectoriesareused.IfTRUEthenanymethodwhichutilizesaPathargumentshoulduseavirtualpathnameandnotaphysicalpathname.
CollectionProperties
Files CollectionofUploadedFileobjects,eachofwhichrepresentsafileuploadedfromanhtmlform.
Form CollectionofFormItemobjects,witheachobjectcorrespondingtoaformelement.Notethatinputelementsofthefiletype(<inputtype="file">)arenotrepresentedintheFormcollection.
CheckMacBinary(DundasUploadControl2.0)
Overview|Properties|Methods
SetthispropertytoTRUEbeforeuploadingsothateachuploadedfileischeckedforaMacBinaryformat.
Syntax
UploadObject.CheckMacBinary=[boolean]
TheCheckMacBinarypropertysyntaxhasthefollowingparts:
Part Description
boolean IfsettoTRUE(beforeuploading)theneachuploadedfilewillbecheckedforaMacBinaryformat.
Remarks
ClientmachineswhichareMacintoshmayutilizeaprotocolcalled"MacBinary".
MacBinaryformattedfilesconsistofa128-byteheader,adataforkandaresourcefork.IfyousetthispropertytoTRUEandaMacBinaryfileisencounteredthenonlythedataforkportionoftheuploadedfilewillbesaved.
MaxFileCount(DundasUploadControl2.0)
Overview|Properties|Methods
Themaximumnumberoffileswhichcanbeuploadedtotheserver.
Syntax
UploadObject.MaxFileCount=[long]
TheMaxFileCountpropertysyntaxhasthefollowingparts:
Part Description
long Themaximumnumberoffileswhichcanbeuploadedtotheserver.Defaultstonegativeone(nolimit).
Remarks
SetthispropertybeforecallingSaveorSaveToMemoryinordertolimitthenumberoffilesauserisallowedtoupload.Ifthislimitisexceededandyoucalleitherthecontrol'sortheNextFileobject'sSaveorSaveToMemorymethodsanexceptionwillberaisedandthesaveoperationwillbecancelled.
NotethatifthemaximumnumberofallowableuploadsisexceededasaresultofaNextFileobject'ssaveoperationthenanypreviousuploadeddatawillstillbeavailablefromthecontrol'sFormcollection.
MakesurethatyouuseanOnErrorResumeNextstatementsothatanyraisedexceptionsarehandled.ToretrievearelevanterrorstringuseVBScript'sErr.Descriptionproperty.
Setthispropertytonegativeone(-1)fornolimit.
SeeAlso:MaxFileSize|MaxUploadSize
MaxFileSize(DundasUploadControl2.0)
Overview|Properties|Methods
Themaximumallowablefilesizeinbytes.
Syntax
UploadObject.MaxFileSize=[long]
TheMaxFileSizepropertysyntaxhasthefollowingparts:
Part Description
long Themaximumallowablefilesizeinbytes.Defaultstonegativeone(nolimit).
Remarks
SetthispropertybeforecallingSaveorSaveToMemoryinordertolimitthesizeoffilesuploadedbyauser.Ifyoucalleitherthecontrol'sortheNextFileobject'sSaveorSaveToMemorymethodsandthislimitisexceededthenanexceptionwillberaised.
Notethatifafileisencounteredwhichexceedsthislimitthennofurtherformdatawillbeprocessed.However,youcanstillaccessanyformdataprocessedpreviouslythroughthecontrol'sFormcollection.
Setthispropertytonegativeone(-1)fornolimit.
MakesurethatyouuseanOnErrorResumeNextstatementsothatanyraisedexceptionsarehandledinyourASPpage.ToretrievearelevanterrorstringuseVBScript'sErr.Descriptionproperty.
SeeAlso:MaxFileCount|MaxUploadSize
MaxUploadSize(DundasUploadControl2.0)
Overview|Properties|Methods
Themaximumamountofdatawhichcanbeuploadedtotheserver.
Syntax
UploadObject.MaxUploadSize=[long]
TheMaxUploadSizepropertysyntaxhasthefollowingparts:
Part Description
long Themaximumamountofdatawhichcanbeuploadedtotheserver(inbytes).Defaultstonegativeone(nolimit).
Remarks
Uploadeddataconsistsofalluploadedfilesaswellasanyformdata(asaresultofaPOSToperation).
Ifyoudonotsetthispropertythenthedefaultofnegativeone(-1)isusedandnolimitisset.
CallingtheSaveorSaveToMemorymethodsofeitherthecontrolortheNextFileobjectwillresultinanexceptionbeingthrowniftheuploadeddataexceedsthemaximumallowablelimit.Asaresultnodatawillbesavedandthecontrol'scollectionswillnotbepopulated.
UnliketheMaxFileCountortheMaxFileSizepropertiesifthisallowabledatalimitisexceededthentherewillbenoavailabledataviathecontrol'sFormcollectionirregardlessofwhentheexceptionisthrown.
Setthispropertytonegativeone(-1)fornolimittotheuploadeddata.
SeeAlso:MaxFileCount|MaxFileSize
ProgressID(DundasUploadControl2.0)
Overview|Properties|Methods
SetthispropertytoauniqueID(obtainedbytheUploadProgresscomponentfromtheDundasStateServer)whenprocessinganuploadwhichutilizesaprogressbarwindow.
Syntax
long=UploadObject.ProgressID
TheProgressIDpropertysyntaxhasthefollowingparts:
Part Description
long AnIDwhichuniquelyidentifiesoneparticularuploadoperation.Defaultstonegativeone(disabled).
Remarks
YoumustsetthispropertybeforecallingeithertheSaveorSaveToMemorymethodsofthecontrolifyouwanttoutilizetheStateServerandtheUploadProgresscomponentinordertodisplayaprogressbar.
SettingthispropertyallowstheStateServercomponent'sdatafortheuploadoperationinquestiontobecontinuoslyupdatedbytheUploadControl.Inotherwords,astheuploadingofformdataoccurstheStateServeriscontinuouslybeingupdatedastohowmuchdatahasbeenuploaded,therebyallowingtheUploadProgresscomponenttoretrievethisinformationinordertoupdateaprogressbarwindow.
AuniqueIDisgeneratedbycallingtheGetNewProgressIDmethodoftheUploadProgresscomponent.
SeeAlso:Tutorial4:ImplementingaProgressBar|StateServer|StateServerPort
StateServer(DundasUploadControl2.0)
Overview|Properties|Methods
SetthispropertytotheIPaddressoftheDundasStateServerwhenprocessinganuploadwhichutilizesaprogressbarwindow.
Syntax
UploadObject.StateServer=string
TheStateServerpropertysyntaxhasthefollowingparts:
Part Description
string TheIPaddressofthemachinewhichisrunningtheDundasStateServer.Defaultstothelocalloopbackaddress(127.0.0.1).
Remarks
YoumustsetthispropertybeforecallingeithertheSaveorSaveToMemorymethodsoftheUploadcontrolif:youwanttoutilizetheStateServerandtheUploadProgresscomponentinordertodisplayaprogressbar;andtheStateServerisrunningatadifferentmachinecomparedtowheretheASPpage(s)inquestionarelocated.
YoudonothavetosetthispropertyiftheStateServerisrunningonthesamemachinewhichtheASPpageinquestionisrunningonsincethelocalloopbackaddressisthedefault.
SeeAlso:Tutorial4:ImplementingaProgressBar|StateServerPort|ProgressID
StateServerPort(DundasUploadControl2.0)
Overview|Properties|Methods
SetthispropertytotheportthattheStateServerislisteningonwhenprocessinganuploadwhichutilizesaprogressbarwindow.
Syntax
UploadObject.StateServerPort=long
TheStateServerPortpropertysyntaxhasthefollowingparts:
Part Description
long TheportwhichtheDundasStateServerislisteningon.Defaultsto6723,whichisalsothedefaultportthattheStateServerissetto.
Remarks
YoumustsetthispropertybeforecallingeithertheSaveorSaveToMemorymethodsoftheUploadcontrolif:youwanttoutilizetheStateServerandtheUploadProgresscomponentinordertodisplayaprogressbarand;theportthattheStateServerislisteningonwaschangedfromthedefault(whichisalsoport6723).
SeeAlso:Tutorial4:ImplementingaProgressBar|StateServer|ProgressID
UseUniqueNames(DundasUploadControl2.0)
Overview|Properties|Methods
Abooleanpropertywhichdeterminesifuploadedfilesaresavedtodiskwithuniquefilenames.
Syntax
UploadObject.UseUniqueNames=[boolean]
TheUseUniqueNamespropertysyntaxhasthefollowingparts:
Part Description
boolean IfthispropertyissettoTRUE(thedefault)thenfileswillbesavedtodiskwithuniquefilenames.IfitissettoFALSEthenfileswillbesavedtodiskusingtheiroriginalfilenames.
Remarks
IfthisisTRUE(thedefault)thentheresultingfilenamewillhavethefollowingformat:GUID_OriginalFilename.
Wehighlyrecommendthatyousavefileswithuniquefilenamesifyouaresavingtodisk.Thisensuresthattwouserswhouploadafilewiththesamenameatthesametimedoesnotcauseproblems.
SeeAlso:Save
UseVirtualDir(DundasUploadControl2.0)
Overview|Properties|Methods
Abooleanpropertywhichdeterminesiffilesave,copyormoveoperationsshouldusephysicalorvirtualdirectories/paths.
Syntax
UploadObject.UseVirtualDir=[boolean]
TheUseVirtualDirpropertysyntaxhasthefollowingparts:
Part Description
boolean IfthispropertyissettoTRUEthenyoumustspecifyavirtualdirectoryifyouarecopying,movingorsavingfilestodisk.IfitissettoFALSE(thedefault)thenyoumustspecifyaphysicaldirectory/path.
Remarks
IfthispropertyisTRUEthenmakesurethatthevirtualpathspecifiedinaSavemethodcallbeginswithaforwardslash.Thefirstdirectoryspecifiedaftertheforwardslashmustbeprecededwithaforwardslash,andanysubsequentsub-directories(physicalfolderslocatedbeneaththevirtualdirectory)areseparatedwithforwardslashes.
Youwillalsohavetospecifyvirtualpathswhencallinganyothermethodswhichtakeapathargument(e.g.Move,Copy,etc.).
Usethefollowingformatforarelativepathargumentinafunctioncall:objUpload.Save"/MyVirtualDir/ASubDirectory".
SeeAlso:Save
Methods(DundasUploadControl2.0)
Overview|Properties|Methods
DirectoryCreate Createsadirectory.
DirectoryDelete Deletesadirectory.
DirectoryExists Checkstoseeifthespecifieddirectoryexists.
FileCopy Copyafilefromonelocationtoanother.
FileDelete Deletesaspecifiedfile.
FileExists Checkstoseeifthespecifiedfileactaullyexists.
FileMove Movesafilefromonelocationtoanother.
GetFileDirName Callthismethodtoextractthedirectorynamefromafullyspecifiedpathname.
GetFileExt Callthismethodtoextractthefileextensionfromafullyspecifiedpathname.
GetFileName Callthismethodtoextractthefilenamefromafullyspecifiedpathname.
GetNextFile Usedtoretrieveformdataincrementally,thismethodreturnsNextFileobjects.
GetUniqueName ThismethodreturnsaGUID(usefulforsavingfileswithuniquenames).
ImpersonateUser Callthismethodtotemporarilyutilizea
Windowsaccountotherthanthedefault(usuallytheIUSRaccount).
ImpersonationTerminate CallthismethodtorevertbacktothedefaultuseraccountafterhavingcalledtheImpersonateUsermethod.
RegisterServer CallthismethodtoregisteraCOMcomponent.
Save SavesuploadedfilestodiskandpopulatestheUploadcontrol'sFormandFilescollections.
SaveToMemory Savesalluploadedformdata(uploadedfilesaswellasformelementvalues)tomemory.ThismethodalsopopulatestheFilesandFormcollections.
SendBinary Callthismethodtodownloadfilesfromtheserver.
DirectoryCreate(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtocreateafolder.
Syntax
UploadObject.DirectoryCreate(PathAsString,[MustNotExistAsBoolean=FALSE])
TheDirectoryCreatemethodsyntaxhasthefollowingparts:
Part Description
Path Thenameofthefoldertobecreated.Eitheravirtualorphysicalpathnamemustbeused,dependingontheUseVirtualDirpropertysetting.
MustNotExist Abooleanwhichspecifieswhetherornotthedirectorymustnotexist.
Remarks
Anexceptionisthrowniftheoperationfails.Trapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
NotethatanexceptionisalsothrownifyousettheMustNotExistargumenttoTRUEandthefolderalreadyexists.Theresultingerrorstringwillbe"Cannotcreateafilewhenthatfilealreadyexists."
IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalid
alias.Anyfollowingfoldersneedtobeseparatedwithforwardslashes.
Ifthedefaultuseraccountdoesnothavepermissiontocreateafolderthenan"AccessDenied"errorwilloccur.YoucanusetheImpersonateUsermethodtotemporarilyassumeanotheruseraccountwhichhasthepermissiontocreateafolderandthencallImpersonationTerminatetoresumeusingthedefaultaccount.
SeeAlso:DirectoryDelete|DirectoryExists
DirectoryDelete(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtodeleteafolder.
Syntax
UploadObject.DirectoryDelete(PathAsString[,DeleteContentAsBool=FALSE])
TheDirectoryDeletemethodsyntaxhasthefollowingparts:
Part Description
Path Thenameofthefoldertobedeleted.Eitheravirtualorphysicalpathnamemustbeused,dependingontheUseVirtualDirpropertysetting.
DeleteContent IfsettoTRUEthenthefolderandallofitscontentswillbedeleted.
Remarks
Anexceptionisthrowniftheoperationfails(theNumberpropertyoftheErrobjectwillbeanon-zerovalueuponfailure).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
Ifthedefaultuseraccountdoesnothavepermissiontodeleteafolderthenan"AccessDenied"errorwilloccur.YoucanusetheImpersonateUsermethodtotemporarilyassumeanotheruseraccountwhichhasthepermissiontodeleteafolderandthencallImpersonationTerminatetoresumeusingthedefaultaccount.FormoredetailsondeletinguploadedfilesattheserverrefertotheUploadedFileObjecttopic.
Anexceptionisraisedifthespecifiedfolderdoesnotexist,andtheresultingerrorstringis"Thesystemcannotfindthefilespecified".TryingtodeleteafolderwhichisnotemptyandDeleteContent=FALSEalsoresultsinanexception,andtheresultingerrorstringfromthissituationis"Thedirectoryisnotempty".
IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalidalias,andanysub-foldersneedtobeseparatedwithforwardslashes.IfyouspecifyaphysicalpathnamewhenUseVirtualDirisTRUEanexceptionwillbethrown.
SeeAlso:DirectoryCreate|DirectoryExists
DirectoryExists(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtocheckifthespecifiedfolderalreadyexistsontheserver.
Syntax
boolean=UploadObject.DirectoryExists(PathasString)
Part Description
Path Thepathnameofthefoldertobechecked.
Remarks
ReturnsTRUEifthefolderisfoundontheserver,otherwiseFALSEisreturned.
NotethatthetypeofpathspecifieddependsontheUseVirtualDirpropertysetting.IfthispropertyisFALSEthenaphysicalpathnameisrequired.IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalidalias,andanysub-foldersneedtobeseparatedwithforwardslashes.
SeeAlso:DirectoryCreate|DirectoryDelete
FileCopy(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtocopyafilefromaspecifiedsourcetoaspecifieddestinationattheserver.
Syntax
UploadObject.FileCopy(SourceAsString,DestinationAsString[,FailIfExistsAsBoolean=TRUE]
TheFileCopymethodsyntaxhasthefollowingparts:
Part Description
Source Thenameofthefiletobecopied.Useeitherarelativeorabsolutepathname,dependingonthesettingoftheUseVirtualDirproperty.
Destination Thenameofthefoldertocopythefileto.Eitherarelativeorabsolutepathname,dependingonthesettingoftheUseVirtualDirproperty.
FailIfExits IfTRUEthenanexceptionwillbethrownifthefilealreadyexistsatthespecifieddestination.IfthisisFALSEanexistingfilewillbeoverwritten.DefaultstoTRUE.
Remarks
Anexceptionisthrowniftheoperationfails.Trapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnError
ResumeNextstatementatthebeginningoftheASPpage.
IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalidalias,andanysub-foldersneedtobeseparatedwithforwardslashes.IfyouspecifyaphysicalpathnamewhenUseVirtualDirisTRUEanexceptionwillbethrown.
Ifthedefaultuseraccountdoesnothavetheappropriatepermissiontoperformthisactionthenan"AccessDenied"errorwilloccur.YoucanusetheImpersonateUsermethodtotemporarilyassumeanotheruseraccountwhichhastheappropriatepermission,performtheoperationandthencallImpersonationTerminatetoresumeusingthedefaultaccount.
SeeAlso:FileDelete|FileExists|FileMove
FileDelete(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtodeleteafile.
Syntax
UploadObject.FileDelete(PathAsString)
TheFileDeletemethodsyntaxhasthefollowingparts:
Part Description
Path Locationofthefiletobedeleted.Useeitherarelativeorabsolutepathname,dependingonthesettingoftheUseVirtualDirproperty.
Remarks
Anexceptionisthrowniftheoperationfails.Trapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalidalias,andanysub-foldersneedtobeseparatedwithforwardslashes.IfyouspecifyaphysicalpathnamewhenUseVirtualDirisTRUEanexceptionwillbethrown.
Ifthedefaultuseraccountdoesnothavetheappropriatepermissiontoperformthisactionthenan"AccessDenied"errorwilloccur.YoucanusetheImpersonateUsermethodtotemporarilyassumeanotheruseraccountwhichhastheappropriatepermission,performtheoperationand
thencallImpersonationTerminatetoresumeusingthedefaultaccount.
SeeAlso:FileCopy|FileExists|FileMove
FileExists(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtoseeifthespecifiedfileexistsatthespecifiedlocation.
Syntax
UploadObject.FileExists(PathAsString)AsBoolean
TheFileExistsmethodsyntaxhasthefollowingparts:
Part Description
Path Thenameofthefiletobechecked.Useeitherarelativeorabsolutepathname,dependingonthesettingoftheUseVirtualDirproperty.
Remarks
ThismethodreturnsTRUEifthefileisfound,otherwiseFALSEisreturned.
IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalidalias,andanysub-foldersneedtobeseparatedwithforwardslashes.
SeeAlso:FileCopy|FileDelete|FileMove
FileMove(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtomoveafilefromonelocationtoanother.
Syntax
UploadObject.FileMove(SourceAsString,DestinationAsString[,FailIfExsistsAsBoolean=TRUE])
TheFileMovemethodsyntaxhasthefollowingparts:
Part Description
Source Nameofthefiletobemoved.Useeitherarelativeorabsolutepathname,dependingonthesettingoftheUseVirtualDirproperty.
Destination Destinationlocation.Useeitherarelativeorabsolutepathname,dependingonthesettingoftheUseVirtualDirproperty.
FailIfExists IfTRUEanexceptionwillbethrownifthefilealreadyexistsatthespecifieddestination.IfthisisFALSEthenanexistingfilewiththesamenamewillbeoverwritten.DefaultstoTRUE.
Remarks
Anexceptionisthrowniftheoperationfails.Trapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
ThismethodcanbeusedtorenameafilebyspecifyingthesamedirectorypathwithdifferingfilenamesfortheSourceandDestinationarguments.
IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalidalias,andanysub-foldersneedtobeseparatedwithforwardslashes.IfyouspecifyaphysicalpathnamewhenUseVirtualDirisTRUEanexceptionwillbethrown.
Ifthedefaultuseraccountdoesnothavetheappropriatepermissiontoperformthisactionthenan"AccessDenied"errorwilloccur.YoucanusetheImpersonateUsermethodtotemporarilyassumeanotheruseraccountwhichhastheappropriatepermission,performtheoperationandthencallImpersonationTerminatetoresumeusingthedefaultaccount.
SeeAlso:FileCopy|FileExists|FileDelete
GetFileDirName(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtoextractthedirectorynamefromafullyspecifiedpath.
Syntax
UploadObject.GetFileDirName(PathAsString)AsString
TheGetFileDirNamemethodsyntaxhasthefollowingpart(s):
Part Description
Path Fullpathandfilename.
Remarks
Thismethodtruncatesthefilenamefromafullyspecifiedpathname.Notethatthismethoddoesnotcheckfortheexistenceofthespecifieddirectoryorfile.
AnexceptionISNOTRAISEDifthespecifiedfileinthepathnamedoesnotexist.
SeeAlso:GetFileExt|GetFileName
GetFileExt(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtoextractthefileextensionfromafullyspecifiedpath.
Syntax
UploadObject.GetFileExt(PathAsString)AsString
TheGetFileExtmethodsyntaxhasthefollowingpart(s):
Part Description
Path Fullpathandfilenamewithafileextension.
Remarks
Thismethodsimplytruncatesandreturnstheextensionfromafullyspecfiedpath.Notethatthismethoddoesnotcheckfortheexistenceofthedirectorynorthefile.
AnexceptionISNOTRAISEDifthespecifiedfileinthepathnamedoesnotexist.
SeeAlso:GetFileDirName|GetFileName
GetFileName(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtoextractthefilenamefromafullyspecifiedpath.
Syntax
UploadObject.GetFileName(PathAsString)AsString
TheGetFileNamemethodsyntaxhasthefollowingpart(s):
Part Description
Path Fullpathandfilenamewithextension
Remarks
Thismethodsimplytruncatesthefilename(withtheextension)fromafullpathname.Notethatthismethoddoesnotcheckfortheexistenceofthedirectorynorthefile.
ThismethodisveryusefulifyouareloopingthroughtheFilescollectionandwanttocopyormovefilessavedtodisktoanotherlocation,possiblydependingonsomesortofcriteriaconcerningtheuploadedfile.UseGetFileNamewiththeUploadedFileobject'sPathpropertyasthePathargumentsothatyoucancopythefile(s)toanotherlocationusingthesamefilename.SeetheCopymethodforsamplesourcecodeillustratingthis.
AnexceptionISNOTRAISEDifthespecifiedfileinthepathnamedoesnotexist.
SeeAlso:GetFileDirName|GetFileExt
GetNextFile(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtoretrievetheheadersforuploadedfilesoneatatime.
Syntax
SetNextFileObject=UploadObject.GetNextFile()
Remarks
ThismethodreadsanHTMLforminatop-downmannerandreturnsaNextFileobjectwhendatafromapopulatedfileinputboxisencountered.Anyformdata(e.g.textboxdata)priortothepopulatedfileinputboxisuploadedtotheFormcollection."Nothing"isreturnedifnopopulatedfileinputboxisfound.
PleasenotethatiftheuserdidnotspecifyanyfilestobeuploadedthencallingthismethodforthefirsttimewillresultintheUploadcontrol'sFormcollectiontobepopulatedwithALLvaluesenteredbytheuserintotheform'selements.
Toloopthroughalluploadedfilesusea"DoUntil"loop,andtesttoseeifthereturnedNextFileobjectis"Nothing".Seethesamplecodebelowforanexampleofthis.
Onlytheheaderforthefileisuploaded,andyoucanprogrammaticallydecideifyouwanttoretrievethefileinitsentirety,dependingonsomesortofcriteria(e.g.ifthefileisanimage).IfyouwanttoretrievetheentirefilethencalleithertheSavemethodortheSaveToMemorymethodoftheNextFileobjectBEFOREcallingGetNextFileagain.IfyoucallGetNextFileagainWITHOUTcallingSaveorSaveToMemorythenthefileinquestionwillNOTbeuploaded.
IfyoucallSaveorSaveToMemorythentheuploadedfilewillalsohaveacorrespondingUploadedFileobjectappendedtothecontrol'sFilescollection.
Theadvantageofthismethodisthatyouarenotforcedtoretrieveallformdataatonce.Theabilitytoacceptorrejectuploadsisalsoadvantageoustothedeveloper.
SeeAlso:NextFileObject|Tutorial2:RetrievingFormDataIncrementallyUsingtheGetNextFileMethod
Example
'Note:itisassumedthataform(whichcontainsoneormorefileinputboxes)ispostingdatatothispagewithanencodingtypeof"multipart/form-data"
'createaninstanceoftheUploadcontrolSetobjUpload=Server.CreateObject("Dundas.Upload.2")
'retrievetheheaderforthefirstuploadedfileSetobjNextFile=objUpload.GetNextFile()
DoUntilobjNextFileIsNothing'loopthroughalluploadedfilesandretrievetheuploadedfileifitisanimage
IfInStr(1,objNextFile.contenttype,"Image",1)Then
objNextFile.SaveToMemory()
EndIf
'retrieveheaderfornextuploadedfileSetobjNextFile=objUpload.GetNextFile()
Loop
'destroyobjectSetUpload=Nothing
GetUniqueName(DundasUploadControl2.0)
Overview|Properties|Methods
Thismethodreturnsauniquename(aGUID).
Syntax
string=UploadObject.GetUniqueName()
Remarks
CallthismethodtoretrieveaGUID(aGloballyUniqueIdentifier).Thiscanbeusefulwhensavingfileswithuniquefilenames.
NotethatyoucanalsoutilizeuniquefilenamesbysettingtheUseUniqueNamespropertytoTRUE.IftheUseUniqueNamespropertyissettoTRUE(thedefault)thenallfileswillbesavedwithaGUIDandan"_"precedingtheoriginalfilename.
SeeAlso:UseUniqueNames
ImpersonateUser(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtoswitchfromthedefaultuseraccounttoanotheraccountwithdifferentpermissions.
Syntax
UploadObject.ImpersonateUser(UserNameAsString,PasswordAsString,[DomainAsString],[TypeAsLong=2])
TheImpersonateUsermethodsyntaxhasthefollowingparts:
Part Description
UserName TheusernameoftheWindowsaccounttouse.
Password ThepasswordoftheWindowsaccounttouse.
Domain ThedomainoftheWindowsaccounttouse.Ifnotspecifiedthedomainofthecurrentdefaultaccountisused.
Type Specifiesthetypeoflogonoperationtoperform.
Remarks
Anexceptionisthrownifthisoperationfails.Youcantrapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
Thismethodisusefulifyouneedtoperformanoperationforwhichthe
defaultuseraccount(usuallytheIUSRaccount)doesnothavetheappropriatepermissions.Forexample,youcancallImpersonateUsertouseanaccountwhichhastherightstodelete,moveorcopyfiles,andwhenthefileoperationiscompleteyoucanthencallImpersonationTerminatetorevertbacktothedefaultaccount.
IMPORTANT:Ifyourvirtualwebsitedirectoryhas"Runinseparatememoryspace"checkedtheninordertouseImpersonateUseryouMUSTgivethedefaultaccount"Partoftheoperatingsystem"priviledges.Seebelowforinstructionsonhowtodothis.
TheTypeargumentdetermineshowthelogonoperationistobeperformed(youcanusethedistributedincludefilenamedUploadControl.inctoincorporatenamedconstantsinyourASPsourcecode).Thepossiblevaluesforthisare:
LOGON_INTERACTIVE(2).
LOGON_NETWORK(3).
LOGON_BATCH(4).
LOGON_SERVICE(5).
FormoredetailsconcerningthelogontyperefertoyourMSDNunderthe"LogonUser"topic.
GrantingOperatingSystemPriviledgesinWindowsNT:
1. Open"StartMenu|AdministrativeTools|UserManager".
2. Thenopen"Policies|UserRights"fromthemenu,MAKINGSUREthatthe"ShowAdvancedUserRights"boxischecked.
3. Fromthedropdownlistboxselect"ActasPartoftheOperatingSystem".
4. AddthedefaultuseraccounttothelistofaccountswhichhavethispriviledgebyclickingontheADDbutton.Ifthedefaultaccountisnot
listedthenadditbyclickingon"ShowUsers"andselectingthedefaultaccountandthenclickingthe"Add"and"OK"buttons.
5. Reboot.
GrantingOperatingSystemPriviledgesinWindows2000:
1. Open"AdministrativeTools|LocalSecurityPolicy"andthendouble-clickon"LocalPolicies".
2. Open"UserRightsAssignment"andthendouble-clickon"ActasPartoftheOperatingSystem".
3. Addthedefault(i.e.IUSR)accounttothecurrentlist.IfthedefaultaccountisnotlistedfollowStep4fromabove.
SeeAlso:ImpersonationTerminate
ImpersonationTerminate(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtorevertbacktousingthedefaultuseraccount.
Syntax
UploadObject.ImpersonationTerminate()
Remarks
Anexceptionisthrowniftheoperationfails.Youcantrapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
IfyouneedtoperformanoperationforwhichthedefaultuseraccountdoesnothavepermissionthencalltheImpersonateUsermethodtoutilizeanaccountwhichhaswiderpermissionsthanthedefaultaccount(whichisusuallytheIUSRaccount).OnceyounolongerneedthesewiderpermissionscalltheImpersonationTerminatemethodtorevertbacktousingthedefaultaccount.
SeeAlso:ImpersonateUser
RegisterServer(DundasUploadControl2.0)
Overview|Properties|Methods
Usethismethodtoregister/unregistera(COM)componentattheserver.
Syntax
UploadObject.RegisterServer(PathAsString[,UnregisterAsBoolean=False])
TheRegisterServermethodsyntaxhasthefollowingpart(s):
Part Description
Path Pathnameofthecomponenttoberegistered.Useeitherarelativeorabsolutepathname,dependingonthesettingoftheUseVirtualDirproperty.
Unregister SetthisbooleantoFALSEtoregisterthecomponent(thedefault).SetittoTRUEtounregisterthecomponent.
Remarks
Thismethodwillraiseanexceptionifthespecifiedfiledoesnotexist.TomakesurethatthefileinquestionexistsyoucanusetheFileExistsmethodbeforecallingRegisterServer.
IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalidalias,andanysub-foldersneedtobeseparatedwithforwardslashes.IfyouspecifyaphysicalpathnamewhenUseVirtualDirisTRUEan
exceptionwillbethrown.
SeeAlso:FileExists
Save(UploadControlandNextFileObject)
Overview|Properties|Methods
Callthismethodtosaveuploadedfilestodiskandpopulatethecontrol'scollections.
Syntax
Object.Save(PathAsstring)
TheSavemethodsyntaxhasthefollowingparts:
Part Description
Path Astringexpressionspecifyingthefolderpathtosavetheuploadedfilesin.Useeitherarelativeorabsolutepathname,dependingonthesettingoftheUseVirtualDirproperty.
Remarks
Callthismethodtosaveuploadedfilestodisk.IftheUseUniqueNamespropertyissettoTRUE(thedefault)thenallfileswillbesavedwithaGUIDandan"_"precedingtheoriginalfilename.Forexample,ifthenameofanuploadedfileis"index.txt"thenthecorrespondingfilesavedtodiskwillbe"SomeGUID_index.txt".Wehighlyrecommendthatyouutilizeuniquenamesforsavedfiles.
YouMUSTEITHERCALLTHISMETHOD,theSaveToMemorymethodortheGetNextFilemethodbeforeattemptingtouseeithertheFormorFilescollections.NotonlydothesemethodsretrieveuploadedfilesbuttheyalsopopulatetheUploadcontrol'scollections.Atrappableerrorwilloccurifyoutrytoutilizethesecollectionsbeforecallingeitherofthesemethods.
Callingasavemethodwillthrowanexceptioniftheuploadeddata
exceedsthemaximumallowablelimit,assetbytheMaxUploadSizeproperty.Asaresultnofileswillbesavedandthecontrol'scollectionswillnotbepopulated.
Anexceptionwillalsobethrownifthespecifiedpathdoesnotexist.
IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalidalias,andanysub-foldersneedtobeseparatedwithforwardslashes.IfyouspecifyaphysicalpathnamewhenUseVirtualDirisTRUEanexceptionwillbethrown.
NOTE:IfyoudonotwanttoautomaticallyretrievealldownloadedfilesandformdatathenalternativelyyoucanusetheGetNextFilemethodtoretrievetheformdata.
SeeAlso:UseUniqueNames|MaxUploadSize|SaveToMemory|GetNextFile|Tutorial1:UploadingMultipleFilesandUsingtheFormandFilesCollections|Tutorial2:RetrievingFormDataIncrementallyUsingtheGetNextFileMethod
SaveToMemory(UploadControlandNextFileObject)
CallthismethodtosaveuploadedfilestomemoryandpopulateboththeFilesandFormcollections.
Syntax
Object.SaveToMemory()
Remarks
YouMUSTEITHERCALLTHISMETHODortheSavemethodbeforeattemptingtouseeithertheFormorFilescollections.NotonlydothesemethodsretrieveuploadedfilesbuttheyalsopopulatetheUploadcontrol'scollections.Atrappableerrorwilloccurifyoutrytoutilizethesecollectionsbeforecallingoneofthesemethods.
Iffilesaresavedtomemorythencallinganyofthefollowingmethodswillresultinanexceptionbeingthrownsincetherewillbenofilessavedtodisk:FileCopy,FileDelete,FileMove,SetAttributes,GetAttributesandtheSetOwnermethodsoftheUploadedFileobject.
CallingtheSaveToMemorymethodwillalsothrowanexceptioniftheuploadeddataexceedsthemaximumallowablelimit,assetbytheMaxUploadSizeproperty.Asaresultnoformdatawillberetrieved.
Notethatcallingthecontrol'sSaveToMemorymethodpopulatestheFilesandFormcollectionswithonemethodcall,whilecallingtheSaveToMemorymethodofaNextFileobjectpopulatestheFormandFilescollectionsincrementally.
SeeAlso:Save|Tutorial1:UploadingMultipleFilesandUsingtheFormandFilesCollections|Tutorial2:RetrievingFormDataIncrementallyUsingtheGetNextFileMethod
SendBinary(DundasUploadControl2.0)
Overview|Properties|Methods
Callthismethodtodownloadfilesfromtheserver.
Syntax
UploadObject.SendBinary(PathAsString[,ContentTypeAsString="default"])
TheSendBinarymethodsyntaxhasthefollowingpart(s):
Part Description
Path Thepathnameofthefiletobedownloaded.Useeitherarelativeorabsolutepathname,dependingonthesettingoftheUseVirtualDirproperty.
ContentType Thetypeoffiletobedownloaded.
Remarks
Anexceptionisthrowniftheoperationfails.Trapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
IfUseVirtualDirissettoTRUEthenthespecifiedpathneedstoberelative.Itshouldstartwithaforwardslashandbefollowedbyavalidalias,andanysub-foldersneedtobeseparatedwithforwardslashes.IfyouspecifyaphysicalpathnamewhenUseVirtualDirisTRUEanexceptionwillbethrown.
IfyouspecifyanemptycontenttypetheresultingResponse.ContentTypeheaderisnotset.Ifitissettothedefault(whichis"default")thentheresultingcontenttypeheaderwillbesettoavaluewhichcorrespondstotheassociatedfileextension.
PleasenotethatitismuchmoreefficienttousetheSaveToMemorymethodwhencallingSendBinary.
Thedatasentbacktotheclientwillconstitutethecontentsoftheresultingwebpagedisplayedintheclient'sbrowser.
FilesCollection(DundasUploadControl2.0)
Overview|Properties|Methods
TheFilescollectionstoresUploadedFileobjectswhicharearesultoffilesuploadedtotheserver.
Remarks
TheFilescollectionstoresone(1)UploadedFileobjectforeveryfileuploadedtotheserverasaresultoffileinputinboxes(e.g.<inputtype="file"name="File1>)inaForm.TheFormmustPOSTtotheASPpagewhichusestheFilescollection,andtheENCTYPEoftheformmustbe"Multipart/Form-Data".
Thiscollectioniszero-based.
YouMUSTCALLoneofthefollowingmethodstopopulatetheFilescollection:theSavemethodofeithertheUploadobjectoraNextFileobject;ortheSaveToMemorymethodofeitheranUploadobjectoraNextFileobject.PleasenotethatusingtheNextFileobject'sSaveorSaveToMemorymethodswillpopulatetheFilescollectiononefileatatime,unliketheUploadcontrol'ssavemethodswhichpopulatestheFilescollectionwithonemethodcall.
Loopthroughthiscollectionwhenyouwanttoutilizetheuploadedfiles(e.g.asAttachmentobjectsfortheMailercontrol).YoucanusetheCountpropertyofthecollectionastheupperloopdelimiterwithastandardForloop,oralternativelyyoucaniteratethroughthecollectionbyusingaForEachloop.
SeeAlso:UploadedFileObject|NextFileObject|Tutorial1:UploadingMultipleFilesandUsingtheFormandFilesCollections|Tutorial3:ADOSupportandSavingaFileasaBLOB
Example
Assumptions
InstancesoftheUploadandMailercontrolshavebeencreated.
AnotherhtmlorASPpagehasPOSTEDfilestothepagewhichcontainsthiscodeviafileinputboxesinaform,withanENCTYPEof"Multipart/Form-Data".
Theuploadedfileswillbeusedasemailattachments.
'wewillloopthroughallUploadedFileobjectsandusethem'asemailattachments.
ForEachIteminobjUpload.Files'notethatweareusingtheOriginalPathpropertyoftheUploadedFileobjectsasthe'ContentNamepropertyoftheAttachmentobjects(ContentNamewillbethefilename'displayedintheclient'semailsoftware).Ifwedonotdothisthenthefilename'thattheuploadedfilewassavedunderwillbeusedinstead(alluploadedfiles'areautomaticallysavedwithaGUIDprecedingtheoriginalfilename).objMailer.Attachments.AddItem.Path,Item.OriginalPathNext
FormCollection(DundasUploadControl2.0)
Overview|Properties|Methods
ConsistsofFormItemobjectswhichstoreuploadedformdata.
Remarks
TousetheUploadcontrolthehtmlformwhichPOSTSthedatamusthaveanENCTYPEof"Multipart/Form-Data".
TheFormcollectionisusedtoretrieveformdata.YouMUSTusethiscollectionwhenexaminingformelementsandtheirvaluessinceaformwithanENCTYPEof"Multipart/Form-Data"POSTSthedatainsuchawaythatyoucannolongeruseASP'sRequest.Formobjecttoretrievethedata.
Thiscollectioniszero-based.
IfaformelementwasnotpopulatedbytheuserthentherewillbenocorrespondingFormItemobjectinthecontrol'sFormcollection(e.g.ifyouloopthroughtheFormcollectionwithaFor...EachlooptherewillbenoFormItemobjectfortheformelementsleftemptybytheuser).Ifyouretrievethevalueofaparticularformelementwhichwasleftemptybytheuserthereturnwillbe"Empty".Youcantesttoseeiftheuserleftaformelementblank,orempty,byusingVBScript'sIsEmptymethod.
TousetheFormcollectionyouMUSTCALLoneofthefollowingmethods:theSavemethodofeithertheUploadcontroloraNextFileobject;ortheSaveToMemorymethodofeithertheUploadcontroloraNextFileobject.PleasenotethatusingtheGetNextFilemethod(whichreturnsaNextFileobject)willpopulatetheFormcollectionwithallformdatauptothefileinputboxinquestion.TheUploadobject'ssavemethods,however,populatestheFormcollectionwithALLPOSTEDformdatainonemethodcall.
Toretrieveformitemsyoucanspecifythenameoftheformelementvia
itsstringkey(e.g.strVariable=objUpload.Form("txtSomeTextBox").Alternativelyyoucanretrieveanelement'svaluebyspecifyingtheappropriatenumericalindex(e.g.strVariable=objupload.Form(0)).
Youcanretrievemultipleselectionsforoneformelement(e.g.alistbox)byusingtheCountpropertyoftheFormItemobject(thiswillhavethetotalnumberofitemsselectedfortheformelement)alongwiththeValuemethod.UseaForloopwiththeCountpropertyoftheFormItemobjectastheupperloopdelimiterandcalltheValuemethodforeachitem.Forexample,toretrieveallselectedelementsforamulti-itemlistbox(named"ListBox")youcouldusethefollowingsyntax:
Fori=0ToobjUpload.Form("ListBox").Count-1
Response.WriteobjUpload.Form("ListBox").Value(i)
NextNote:alternativelyyoucanalsouseaFor...Eachlooptoaccessmultiple-itemformelementvalues.
ToiteratethroughallformelementsyoucanuseastandardForloopwiththeupperdelimitersettoonelessthantheFormcollection'sCountproperty.YoucanalsoloopthroughallformelementsbyusingaForEachloop(e.g.ForEachIteminobjUpload.Form).Thenaccesseachformelementusingthefollowingsyntax:strSomeString=objUpload.Form(Item).
TheFormcollectionsupportsthefollowingpropertiesandmethods:
Properties Description
Count Read-onlypropertywhichstoresthenumberofFormItemobjectsinthecollection.
Methods Description
Item Usethismethodtoretrieveitemsfromthecollection.Thedefaultmemberofthecollection.
TheItemmethodisthedefaultmemberofthecollectionsoitdoesnothavetobeusedexplicitly.Forexample,"SetobjFormItem=objUpload.Form(0).Item"accomplishesthesamethingas"SetobjFormItem=objUpload.Form(0)".
SeeAlso:FormItemObject|HowtoUsetheDundasUploadControl|Tutorial1:UploadingMultipleFilesandUsingtheFormandFilesCollections
CountProperty(AllDundasUploadCollections)
Usethisread-onlypropertytodeterminethenumberofelementscurrentlystoredinanyDundasUploadcollection.
Syntax
AnyUploadCollection.Count
Remarks
UsethispropertytofindouthowmanyelementsarecurrentlybeingstoredinanyDundasUploadcollection.Thisisusefulfordeterminingtheupperloopdelimiterwheniteratingthroughallofacollection'sitems.NotethatyoucanalsoiteratethroughanyDundasUploadcollectionwithFor...Eachloops.
SeeAlso:Item
Item(AllDundasUploadCollections)
CallthismethodtoretrieveanelementfromanyDundasUploadcollection.Thisisthedefaultmemberofallcollections.
Syntax
AnyMailerCollection.Item(Index)
TheItemmethodsyntaxhasthefollowingparts:
Part Description
Index Thisargumentcanbeeitheranumber(integerorlongdatatype)orastringkey.AlloftheDundasUploadcollectionsarezero(0)based.
Remarks
IftheIndexargumentisspecifiedasanumberthentheitemisretrievedviatheindexofthecollection(zero-based).Forexample,toretrievethefirstelementintheFilescollectionyoucouldusethefollowingstatement:SetobjUploadedFile=Files.Item(0).Ifastringisspecifiedthentheelementisretrievedviaitskey.Foralistingofcollectionkeysrefertothefollowing:
FilesCollectionstringkey=TagNamepropertyoftheUploadedFileobject.
FormCollectionstringkey=TagNamepropertyoftheFormItemobject.
Thismethodisthedefaultcollectionmethodsoyoudonothavetoexplicitlydeclareit.Forexample,toretrievethefirstUploadedFileobjectintheFilescollectionyoucouldusethefollowing:SetobjUploadedFile=objUpload.Files(0).
Note:ifyouspecifyanindexwhichisoutofrangethenanexceptionwillbethrown.
SeeAlso:CountProperty
UploadedFileObject(DundasUploadControl2.0)
ComprisestheFilescollection,andstoresdataforoneuploadedfile.
Remarks
TheUploadedFileobjectisusedtostoreinformationanddataaboutanuploadedfile,andeachobjectcorrespondstoafileuploadedviaanhtmlform.
Youmustfirstcallthecontrol'sSaveorSaveToMemorymethodbeforeattemptingtousetheFilescollection.Seethesamplecodebelowforanillustrationofthis.
IfyoucalltheSaveToMemorymethodthenthePathpropertywillbeazero-lengthstring.
Example
'thissamplecodeillustrateshowtopopulatetheFilescollection'withUploadedFileobjects
'methodfailuresusuallythrowanexceptionOnErrorResumeNext
'createaninstanceoftheUploadControlSetobjUpload=Server.CreateObject("Dundas.Upload.2")'wewillexaminetheErrobjecttoseeifanerroroccurred,ifsowewill'redirectusertoanerrorpageIfErr.Number<>0ThenResponse.Redirect"Error.asp?Error="&Err.DescriptionEndIf
'calltheSaveToMemorymethodofthecontroltopopulatetheFilescollectionfirstobjUpload.SaveToMemory
'loopthroughalluploadedfiles,andoutputtheirsizeinbytes
ForEachobjUploadedFileinobjUpload.FilesResponse.Write("Size:"&objUploadedFile.Size&"<br>")Next
'destroyUploadobjectSetobjUpload=Nothing
UploadedFileObjectProperties
Path Read-onlypropertywhichstorestheuploadedfile'slocalpathattheserver.
OriginalPath Thisread-onlypropertystorestheoriginalpathname(attheclient)oftheuploadedfile.
Size Read-onlypropertywhichstorestheuploadedfile'ssizeinbytes.
TagName Read-onlypropertywhichstoresthenameoftheform'sfileinputboxfromwhichtheuploadedfileoriginated.
ContentType Read-onlypropertywhichstorestheuploadedfile'scontenttype.
Binary Read-onlypropertywhichstorestheuploadedfile'sdataasasafe-array-of-bytes.UsefulforsavinguploadedimagefilesintoadatabaseBLOB.
Binary(UploadedFileObject)
Overview
Read-onlypropertywhichstorestheuploadedfile'sdataasasafe-array-of-bytes.
Syntax
UploadObject.Binary=[variant]
TheBinarypropertysyntaxhasthefollowingparts:
Part Description
variant Thefile'sdataasasafe-array-of-bytes.
Remarks
TousetheFilescollectionyoumustfirstcalleithertheSaveorSaveToMemorymethodsofeithertheUploadcontroloraNextFileobject.
YoucansaveuploadedbinaryfilestoaBLOB(e.g.aSQLServer"Image"column)byusinganADOrecordsetwithaDSNlessconnection.NotethatyoucannotutilizeasystemDSNtoopenthedatabase.
SeeAlso:Tutorial3:ADOSupportandSavingaFileasaBLOB
ContentType(UploadedFileandNextFileObjects)
Overview
Read-onlypropertywhichstorestheuploadedfile'scontenttype.
Syntax
[string]=Object.ContentType
TheContentTypepropertysyntaxhasthefollowingparts:
Part Description
string Thevalueofthecontenttypeheader.
Remarks
TousetheFilescollection(whichstoresUploadedFileobjects)youmustfirstcalleithertheSaveorSaveToMemorymethods.
ToworkwithaNextFileobjectyoumustfirstcalltheGetNextFilemethod.
Theformatofthecontenttypeisasfollows:"Type/Sub-Type"(e.g."image/bmp").
TodeterminewhattypeoffilehasbeenuploadedyoucanuseVBScript'sInStrmethodwiththispropertyasthestringtobesearched.Forexample,toseeiftheuploadedfileisanimageyoucouldusethislineofcode:InStr(1,objUploadedFile.ContentType,"image",1).
OriginalPath(UploadedFileandNextFileObjects)
Overview
Thisread-onlypropertystorestheoriginalpathname(attheclient)oftheuploadedfile.
Syntax
[string]=Object.OriginalPath
TheOriginalPathpropertysyntaxhasthefollowingparts:
Part Description
string Thefullpathname(attheclient)oftheuploadedfile.
Remarks
TousetheFilescollection(whichstoresUploadedFileobjects)youmustfirstcalleithertheSaveorSaveToMemorymethods.
ToworkwithaNextFileobjectyoumustfirstcalltheGetNextFilemethod.
Thispropertyisusefulifyouwanttosavefileswhichhavebeenuploadedtomemorytodiskwiththeiroriginalfilenames(i.e.filenameattheclient).ForsamplesourcecodedemonstratingthisseetheSaveAstopic.
SeeAlso:Path
Path(UploadedFileObject)
Overview
Read-onlypropertywhichstorestheuploadedfile'slocalpathattheserver.
Syntax
[string]=Object.Path
ThePathpropertysyntaxhasthefollowingparts:
Part Description
string Thephysicallocationoftheuploadedfileattheserver.
Remarks
TousetheFilescollection(whichstoresUploadedFileobjects)youmustfirstcalleithertheSaveorSaveToMemorymethods.IfyouusetheSaveToMemorymethodthenthispropertywillbeazero-lengthstring.
ThePathpropertyreturnsthephysicalpathoftheuploadedfileattheserver,eveniftheUseVirtualDirpropertyhasbeensettoTRUE.
Thispropertyisusefulifyouwanttocopy/moveuploadedfilesusingthefilenamestheywereoriginallysavedtodiskwith.ForsamplesourcecodedemonstratingthisseetheCopytopic.
SeeAlso:OriginalPath
Size(UploadedFileObject)
Overview
Read-onlypropertywhichstorestheuploadedfile'ssizeinbytes.
Syntax
[long]=Object.Size
TheSizepropertysyntaxhasthefollowingparts:
Part Description
long Thesizeoftheuploadedfileinbytes.
Remarks
TousetheFilescollection(whichstoresUploadedFileobjects)youmustfirstcalleithertheSaveorSaveToMemorymethods.
IfyouwanttosettheallowablesizeofafiletobeuploadedusetheMaxFileSizeproperty.
TagName(UploadedFile,NextFileandFormItemObjects)
Overview|Properties|Methods
Read-onlypropertywhichstoresthenameoftheform'sfileinputboxfromwhichtheuploadedfileoriginated.
Syntax
[string]=Object.TagName
TheTagNamepropertysyntaxhasthefollowingparts:
Part Description
string Thenameoftheform'sfileinputboxfromwhichtheuploadedfileoriginated.
Remarks
TousetheFilescollection(whichstoresUploadedFileobjects)youmustfirstcalleithertheSaveorSaveToMemorymethods.TouseaNextFileobjectyoumustfirstcalltheGetNextFilemethod.
Thispropertyisextremelyusefulifyouwantuserstouploadaparticularfiletypeforaspecificfileinputbox.Examinetheuploadedfile'scontenttype,andifthecontenttypeforaparticularfileinputboxisnotcorrectyoucantakeactionaccordingly.ThisisespeciallyusefulifyouareretrievinguploadedfilesoneatatimeviatheGetNextFilemethod(usingNextFileobjects)sincethismethodgivesyoutheoptionofnotallowingtheuploadofafiletooccur(onlyheadersareretrievedwiththeGetNextFilemethod).
Refertothesourcecodebelowforfurtherillustrationonhowtoensurethatafileisacertaintypeforagivenfileinputbox.
SeeAlso:ContentType
Example
'thissamplecodewillassumethereafileinputboxinsideaPOSTform'boxis"Audio",andwewillperformtypecheckingtomakesurethat'theuseractuallyuploadedavalidaudiofiletotheserverfromthisinputbox
'createaninstanceofthecontrolobjUpload=Server.CreateObject("Dundas.Upload.2")
'nowletsloopthroughtheuploadedfilesForEachIteminobjUpload.Files'wewillchecktoseewhichfileinputelementisresponsiblefortheuploadedfileIf(Item.TagName="Audio")Then'wenowknowthefilecamefromtheAudiofileinputbox,butletsmakesure'thattheuseractuallyuploadedsomesortofaudiofileIfInStr(1,Item.ContentType,"audio")Then'thefileisactuallyanaudiotypeResponse.Write"Theuploadedfileisavalidaudiofile."EndIfEndIfNext
'releaseresourcesSetobjUpload=Nothing
UploadedFileObjectMethods
AllowAccess Addsanallowanceaccesscontrolentityforafilewhichhasbeensavedtodisk.
Copy Callthismethodtocopyfileswhichhavebeensavedtodisktoaspecifieddestinationontheserver.
Delete Callthismethodtodeleteuploadedfileswhichhavebeensavedtodisk.
DenyAccess Callthismethodtoaddadenialcontrolentityforafilesavedtodisk.
GetAttributes Callthismethodtoretrievetheattributesofanuploadedfilewhichhasbeensavedtodisk.
Move Callthismethodtomovefileswhichhavebeensavedtodisktoaspecifieddestinationontheserver.
RevokeAccess Callthismethodtoremoveanallowanceaccesscontrolentityforafilewhichhasbeensavedtodisk.
SaveAs Callthismethodtosaveanuploadedfileinmemorytodisk.
SetAttributes Callthismethodtochangetheattributesofafilewhichhasbeensavedtodisk.
SetOwner Callthismethodtosetanownertoafilewhichhasbeensavedtodisk.
AllowAccess(UploadedFileObject)
Addsanallowanceaccesscontrolentityforafilewhichhasbeensavedtodisk.
Syntax
UploadedFileObject.AllowAccess(AccountAsString,FlagsAsLong)
TheAllowAccessmethodsyntaxhasthefollowingparts:
Part Description
Account ThenameofavalidWindowsaccount.Youcanoptionallyprecedetheaccountnamewiththedomainnameandabackslash.
Flags Alongwhichdeterminesthetypeofaccesstobegranted.
Remarks
Callthismethodtosettheaccessrightsforanuploadedfilewhichhasbeensavedtodisk.ThismethodisnotapplicableiftheSaveToMemorymethodhasbeenusedinsteadoftheSavemethod,sincetherewillnotbeacopyoftheuploadedfileondisk.
Tousenamedconstantsuseaserver-sideincludefortheDSUpload.incfilewhichisdistributedwiththeUploadControlinstallation.
TheAccountargumentusesthefollowingsyntax:"[Domain\]Username".
TheFlagsargumentcanhaveanyofthefollowingvaluesoranylogicalcombinationofthefollowingvalues:
Description Value
GenericAccessRights
GENERIC_ALL &H10000000
GENERIC_EXECUTE &H20000000
GENERIC_WRITE &H40000000
GENERIC_READ &H80000000
StandardAccessRights
DELETE &H00010000
READ_CONTROL &H00020000
WRITE_DAC &H00040000
WRITE_OWNER &H00008000
WRITE_SYNCHRONIZE &H00010000
SpecificAccessRightsforfiles
FILE_GENERIC_READ &H120089
FILE_GENERIC_WRITE &H120116
FILE_GENERIC_EXECUTE &H1200A0
FILE_READ_DATA &H0001
FILE_WRITE_DATA &H0002
FILE_APPEND_DATA &H0004
FILE_READ_EA &H0008
FILE_WRITE_EA &H0010
FILE_EXECUTE &H0020
FILE_READ_ATTRIBUTES &H0080
FILE_WRITE_ATTRIBUTES &H0100
FILE_ALL_ACCESS &H001f03ff
SeeAlso:DenyAccess|RevokeAccess
Copy(UploadedFileObject)
Callthismethodtocopyfileswhichhavebeensavedtodisktoaspecifieddestinationontheserver.
Syntax
UploadedFileObject.Copy(DestinationAsString[,OverwriteAsBool=FALSE])
TheCopymethodsyntaxhasthefollowingparts:
Part Description
Destination Thefullpathnameofthedestination(includingthefilename).
Overwrite IfthisisTRUEthenanexistingfilewiththesamefilenamewillbeoverwritten.DefaultstoFALSE
Remarks
Anexceptionisthrowniftheoperationfails.Trapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
AnexceptionwillbethrownifyouattempttocopyafileiftheFilescollectionwaspopulatedusingtheSaveToMemorymethod.Iffilesaresavedusingavirtualpath(i.e.theUseVirtualDirpropertyhasbeensettoTRUE)thenavirtualpathshouldalsobeusedfortheDestinationargument.
Whencallingthismethodyoumustspecifythedirectoryandfilenameforthedesireddestination(e.g."e:\temp\myfile.txt").TocopythefiletoadirectoryusingthesamenamethatthefilewassavedtodiskwithyoucanusetheUploadcontrol'sGetFileNamemethod,usingtheUploadedFileobject'sPathpropertyastheargument.Seethesamplesourcecodebelowforanillustrationofthis.
SeeAlso:Move|Delete|Save
Example
'wewillassumethattheFilescollectionhasbeenpopulatedusingtheUpload'control'sSavemethod(e.g.uploadedfileshavebeensavedtodisk).''thissamplecodecopiesthefilessavedtodisktoadirectorynamed"temp",'usingthefilenamesthatthefilesweresavedtodiskwith.
'createinstanceofcontrolSetobjUpload=Server.CreateObject("Dundas.Upload.2")
'populatecollectionsandretrievealluploadedformdata(including'uploadedfiles)objUpload.Save"c:\SomeDir"
'loopthroughalluploadedfilesandcopyeachfiletothe"temp"'directory,usingthesamefilenamesthatthefilesweresaved'todiskwith.ForEachobjUploadedFileinobjUpload.FilesobjUploadedFile.Copy"c:\temp\"&objUpload.GetFileName(objUploadedFile.Path)Next
'releaseresourcesSetobjUpload=Nothing
Delete(UploadedFileObject)
Callthismethodtodeleteuploadedfileswhichhavebeensavedtodisk.
Syntax
UploadedFileObject.Delete
Remarks
Anexceptionisthrowniftheoperationfails.Trapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
AnexceptionwillbethrownifyouattempttodeleteafileiftheFilescollectionhasbeenpopulatedbycallingSaveToMemoryinsteadoftheSavemethod.
SeeAlso:Move|Copy|Save
DenyAccess(UploadedFileObject)
Callthismethodtoaddadenialcontrolentityforafilesavedtodisk.
Syntax
UploadedFileObject.DenyAccess(AccountAsString,FlagsAsLong)
TheDenyAccessmethodsyntaxhasthefollowingparts:
Part Description
Account AvalidWindowsaccountname.Youcanoptionallyprecedetheaccountnamewiththedomainnameandabackslash.
Flags Alongwhichdeterminesthetypeofaccesstobedenied.
Remarks
ThismethodisnotapplicableiftheSaveToMemorymethodhasbeenusedinsteadoftheSavemethod,sincetherewillnotbeacopyoftheuploadedfileondisk.
Tousenamedconstantsuseaserver-sideincludefortheDSUpload.incfilewhichisdistributedwiththeUploadControlinstallation.
TheAccountargumentusesthefollowingsyntax:"[Domain\]Username".
TheFlagsargumentcanhaveanyofthefollowingvaluesoranylogicalcombinationofthefollowingvalues:
Description Value
GenericAccessRights
GENERIC_ALL &H10000000
GENERIC_EXECUTE &H20000000
GENERIC_WRITE &H40000000
GENERIC_READ &H80000000
StandardAccessRights
DELETE &H00010000
READ_CONTROL &H00020000
WRITE_DAC &H00040000
WRITE_OWNER &H00008000
WRITE_SYNCHRONIZE &H00010000
SpecificAccessRightsforfiles
FILE_GENERIC_READ &H120089
FILE_GENERIC_WRITE &H120116
FILE_GENERIC_EXECUTE &H1200A0
FILE_READ_DATA &H0001
FILE_WRITE_DATA &H0002
FILE_APPEND_DATA &H0004
FILE_READ_EA &H0008
FILE_WRITE_EA &H0010
FILE_EXECUTE &H0020
FILE_READ_ATTRIBUTES &H0080
FILE_WRITE_ATTRIBUTES &H0100
FILE_ALL_ACCESS &H001f03ff
SeeAlso:AllowAccess|RevokeAccess
GetAttributes(UploadedFileObject)
Callthismethodtoretrievetheattributesofanuploadedfilewhichhasbeensavedtodisk.
Syntax
long=UploadedFileObject.GetAttributes()
Remarks
Thismethodreturnsthefile'sattributesasalong.
PleasenotethatcallingthismethodwillresultinanexceptionbeingthrownifthefilehasbeensavedtomemoryusingtheSaveToMemorymethod.
Theattributesargumentcanhaveanyofthefollowingvaluesoranylogicalcombinationofthefollowingvalues:
Value Description.
0 Noattributesareset.
1 Read-onlyfile.
2 Hiddenfile.
4 Systemfile.
8 Diskdrivevolumelabel.
16 Folderordirectory.Attributeisread-only.
32 Filehaschangedsincelastbackup(archive).Attributeisread/write.
64 Linkorshortcut.Attributeisread-only.
128 Compressedfile.Attributeisread-only.
Note:Callingthismethodwillresultinanexceptionbeingthrownifthefilewassavedtomemory.
SeeAlso:SetAttributes
Move(UploadedFileObject)
Callthismethodtomovefileswhichhavebeensavedtodisktoaspecifieddestinationontheserver.
Syntax
UploadedFileObject.Move(PathAsString[,FailIfExsistsAsBoolean=True])
TheMovemethodsyntaxhasthefollowingpart(s):
Part Description
Path Thefullpathnameofthedestination(includingthefilename).Ifyousaveduploadedfilestodiskusingavirtualdirectorythenthisargumentmustalsouseavirtualdirectory.
FailIfExsists IfTRUEthenanexceptionwillbethrownifthefilealreadyexistsatthedestinationfolder.DefaultstoTRUE.
Remarks
Anexceptionisthrowniftheoperationfails.Trapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
AnexceptionwillalsobethrowniftheFilescollectionwaspopulatedbyusingtheSaveToMemorymethod.
YoumustuseavirtualdirectoryforthePathargumentifavirtualdirectorywasusedintheSavemethodcall(i.e.theUseVirtualDir
propertywassettoTRUEbeforecallingtheSavemethod).ThesyntaxforthePathargumentwouldthenbe:"/VirtualDir/AnyOtherDirs/FileName".
SeeAlso:Copy|Delete|Save
RevokeAccess(UploadedFileObject)
Callthismethodtoremoveanallowanceaccesscontrolentityforafilewhichhasbeensavedtodisk.
Syntax
UploadedFileObject.RevokeAccess(AccountAsString)
TheRevokeAccessmethodsyntaxhasthefollowingpart(s):
Part Description
Account ThenameofavalidWindowsaccount.Youcanoptionallyprecedetheaccountnamewiththedomainnameandabackslash.
Remarks
Thismethodwillthrowanexceptionifaninvalidaccountnamehasbeenspecified.
TheAccountargumentusesthefollowingsyntax:"[Domain\]Username".
SeeAlso:DenyAccess|AllowAccess
SaveAs(UploadedFileObject)
Callthismethodtosaveanuploadedfileinmemorytodisk.
Syntax
UploadedFileObject.SaveAs(PathAsString)
TheSaveAsmethodsyntaxhasthefollowingpart(s):
Part Description
Path Thefullpathname(i.e.pathandfilename)ofthefile'sdestination.IfUseVirtualDirhasbeensettoTRUEthenthisargumentmustalsouseavirtualdirectory.
Remarks
ToutilizethismethodthefilemusthavebeensavedtomemoryusingtheSaveToMemorymethod.Anexceptionwillbethrownifthefileinquestionwasnotsavedtomemory.Anexceptionwillalsoberaisedifyoucallthismethodtwiceforthesamefile.
IfyouhavesettheUseVirtualDirpropertytoTRUEthenthePathargumentmustalsouseavirtualdirectory.ThesyntaxforthePathargumentwouldthenbe:"/VirtualDir/AnyOtherDirs/FileName".
Whencallingthismethodyoumustspecifythedirectoryandfilenameforthedesireddestination(e.g."e:\temp\myfile.txt").Tosavethefiletoadirectoryusingtheoriginalfilename(i.e.thefilenameattheclient)youcanusetheUploadcontrol'sGetFileNamemethod,usingtheUploadedFileobject'sOriginalPathpropertyastheargument.Seethesamplesourcecodebelowforanillustrationofthis.
SeeAlso:Save|SaveToMemory
Example
'wewillassumethattheFilescollectionhasbeenpopulatedusingtheUpload'control'sSaveToMemorymethod.''thissamplecodesavesthefilesinmemorytoadirectorynamed"temp",'usingthefile'soriginalnames(attheclient)
'createinstanceofcontrolSetobjUpload=Server.CreateObject("Dundas.Upload.2")
'populatecollectionsandretrievealluploadedformdata(including'uploadedfiles)objUpload.SaveToMemory
'loopthroughalluploadedfilesandsaveeachfiletothe"temp"'directory,usingtheiroriginalfilenamesForEachobjUploadedFileinobjUpload.FilesobjUploadedFile.SaveAs"c:\temp\"&objUpload.GetFileName(objUploadedFile.OriginalPath)Next
'releaseresourcesSetobjUpload=Nothing
SetAttributes(UploadedFileObject)
Callthismethodtochangetheattributesofafilewhichhasbeensavedtodisk.
Syntax
UploadedFileObject.SetAttributes(AttributesAsLong)
TheSetAttributesmethodsyntaxhasthefollowingpart(s):
Part Description
Attributes Alongwhichdeterminesthefileattributestobeset.
Remarks
Callingthismethodwillresultinanexceptionbeingthrownifthefilewassavedtomemory.
Theattributesargumentcanhaveanyofthefollowingvaluesoranylogicalcombinationofthefollowingvalues:
Value Description.
0 Noattributesareset.
1 Read-onlyfile.
2 Hiddenfile.
4 Systemfile.
8 Diskdrivevolumelabel.
16 Folderordirectory.Attributeisread-only.
32 Filehaschangedsincelastbackup(archive).Attributeisread/write.
64 Linkorshortcut.Attributeisread-only.
128 Compressedfile.Attributeisread-only.
SeeAlso:GetAttributes
SetOwner(UploadedFileObject)
Callthismethodtosetanownertoafilewhichhasbeensavedtodisk.
Syntax
UploadedFileObject.SetOwner(AccountAsString)
TheSetOwnermethodsyntaxhasthefollowingpart(s):
Part Description
Account ThenameofavalidWindowsaccount.Youcanoptionallyprecedetheaccountnamewiththedomainnameandabackslash.
Remarks
Anexceptionisthrowniftheoperationfails.Trapforsuccess/failurebyexaminingVBScript'sErrobjectimmediatelyaftercallingthismethod(theNumberpropertyoftheErrobjectwillbeanon-zerovalueifitfailed).MAKESUREthatyouhaveenabledinlineerrortrappingbyusinganOnErrorResumeNextstatementatthebeginningoftheASPpage.
Note:Permissionissuesshouldbeconsideredwhenusingthismethodsinceanexceptionwillbethrowniftheuserdoesnothavetherighttosettheowner.UsetheImpersonateUsermethodtotemporarilyassumeanotherWindowsaccountwhichhasthepermissiontosetthefile'sowner.OncethisisdonecalltheImpersonationTerminatemethodtoresumeusingthedefaultaccount.
SeeAlso:ImpersonateUser|ImpersonationTerminate
FormItemObject(DundasUploadControl2.0)
ComprisestheFormcollection,andstoresinputdataforaformelement.
Remarks
TheFormItemobjectisusedtoretrievedatafromthePOSTform.
TousetheUploadcontrolthehtmlformwhichPOSTSthedatamusthaveanENCTYPEof"Multipart/Form-Data".
ToretrievedatayouMUSTFIRSTCALLeitherthecontrol'sSavemethod,theSaveToMemorymethodortheGetNextFilemethodfirstsothattheFormcollectionispopulated.OncethisisdoneyoucanretrievedataviatheFormcollection'sFormItemobjects.
Note:theSaveandSaveToMemorymethodswillretrieveALLformdatawithonemethodcall,unliketheGetNextFilemethodwhichretrievesallformdatauptothefirstpopulatedfileinputboxencountered.ToretrieveallformdatawithGetNextFilecallGetNextFileuntilthefunctionreturns"Nothing."forsamplecodedemonstratinghowtodothisseetheGetNextFiletopic.
Toretrieveformitemsyoucanspecifythenameoftheformelementviaitsstringkey(e.g.strVariable=objUpload.Form("txtSomeTextBox")).NotethatthestringkeyisactuallytheTagNamepropertyoftheFormItemobject.Alternativelyyoucanretrieveanelement'svaluebyspecifyingtheappropriatenumericalindex(e.g.strVariable=objupload.Form(0)).ToretirevethevalueyoudonothavetospecifyValue.
NOTE:Ifaformelementisleftemptybytheuserthenattemptingtoaccesstheelement'sdataviatheUploadcontrol'sFormcollectionwillresultinavalueof"Empty"beingreturned.Totestforanemptyformelementusethefollowinglineofcode:"IfIsEmpty(objUpload.Form("MyFormElement"))Then...Else...EndIf".
Toretrievemultipleselectionsforoneformelement(e.g.alistbox)usetheCountpropertyoftheFormItemobject(thiswillhavethetotalnumberofitemsselectedfortheformelement).UseaForloopwiththeCountpropertyoftheFormItemobjectastheupperloopdelimiterandcalltheValuemethodforeachitem.Forexample,toretrieveallselectedelementsforamulti-itemlistbox(named"ListBox")youcouldusethefollowingsyntax:
Fori=0ToobjUpload.Form("ListBox").Count-1
Response.WriteobjUpload.Form("ListBox").Value(i)
Next
Note:alternativelyyoucoulduseaFor...Eachlooptoaccessthesemultipleselections.TouseaFor...Eachlooputilizethefollowingsyntax:
ForEachIteminobjUpload.Form
strSomeVariable=objUpload.Form(Item)
Next
SeeAlso:FormCollection|HowtoUsetheDundasUploadControl
CountProperty(FormItemObject)
Overview
Thispropertyindicatesthenumberofdataelementsselectedforaformelementwithmultipleitems.
Syntax
FormItemObject.Count
Remarks
Thiscountpropertyisusefulifmultipledatahasbeenentered/selectedinaformitem(e.g.amultipleitemlistbox).Usethispropertytodeterminethetotalnumberofselecteddataentries.
YoucanretrievethevalueofeachdataitemusingtheValuepropertyoftheFormItemobjectinquestion.
SeeAlso:Value
Value(FormItemObject)
Overview
Usethispropertytoretrievethevalueofaformelement.
Syntax
string=FormItemObject.Value
Remarks
Thispropertyisessentialforretrievingdatafromamultiple-entryformelement(e.g.amultipleitemlistbox).ItisalsothedefaultmemberoftheFormItemobject,soitdoesnothavetobedeclaredexplicitly.
Toretrievemultipleselectedvaluesforonesingleformelementusethefollowingsyntax:string=objFormItem.[Value](Index),whereIndexisazero-basedlong.
SeeAlso:CountProperty(FormItemObject)
NextFileObject(DundasUploadControl2.0)
Containsheaderinformationforafileoriginatingfromafileinputbox.
Remarks
ANextFileobjectisreturnedfromaGetNextFilecall.
TheNextFileobjectstoresheaderinformationforafileresultingfromaform'sfileinputbox.YoucanexaminetheexposedpropertiesoftheNextFileobjectanddecidewhetherornotyouwanttoallowtheusertouploadthefile.ToallowtheuploadtooccurcalltheSaveorSaveToMemorymethodsoftheNextFileobject.TocanceltheuploadjustcalltheGetNextFilemethodagainwithoutcallingeithertheSaveorSaveToMemorymethodfirst.
ToseesamplesourcecodeillustratinghowtoloopthroughallfilestheuserwantstouploadtotheserverseetheGetNextFiletopic.
SeeAlso:GetNextFile|Tutorial2:RetrievingFormDataIncrementallyUsingtheGetNextFileMethod
Example
'thissamplecodewilldetermineifanimagefilehasbeenspecifiedbytheuser'uploadtooccur.NotethatweareassumingthataformhasPOSTEDdata'tothispage,usinganencodingtypeof"Multipart/Form-Data".
'createaninstanceoftheUploadcontrolSetobjUpload=Server.CreateObject("Dundas.Upload.2")
'callGetNextFiletoretrievetheheaderforthefilewhichtheuserwants'toupload.NotethatGetNextFilewillreturnavalueof"Nothing"if'theuserdidnotspecifyanyfilesatalltobeuploaded.Alsonotethat'GetNextFilepopulatesthecontrol'sFormcollectionwiththevaluesof'ALLformelementswhichoccurinthehtmlformONLYupuntilthefirst
'encountered,populatedfileinputbox.Ifnopopulatedfileinputbox'isfoundthenallformelementvalueswillbeinsertedintotheFormcollection.SetobjNextFile=objUpload.GetNextFile()
IfInStr(1,objNextFile.ContentType,"image")ThenobjNextFile.SaveToMemoryEndIf
'releaseresourcesSetobjUpload=Nothing
NextFileObjectProperties
Attributes Read-writepropertywhichallowsyoutoretrieveorsettheattributesofafilestoredinaNextFileobject.
ContentType Read-onlypropertywhichstoresthefile'scontenttype.
FileName Read-writepropertywhichdeterminesthefile'sfullpathname(attheserver).
OriginalPath Thisread-onlypropertystorestheoriginalpathname(attheclient)ofthefileinquestion.
TagName Read-onlypropertywhichstoresthenameoftheform'sfileinputboxfromwhichthefileoriginated.
Attributes(NextFileObject)
Overview
Thisread-writepropertyletsyouretrieveorsettheattributesofafilestoredinaNextFileobject.
Syntax
NextFileObject.Attributes=[long]
Part Description
long Alongwhichdeterminestheattributesofthefileinquestion.
Remarks
TosetthispropertymakesurethatyoucalleitherSaveorSaveToMemoryAFTERtheattributeshavebeenset.Tosetorretrieveafile'sattributesAFTERthefilehasbeensavedtodiskormemoryusetheUploadcontrol'sGetAttributesandSetAttributesmethods.
Afile'sattributescanbeanyofthefollowingvaluesoranylogicalcombinationofthefollowingvalues:
Value Description.
0 Noattributesareset.
1 Read-onlyfile.
2 Hiddenfile.
4 Systemfile.
8 Diskdrivevolumelabel.
16 Folderordirectory.Attributeisread-only.
32 Filehaschangedsincelastbackup(archive).Attributeisread/write.
64 Linkorshortcut.Attributeisread-only.
128 Compressedfile.Attributeisread-only.
SeeAlso:GetAttributes|SetAttributes
FileName(NextFileObject)
Overview
Read-writepropertywhichdeterminestheuploadedfile'sfullpathname(attheserver).
Syntax
NextFileObject.FileName=[string]
ThePathpropertysyntaxhasthefollowingparts:
Part Description
string Thefullpathnameoftheuploadedfile(attheserver).
Remarks
Iffilesaretobesavedwithuniquesfilenames(thedefault)thenthevalueofthispropertywillbe:GUID_OriginalFileName.Ifuniquesfilenamesarenotbeingusedthenthispropertywilljustconsistoftheoriginalfilename(i.e.thefilenameattheclient).
IfyouwouldliketoallowtheuploadofthefiletooccurandyouwanttospecifythenamethefileistobesavedwiththensetthispropertyBEFOREcallingtheSavemethod(SaveToMemoryisnotrelevanthere).
Important:ifyouspecifythefilenamewhichthefileistobesavedunderthenitisyourresponsibilitytomakesurethatthenameisunique(ifuniquefilenamesaredesired).UsetheGetUniqueNamemethodoftheUploadcontroltohelpyouaccomplishthis.
SeeAlso:GetUniqueName
NextFileObjectMethods
Save Uploadsandsavesthefiletodisk.
SaveToMemory Uploadsandsavesthefiletomemory.
UploadProgressComponentOverview
ComponentProperties|ComponentMethods
UsetheUploadProgresscomponentwhenyouwanttodisplayaprogressbarforanuploadoperation.
TheUploadProgressComponentisusedtoaccesstheStateServerandretrieveuploadinformationwhichcanthenbeusedtoupdateaprogressbarwindow.ItcanretrievenewprogressID's,retrievetheprogressinformationstoredintheStateServerandalsodeletestateinformationbyID.ItisalsoresponsibleforretrievinganewProgressIDwhenanuploadoperationisinitiated(accomplishedviatheGetNewProgressIDmethod).
ToretrieveuploadinformationsettheProgressIDpropertytotheuniqueProgressID,calltheGetProgressmethodandthenutilizethePercentCompleted,TotalSize,andUploadedSizeproperties.Pleasenotethatthesepropertieswillbenegativeone(-1)ifnodatahasbeenuploadedyet.
FordetailedinstructionsonhowtoimplementaprogressbarseeTutorial4:ImplementingaProgressBar.
Anyerrorswhichoccurwillresultinanexceptionbeingthrown.
SeeAlso:Overview(DundasStateServer)
UploadProgressComponentMethods
ThefollowingisalistofallmethodsoftheUploadProgressComponent:
Method Description
GetNewProgressID
ReturnsanewProgressID(obtainedfromtheStateServerComponent)whichisusedtouniquelyidentifytheuploadoperation.
GetProgress ConnectstotheStateServercomponentandcausestheTotalSize,UploadedSizeandPercentCompletedpropertiesoftheProgressBarcomponenttobere-calculated.YoumustobtainanID(viaGetNewProgressID)beforecallingthismethod.
DeleteProgress ConnectstotheStateServercomponentanddeletestheprogressstateinformationforthegivenProgressID.YoumustobtainanID(viaGetNewProgressID)beforecallingthismethod.
Pleasenotethatanyerrorswillresultinanexceptionbeingthrown.
SeeAlso:ProgressBarComponentMethods|Overview(ProgressBarComponent)
UploadProgressComponentProperties
ThefollowingisalistingofallUploadProgressComponentproperties:
Property DataType
Description
ProgressID
long
AuniqueProgressID(setbytheGetNewProgressIDmethod).
PercentCompleted long Read-only,theuploadcompletionpercentage(setbytheGetProgressmethod).Thiswillbenegativeone(-1)iftherehasbeennodatauploadedyet.
StateServer string TheIPaddressofthemachinewheretheStateServerexecutableisrunning.
StateServerPort long TheportnumbertousefortheStateServerComponent.
TotalSize long Read-only,thetotalamountofdatabeinguploaded(setbytheGetProgressmethod).Thiswillbenegativeone(-1)iftherehasbeennodatauploadedyet.
UploadedSize long Read-only,theamountofdatawhichhasbeenuploaded(setbytheGetProgressmethod).Thiswillbenegativeone(-1)iftherehasbeennodatauploadedyet.
SeeAlso:UploadProgressComponentMethods|Overview(UploadProgressComponent)
DundasStateServerOverview
TheDundasStateServer(StateServer.exe)isusedtostoreuploadprogressinformationwhichcanbestoredandretrievedusingtheUploadProgressandUploadcomponents.Thisdataisaccessiblefromanywhereonanetwork,therebyallowingtheStateServertofunctioninaweb-farmscenario.
TheStateServercanalsobesetuptorunasaservice(seebelowformoredetails).
PerformthefollowingstepstosetuptheServer:
1. MovetheStateServer.exetothemachinewhichistobeusedtostorestateinformation.
2. Youcaneitherruntheserverasanormalexecutableoralternativelyyoucanrunitasaservice.Torunitasaservicerefertothesectionimmediatelyfollowingthislistingofsteps.
3. Setthefollowingpropertiesoralternativelyusetheirdefaults:
1. Toacceptarequestfromanymachineonthenetworkdonotinsertanyentriesintothe"ValidClient'sIPAddresses"listbox.However,ifyouwanttorestrictwhichmachinesonthenetworkcanaccesstheserverthenentertheirIPaddressesintothislistbox.NotethatbyspecifyingoneormoreaddresseshereonlythoseIPaddresseswillbeallowedtoaccesstheStateServer.
2. Settheportnumberwhichtheservershouldlistenon(thisistheportnumberwhichyoumustspecifywhenconnectingtotheStateServer)orusethedefaultport(6723).
3. Thetimeoutvaluedetermineswhenarequestwillbetimed-out.Youcanacceptthedefaultof15secondsorsetthisyourself.
4. The"StateValidFor"valuedetermineshowlongstateinformationforaparticularuploadoperationwillbestored.You
canincreaseordecreasethisvalueasyouseefit.
5. The"Max.Connections"valuedetermineshowmanycomponentscanaccesstheStateServeratonetime.Thedefaultvalueis"20",butyoumaychangethisifyousodesire.
IfyouhavesetuptheStateServertorunasaservicethentherewillbenoGUItosetthesepropertieswith.YouwillneedtoruntheStateServermanually(seebelow),setupyourpropertiesandthensettheStateServerbacktorunningasaservice.
TosettheStateServeruptorunasaserviceyouwillneedtoruntheexecutablefromthecommandlinewiththefollowingswitches:
i-RuntheServerasaservicethenexttimethemachineisbooted.
u-CausestheStateServertobeuninstalledasaservice.
m-RunstheStateServermanuallyfromthecommandline.Usethisoptioniftheserverisrunningasaserviceandyouwanttosetorchangeoneormoreproperties.
Forexample,tosetuptheStateServertorunasaserviceusethefollowingsytaxfromthecommandline(usingafictitiouspath):"e:\StateServer.exe/i".
FordetailedhelponhowtoutilizetheStateServerinconjunctionwiththeUploadProgresscomponentseeTutorial4:ImplementingaProgressBar.
SeeAlso:Overview(ProgressBarComponent)
Copyright
DundasChart,UltimateToolbox,UltimateGrid,UltimateChartPro,UltimateDiagram,Hyperview,HyperHost,UltimateFastMaps!,UltimateTCP/IP,UltimateVB/NTService,Ultimate16BitCoolTools,UltimateWizardFactoryandtheirrespectivedocumentationarecopyright(c)DundasSoftwareLtd.
Microsoft,MS,MS-DOS,InternetExplorer,MicrosoftDeveloperStudio,Windows,WindowsNT,Win32,andWin32sareregisteredtrademarksofMicrosoftCorporation.
SomefilesdistributedwithUltimateToolboxand/orincorporatedwithDundasChartarecopyright(c)1991-1995,ThomasG.LaneandformpartoftheIndependentJPEGGroup'ssoftware.
SomefilesdistributedwithUltimateToolboxarecopyright(c)1995,IntelCorporation.
OpenGLisaregisteredtrademarkofSiliconGraphics,Inc.
Allotherproductsandcompanynamescitedhereinmaybethetrademarksoftheirrespectiveowners.
TechnicalSupport
WeunderstandthatwhenyouuseourdevelopmentproductsyouaremakinganinvestmentinDundasSoftware,andareputtingyourfaithinus.Thatiswhywetaketechnicalsupportveryseriously.
Alloftheseproducts,althoughfree,arenotshareware/freeware.Theyarecommercial-qualitycomponentsthatcomewithextensivedocumentation,tutorials,examples,andfully-commentedsampleapplications.Youareentitledtofreeemailsupport,wewillattempttohelpyouwithanyofyourinquiriesasquicklyaspossible.
Tofurtherhelpourusers,DundashasadedicatedOnlineDeveloper'sSite,whereyouwillfindevenmoreexamples,helpfularticles,hintsandtips,andnoticesconcerningpointreleasesandcodeupdates.
DundasSoftware'sPrioritysupportisalsoavailable,andcomeswithdirecttelephoneandemailassistance.Ourprofessionalsupportteamcangiveyoudozensoftimesavingpointersanddevelopmenttipsthatcandramaticallycompressyourdevelopmentcycle.Theycanalsoofferyousuggestionsonhowtoenhanceyourprograms,helpingtomakeagreatresultevenbetter.CalloursalesdepartmenttofindoutmoreaboutDundasPrioritysupport.
Phone:416467-5100
Fax:416422-4801
E-mail:[email protected]