You are on page 1of 82
Se eee ee ee erry ent C# Programming Interview Questions, Answers and Explanations: Programming C# Certification Review By Terry Sanchez Clark (Ce eterdew Questions (Ce Programming Interview Questions, Answers and ‘Explanations: Programming Ce Certifiation Review 1933804-55-6 ited by: Jamie Fisher Copyright© 2006 Equity Press and IT COOKBOOK lights feoered. No part ofthis publication may be reproduced stored {na retrieval sytem, or transmitted in any form or by any means (Glectonie, mechanical, photocopying, recordingor otherwise) (without ether the prior writen permassion of the publisher or 3 Tense permitting restricted copying inthe United States or abroad. “The scanning, uploading and distribution ofthis book vs the ferme o via anyother means withthe permission ofthe publisher illegal and punishable by law. Please purchase only {Euthorized electronic editions, and donot participate in or encourage pracy of copyrighted materials “The programs in this book have been included for {instructional value only. They have been tested with fate but are not guaranteed for any particalar purpose. ‘The publisher doce not offer sny warranties or representations not does it accept any Vials with respect tothe programs. ‘Trademarks: All trademarks are the property oftheir Feopective owners, Equity ress not associated with any Drodet or vender mentioned in this book. Please visit our website at ws iteookbonk com eter Qin ‘Table of Contents ‘Questions: Retrieve item from the aay list of 86 ‘Question 2: Start a'GUL app’ from a service in‘Remote Desktop ve Questions tise BiA without installing Offi Question 4: Converting “DateTime” to numeric {Question g: Data Grid and Multiple DataSet. Question to: Rnding ot what statement in ding. Question i sl emp abe Question i: Syma Question sg: Import a regi Question 4: Hide «Form when Xbution spread. Geion i ML /ovo Sekt ihe weston 1: Creating decimal with places, Geet antral ton justin 38: Previewing images (aq cna Qeestion 9; “Treenew nodes a Question 2: Netintroder (1S) “Netineader 48)" Question a: Ce with Bok Qsestion a: stuoset ne — Qteston a Spliting stringinio age cartes {Question 24: Explanation of cde = ‘Queson ag: Plugrn based development {Question 26: Co Beatbox i: {Guetion 27: Lesing SKB when Wing ‘Question 26: Create updates {Question 29: lon hows aa icon wo pete ‘Question go: Binding deta textbox format. 9 ‘Question a: Selecting rom ist box with ight moase bon Ba Question 3: Code fr testing fan “OieDHConnection is open orelose. ena Question 37: Simple base form, 57 Question 38: Casting & WMI Probie. 38 (tevin Quine tere ustions {Question a6: ADO. ' 58 {Question 40: Show result to abe. ve 9 {Question 41: Saving the properties of class. 1 ‘Question 42: Using aclass in a code... Nea Question 43: Sereen size vo 6 Question 44: Adding anew “iniNNode” to fle. 64 Question 4g: Accessinglabels on form... 65 Question 46: Type or name space error message sn 66 {Question 472 C# excepton.n. es Question 48: Version info. 70 {Question 49: Suesinet way to we multi Seeston go: Make auton the "dt 088M 72 Question gi: System. Math. ‘Question su: Passing info between forms... ‘Question 53: Sereen Updating. Question 54 Interfaces Question 55: SQLstring, Question s6: Filtering “Dataset” ora “DataTable™™ Question 57: “Flelnfe Name” ' Question 98: Combo born. ‘Question 60: TreeView visible selected Question 6x: Azraylist containing nodes... Question 62: Executing other programs rom Co NET. Svestion 65: Changing the background look of "TextBo control Cuenion 6: Replace enti Rlienion92 (Question 65: Events. “92 Question 662 DLLe 93 Question 67: Mouse co-oFds.. 34 ‘Question 6 Key check. 97 Question 69: Execute Fle from Co “99 Qcestion 70: Calling public methods... ‘eo (Question 7: 201 104 : es Console application. 308 5: Strngbullaer Mush Validate date hanging he ats path ofc report Calling Notepad. ue Dytamicallyereatinga web contro. {uation i: Opening Forms rom Forms (Question 82: Fle read m4 16 29 Question 83: Close-open Question 84: Using “foreach to enumerate objects. ‘Question 85: Connection to MS SQL... (Question 86: Hard return in asteing Question 87: ie Seemton 9: Brent handler eeton gh: Gating ait cate proper eon: Large fl Rela Wie romance probes. {Reo in pan iia lee Required Error et nee Inde eeterew eine C# Programming Interview Questions, Answers and Explanations: Programming C# Certification Review By Terry Sanchez- Clark eerie eins Question 1: Retrieve items from the array list of class have the following clas: public clase elas ¢ ‘rivate nt RoomNumber, public melas) ‘mycas(ntroomnum, sing se) t RoomNuer=resmam; User= ser , public int myRoomunber t {ae retun Room Number; } Set { ReomNumber= valu; } , public sting my User t be rewen User} ft User= value) , , Here ishow I created an array list ofthis class objects: yaa cron = new mela, Pate AnapListroomArtayList= new ArayLis(); rb vo addon Romunber, ng {his ivtaons.myRoomNunber = Room Number, ‘his ivitaonsanj User = user, Centon veins thisroomAmay Lis. Aeron) , “the above code works fine, but the method below doesn't work. T dont get ‘pe cabrece values in myarrayIn this method am tryingto {Resove the information from the array stand Lam trying to fet thelist of all rooms a particular user isin. plc in) GetRoomstsring se) ‘ iu) wsrtstaray =a singles aso, foreach laste in roomArap Lis) t Te (emmy Users) ‘ roorum ~ten.myRoomNurber ‘ersrayi = oom: ) che t einem: } fetwn writes , ‘Whats the correct syntax? As Assuming this is how you populated the tmyclass‘colletion: anes room = sew mess fete AragstroomarayLst=new Aras pubic oid drootint Room Number, sting ws) {i You sets new oom 1 invitations, but thsinstainsyRoomNunber = Room Number (eerie Quins ‘his ovintionsnyUser=uter, i yotre adding croom this romArayLis? thussoom ArrayList Add roomy , ‘his code wit poplate items for roomArayist bat al points ‘to the single instance of croom. m= Check you're adding the correct 'myelas instance to “thlszoomArsayList”? ‘You need to make new myclas' object every call of “addrooms(” to avoid collecting references ofthe same abject, rather than unique copies. bio abi Rom uber ing 1 tine ote fr brevity ‘i x8d new myclass {shroondancAdoew msateonNant ete etn Question 2: Start a‘GUI app’ from a service in Remote Desktop’ teansarny rg ACU fom ase: Tiere a sa ent Fe ee ee Neato eh ep ncn hee neers ssp it possible to start the process onthe active (remote desktop) ‘season fom the service? As Services should not run any code that interacts diretly with ‘he desktop. Yes, twill ocasionally Work. But what's happening {s ou'e getting lucky besuse tome Iteraal valves ust happen toline wp. “The desktop (Window Staton, more correctly doesnt get treated unt he wer logan, and services start when Windows Sons fa user never logs there il never bea desktop reateds ad nothing forte terice to tract with {you do need to interact with a desktop, dolike ‘SQL Server™ floes and spit the engine apart fom the Ul. The engine runs as @ Service (meaning tears when Windows stars), andthe UI (the Service monitor that sits in theclock tray) runs when the user Togs eon Question g: Use PIA without installing ‘Office’ ‘Ihave an app tht uses the ‘Excel Interop Class (XE “Excel Interop Class”) to open a worksheet (not workbook) to modify the header and import thedata into adatabass, The worksheet is dovenloaded from a third party webapp. works fine fr development because my box ha Office 2003, installed. However, when transfer te esto thetestingserver Taetascmbiy enor tatng that th Easel PLA hs broken ‘tried coping over the“exce.oe’ fe tat i directly refaced. 1 placed the file nthe ‘bin’ and “C:\Program Fle\ Microsoft Otiie\ OFFICES" directory, but the assembly i stil missing references, The data doesn’ start unl row a4, before that was ‘nexplanation on how thei was erated. [used the interop to Femove those rows, and then select fom excel using ‘OleDb 1st possible to instal jst the PtA and COM object without installing the entre office suit on the server? Does installing Office/PIA's require adltional licensing? ‘Az Ifyou intend to use a component pat of Excel, the machine ‘on which it uns shouldbe licensed frit. You could tse the “System Data,OleDD" namespace to pull data from an Excel workbook without requiring interop. This would get around the licensing issue. Using OleDb’ wil remove all Interop worries and Exel dependencies “Take note that using “1V65596" as the“end cell reference! will not result in thousands of empty rows, only rows with data willbe eturned, You ean ignore the fist 24 rows by using the fllowing: sing (System Dat OD, OlzDEComestion = new System, Data OleDb.OleDE Connection" Provider-MlrosoJeLOLED B.A0;DatsSouce-C!\Test als Extended Properties Excel 05"), ‘ System Data OlDb.Ol=DADutaAdpter da = new ‘System Daa OleDs OleDeDanAdaperSELECT * FROM eevee Quins [SteclSADAAVESSP 05 Datiabe d= new DatTables aia, arid DataSource at } Question 4: Converting “DateTime” to numeric Is there net” function that wil take a‘datetmevalue? '8«:“5/5/2006 12:00:00" and output itin this format: (9505206120000. [As Youcan use the following: System DeteTime.Now.ToSting °MMly99hhmms8") Question 5: Data Grid and Multiple Data Sets ‘ean viow data with the data grid ike everyone else, but what I'm ‘uying to dois loop through alist box of server names and fl just ‘one datagrid withthe results from each server Forexample: ‘The server willbe each server in thelist box. Server" + server DataBase-madblntepraod selet* fom SYSTABLE "Now, a8 Irn through th listbox of Servers I wil retrieve diferent results in which { would ike to place int dat grid All ‘column names are the sme SERVER COLUMN COLUMN COLUMN SQL BobSmith Oakwood Horids SQ12 Brian Kite Oakland Georgia SQLg Frank Sinatra Spider Ohio ow would gout ding th this what 'n working on adapter Fillagdstast, connect uri DataSource = sda Tables scone) uatable= sgldase Tabls[dobi] + sqdstact Tabeso (This pore isnt working) Tam trying toad datato the data table. How can I reslvethis problem? ‘Az You coud just makea “Data Table", Fil the data table with the data that you want, and then just make the data table the ource for the data gold The data table has much les overhead. emer tions you havea set number of columns ‘ereate stable and define tem ‘DataTable t= new DatTablet‘statresd™, Cols. Ada(“SERVER" {.Columas-Adal°COLUMNI ‘Columns. Ada(’COLUMN2", {Columns AdICCOLUMNS {i getyour server data out othe listbox 1/00 SOME STUFF HERE ‘ak ap tat ples rough ist orn ses furs 0 ser coe) ‘ “11 define the array that will hold the values for each row ‘vig eto =n sinl 1 gett server name rom you listbox at pstion i 1 assign tthe it ites athe ary ‘theRom[0] = "your euived server mame"; ‘ido your staf to get the dypamie data Ui based on the vale you retrieved above Uv assign tothe ter array pesiions Row} = "Stu you aot reo"; theRow2] = Stuff you gt for cl 2", theRow[3} = Stuff yu got fret 1 one ayo base onthe datatable schema DtaRow dr~ dt New Row); ‘assige the ara othe rom eltemAray=thelows add the ow othe able seRows Ada: , sete dtsource ‘itnGrigl DataSource = A Ce ren Qine ‘Theres another suggestion you can usea“SqlCommand”, *sqlConnecton", and then "SqiDataReader” ‘You can also take a diferent approach by cloning and copying ‘the data toa mew data table, and then view it Question 6: “GetManifestResourceStream” ‘Whats the meaning of GetManifestResoureeStream”? ‘Az Itallows you to pull resources (Images, cons, ete) which are included inyour solution. Soifyouhave My Solution References Images “FastForward gif (Embedded Resource) Assemblylnfos Porm.ct, your form could sa: ‘soeams~ ‘Assembly GetxecutngA sembly) GeManfestResourceStrean("™y Solation mages FastForvard i PictureBox mage ~ Image FromStream(; 'Now, your picture has been pulled from the embedded soltion resputeefle{ XE. “embedded solution resource file” }andis Deing usedin your picturebox. Remember tat any resource ‘that You want to use this way must have the’ Compile Action” property set to "Embedded Resource" et Quon Question 7: Hotkeys How can I blockthe hot kes of excl, word or anotherprogram Tike tis? Is itpossible if open these kind offiles fom Cv? |Az Youcan install ‘system-wide’ keyboard hook You ean ‘heck which app has the fous and fis the one you're interested {and then remove the keystroke from the queue. Question 8: COM interop ow ean use COM interop in Co? 1 em working onan application that uses BIT feature in windows Is there a link for that? As Youcanjust ada reference tothe COM DLLXE “COM DLL} on your project by goin Usrough “Project/Add Reference, Ont tab? After adaing, you'll find onthe Solution Explore that fan” Interop DIT was created. ‘Theimerop DLL's «NET assembly, and is used like how you ‘ise the -Syatemal ascembly of NET" with ll the NET classes land envme Its basieally “NET wrapper that does the ‘marshalling of data as you consume the COM object. ‘What you wil relly need is a good documentation on BITS. But iyoustil need an in-depth material about interop, just google ScoM interop 22. Question 9: SQL issues have the following example dataset: panna oo From this, [need to fetch the highlighted rows. I need each “pubdate” row that has the lowest amount in count. the ‘hunt has more than one, that isthe lowest. But the same as ‘other, need to take the record withthe highest ‘eli’. ‘So ar Thave come up with this (minus the equal count part) ecare @tempst varcha(800) ‘eslare @pubdatelDs varehr(3000) set Qpubdaes SATIS, 4, 708801" set temps ~ ‘select punted rei mncous) from #MR_emp “where pubditeid in (pubs +) group by pubdate, el re (temps) 1 assumed it will give me lie ofall the“pubdatids” with the lowest count, but instead itjust returns the entire table. ear Qin teri Qt ow an cores his? Question 10: Finding out what a statement is doing ‘As Youcan usethe following eodefn your SQL: sion "have this statement that doesnt give me the results I expecta obs tants), ite com ‘ t= mnPostion ) “ up by pub ICount ‘ (Conver Toln32img lmageDataTables{0} Rows] (rinmgea" {Conver Toln{img.ImageDataTabes(0} Rows "paren" ) ke n (Conver Toate nageData Tables Row] (imaged - Convert Tolno (ng imagebats. Tables). Rows = 1yrprentia) > 1 > ‘ {Conver Tolatimg ImageDataTales[0}. Rows] [image = Conver Taln6 2g ageDut Tabs} Rows pet) img ageDut. Tables 0} Rowliparenis") > ae n (Conver Toltimg imageDataTales(0} Rows] {presi - Conver Tln82(mg,ImageData Tablesf0LRowsi- Teper 1 > i | teri Questions | r mg imageData Table 0] Rows pareti") aa img ImageDeta Table 0) Rows] parenti’ ee conser Totnes jmg.tmageData.Tables{0].Row stapinagsi Cane Tot img nageDta Tae Roa = ite > 1 img imageDat Tables(0} Rows ae fg ImageData.Tabes0) Rows parent) = all ae ‘ ‘Convert Toln!32img ImageDuta Tables}. Row sfifimagiy - Conver Tota 2(imgImageDta Tables} Rows = Isthere a way for me to throw message box into the statement, oF ‘some other way forme to find out exactly what is happening? [Az Break ach of the “pieces” of your iftatement” down an ‘se them to tet the values of some ofthe Boolean variables fan besomething ike this: {Ccoane Toin2(ng mages Tabs] Rows image) — SomerTolninginageData Tables] ROW paren") “ae Conve Tott2{ing InageDnia Tadeo] Rowing) Comet Toln2(mynageData Tables} Rows - Cpe) > o eri Quins —_ oT sey noon ator (Coney oan ane er ey 2 (Gong iageDatabes( Rows pret" (Conver Tolns2mg.ImageData Tables 0| Rowsiparcti"). ome Tela iapeD tes Raw fo bool tp = |= maPositon (sept sop293)) ‘This way, you'll be able to check the value ofeach condition along the way. You can break it down even farther fyou need to zai Quests Question 11: tsql temp table ‘have the folowing SQL: ear @temgstr varha(8000) ‘evar eds varchar 3000) set Gods = 83471814, 7608801" set @tempstr~ rete ale emp a slat edd, bub oud) fom fed where eld in = ies» ps) ‘But Lam receiving this eror Server: Mog 16, Level 15, Stat I, Line Incorrect syntax the Keywords hovers ove ‘declare @tempstr varchar #000)" when Tlic on the error message Can Lui a temp table in taal? Iso, how do doit? ‘As You must put the symbol 2"in font ofall temporary tables. ‘ey this: declare @tempsevarcha(8000) ‘elas rede varchar(3000) st @frods = 8347181 4, 7608501 set @tempstr~ sles red, ubbi, count) iz emp fom fro whore fed in (= eds exce(@tempst) COryou ean try the following: (ener Qtions slate sept warcar8000) etre reds varcharS000) Crete table temp “ fri nt ‘ubbid in, sues in set eds = "8347151, 4, 7608501" Set Gtempst~ nse nto Memp( ted ubbid, mmRecs)cect edi bubba, countdoi) fom feds where ein ('> eds +") exc (@tempse) eI Quetns Question 12: Syntax ‘'m currently beginning a project using IBM MQfor ‘ne’ but ‘oneline of syntax made me litle confused. ow can I convert the following o vb.net’? code: int openOptions~ MQC.MQOO_INPUT.AS.Q_DEF| MQeMQOO_OUTPUT; 1 don't know what the pipe” translates to As The pipeisan“OF" operator (that's what thought, but fo ‘ome reason I thought an oe” was two pipes, I's bitwise-OF ‘erbus the two-pipe version which isa logieal-OR 0,2 | returns g because theit-patterns are: 0000010 ‘0000001 0000017 ‘You can also check out the following site for more explanation: -tps/en.ikipedi.org/wiki/Bitwise_operation eri Qutons Question 13: Import a “*.reg” file How ean {import a"*.1ep" ein C9? In VbSexpt, 1 would uss "WehShel Run" 'ogoditexe /s eg ‘Az Youcan ty the following code: System Diagnostics Process Staneget.ve E09"); Question 14: Hide a ‘Form’ when X- button is pressed {have an application where one of my dialogs was created when the program starts, like to eall“Form.Show0) and "Form.tide( to show and hide the frm. ‘When the user presses the 'systom-X button, the form is per efault disposed, How do prevent thet just want a “Form Hide() when the user oes that so thet I can cll "Form, Show()" again without making ‘anew instance oft? ‘You can als try the allowing: ‘protetedoveride vold OnClosing(CancelEventAras¢) t ‘Cancel tae aed: bse OnClsingte: , Ce tmervine Quins Question 15: XML/SVG SetAttribute Issue xlink:href 1'm working ona code to generate SVG dynamiclly(XE. “generate SVG dynamically? via the web. When Itrytocreate an tlement to dieplay one ofthe shapes the “det section ofthe SVG file, Tm getting unexpected output. Below I'm trying to crete x node called "use" with the following, strbute'sdinkchret cose: ssgElem = SvgXml CreteElement( "us" tp 3 .rp 20009" sugElem SetAtiibue link", "+ shectName) Rootode ChildNode( I] FrsChi. AppendChllsegElen), XML Output Coat: 1.0" standalone~"ye8"2> 00" heght"600" ming orp 200048"> cet» ee ot HIX76 5X3 5 370" 90" whdhe"800" hgh style= linonestokerg0,258) token 08°» eet giransform="anslate(20, 585)>> “Sg eantorm="sele(95,-095)> “hae bef ABIXT6 X35 > “eo ‘Notice that the code is puting out the ellowing: code: ‘Ste a f"¥13 81X76 53.5" expected tosee: cod “ue linktrf"13-1X76.5X3.8" > 23 marie Qos ‘Why is this happening and how ean I get the results necessary for the SVG to work propery? Az Youcanusethe following code svgSlem = SvgXmlCretelement(wse', "ht or/2000506 sigElem SeAtsibuteNode( ret, "pv. 3. /1999 ink”); ‘vpElem.Atebuts(hret"] Valie="¥" sbeeName, ‘SegElem Atsibuts ret" Prefie= "link", ‘Routed ChilNodes[ I] Firth AppendChidvglem); Here isthe XM “
    “avg ith="40" eigh="600" mln" wor orp/2000648"> der “tect = "13-51XT6.SXS.5" x0" 70" wihtm"80" eiht="600" style=linonestoke:76(0,0285)srkewidh. 08" Sp rasform="easite(20, 585) g wansform-"seale(095,-0.95)"> “ae ninkre°#13-$176 5X35" senna "tpe wr 03. 1999/nk” ae se Ce teeew Quetons Question 16: Creating decimals with 4 Question 17: Control button places [Ihave the fllowingeode 1 need tohave a counter that ian int tra into 4 decimal places, HSSRURELSTUN ain ee pando Chat mt a) Nenagex sone) Sovift have counter thats: for(int i = 0; i < mipPanel. PageCollection NumPagesSclected;, 1.2,3,4,5,6,7,8,9,10 ms) t rd PCa i" Tread aceite cana hPa lenght eects 0, 007,075.000, 205.008 007, 008.055,.001 mn hg eh te TOSS upPanel Pagelletion mipPane SeletePagesAray(lls teat Moweanaccomph hist } ) ‘The problem is [ned it to do one of two things Ifthe button was licked, Ineed the above event to run Ifthe button was clicked ‘with the contro button pressed, need to do something else ‘At This can do the trick ate minimam: How do I accomplish this? ‘System, Double db =i 00, ‘hatte Console WriteLio(@.TeStng0); ‘As You can try the following: dd 2 more event handlers KeyDown and KeyUp | peat bool contoteypressed it oi youconta Keyes sede, Kees [private vod youeontrol_KeyLp objet sender, Key EventArgs) i [F if(eXeyCode— Keys Contl) 2 a8 in t ‘conrolkeypresed = fase; , , private void BestAval_Clc(objes sender, EvewAras €) t ieGonroheyrenet) ‘ {De your modified stuff due se youre st , Another suggestion to ty the flowing this mibpPane KeyUp reseed during the i {his mibpPanel eyDown Jamas above “Tobuil the event hander, ry the following now Eventtndlerconel_KeyUp //0sed ‘wth best avilable to ind ot whether the (etl button is pew EventTandltcontol_KeyDown) Question 18: Previewing images (64*64) control ‘ike to preview some image objects in “64"6q" format in some ind of control, Is there any "NET" contro for that? 1 only founa the “ListView” control but with that ean only ‘preview pleture n"16%16 format. That snot enough for me How can improveit? At Youcenusethe“PitureBox" controland add ittoa panel. ‘Also, when you gt the Image, recommend getting ony the “thumbnail from the image Iuage Get Thumbnail (or something similar) Cintinc(614: Method "QC.QCMaincott_KeyUptobiest, System Windows Fors Key EventArgs) des ot math delegate voi System Evenianle(bjet, System Evet Aras thisbpPane KeyUp += new KeyEventHandertcontol_KeyUp): ‘Your eontrol hasta have focus, 0 you may have to lick onthe panel before it will register the event. The other option sto put {heevent handler on the form and set the“KeyPreview" propery torte" eter beta chilaNode = new uestion 19: ‘ em Window Forma TreeNode Question 19: “Treeview” node p ‘hldNode Tg sing orm (0) 0% erated nod shoteconyhaea teen, oNC1DDsMD sin create a lazy loading trecview. The tree only has eves. BildNode Tet = ARow{ "Desc" ToS allow loading the fist evel, The second s loaded only ifthe use “hosuinas txpandsit To make the plus appear fr nodes that contains ‘Nodes AddildNode: ‘Ghilren add one node with an empty string under each rt ) level node. The onlycode that deals with expanding and ) callapsing «node isin the “MouseDown” event. Sometimes, the dee ‘ode won't colapee but it would clear the ‘child nodes and add one blank text node. Nodes Clear; Coates hildNode ~ new Sytem Windows Forms. TreeNode ‘i Noder AdAiNds) private void phone Tree MouseDowa(abec Sener, } MouteEventArgse) ) t ) ‘system Windows Forms TreeView ) (som Windows Forms TreeView)sener, ‘System, Windows Forms: TreeNode = Ww GaNodeAKeX, my Systm Windows ems. reeNodecildNode; What am doing wrong? Systm Dat DataTable at Systm Data Dato Row; |As You described bug andi is exactly doing what you coded it stint] values; fodo: iat ‘dou it woul clear the eild nodes and add oneBlanktext it (a null && aLevel 0) pode.” ‘ Nodes Clea, values =m-Tag-ToSringd) Spit); oe: ‘ if ine Parevaves > OVnode has sublevels Nodes Clear ‘ itn tsExpandes) chilaNode = new ystem Windows Fors TreeNode ‘ Noes AdCciltNode), ae! ) indaa table; {oe (= 0:1
    Windows —> Immediate (ier Qetone | ce tterion Singin] = Suing Sbsng) Question 23: Splitting a string into 250 |) characters | The ‘Split method’ wouldn't help inthis ease, as you don'thavea “elimiter to spliton. So, youhaveto doit the hard wa). ‘have large string ay maybe ,000 characters Tong and I want {Shp the engin ago character. So, wi have! | Noe that hese are characters, not bytes. = oe here isa suggenion ut donot ike the way it hands the s#7= 10 chars one “vine ns orhe "tab You can se garter testing. Dotto spt cot: sina System #01 = 290 carstong Jeng prion Text Repalarxressins 2-250 chs ong ‘amespace gst c ease Mantas “ c How can doth? pes ot Manin we) sing gut = "2404434234124 As Az You could just get the length of the string and substring itis tite Ay nc at tela ducer) naam eee a tt page Eh Phe Sinhiney pean Soar paterson encanto sl ; om ane ot i ote ' coh. ; ros ate ‘ Sas ate cla 2) ay 7 Noha cipal 205 ae ona ame oe me ; F ! pty nmi reas | ‘ coterie Questions + Ive Questions Question 24: Explanation ofacode —_| Question 25: Plug-in based | development ‘Whats the explanation of thiscode? | 1m going tobuld an pplication tat shouldbe based ing- this myTime:Tek += new io hat extends the cor application with extra customer spetic Shtem Eventandlr( hit myTimer Tih) functions | ike my plug-in to have a common look, feel, and behavior. ike tips on hove o design my application to make it expandable. lke some tips on design patterns that could be useful How do mark this thread as ‘resolved? A: “sytem Windows Forma Ter Conta iscxetaly an fo ee : +o sey reasons mewn foe ‘happens through an event called "Tick. [sete o ve rend some artes on teflon! : ernment fl ends riena ee serena ey “tine Tk ew Signy iyi on ay yah Seombnauaey mine eight lion tis cmon tr ET can ty other question is how I can get the look and fel of my plug- Tenow about indialoge ike Visual Studie dock able windows? ‘When the timer ics, tells: 1s there any support for hatin the" NET framework? aro vd yi Tt ander, ew |A: The .0 Framework contains alot of those dock able ‘and hss where youd the work hathappens vey inteval__(cal. Youre alo purchase hem fom other hed party (Timer Tek) ) Intec of pga you ren eat separate projet th ‘contain only Interfaces ora base classtype, generally interface’ ‘he other thing that might be eausing confusion isthe ™ " ‘ype, Isbetter, ‘opecetor, These two lines are equivalent. f ‘That project canbe compiled a cass library (DLL), where Code: Jother projets can use to crete thelr own compatibie DLL's. 1 poate: fend to take each of these DLL's and put them intoa specif see folder. The, get all the files from that folder and ereate a speciic lnstance of each tem. Inthe cas of events, this operator subseribes you tothe ‘rent. Youean also remove yourself with the-~»" operator. |For eae say ' writing e raving application The tn conen ul hare ato de igs on ie zen, So, you might reat an interac In Your separate projet |called“iDrawingToo!”. » In nother project called “RectangleTools”,you would create Rectangle Tool clas” that uses Use "IDrawingTooT” interface. eerie Quins ‘Compile the DLL and tick tino "Tools" folder in your main projects bin directory (or anywhere common fr that matter) ‘when you're draeng application loads, youl find al the tools in the Toole’ folder and create instances of"IDrawingToo!” (etvator Getlastancet.)). ‘ow, your applications puely framework. and wil only be Tilloal tere are tol avaliable in that folder, You can hen Aistrbute other tole very eal overtime. Just rete anew projec and develop the new tool When Ws done, drop tin the Fool areetory and you're done. {a termsof design pattern, ensure that you are usingModel View controler wherever posable Thisllows your code tobe Tanageable and salable | hope that gets you started. If'you're notifying all plug-ins of a | toolchangesthenyou could ue MVCor some other peo! ‘Sulsriber:pttrn but, {personally prefer to Keep reference o| ailpug-ine aes ay contrller. | | (eter Qtine Question 26: C# file list box {am wing esto’ ina ev rogram Cope Sena werk forme) and aedtotvethe bly ocous how smany tems erected nthe eto Ihave string] flbltems Directory.GetFiles(this strSoureePath), ‘hich should giveme an array that contains every fle, Then, Thave: for Git x0: tems GtLeng(); x44) which should loop as many times as ther are files. These two things donot sem to work Sous, the program ist crashes with no error mestage What Iam trying to do (sy, Lhave these files): acagezg.it ‘S2aaa4se.be aaziauan png aqzgaasahat sdddddeg pat ‘I nee tobe able to remove all les that contain a non-numeric character. 8, the “442244ah gi and “adddddoa pa should Stay, but I want to remove the res ow can [Toop through the items nthe 'lelistbow to check ‘hem, and remove files that shouldn't be shown? ‘Az Youcan try the following: sng) ters = Directory GetlesthisstSourcePth) 1 < Mbtems Lent, +4) iw Quon ste IO Path GtleName Without tein bens; if (tring Namie) i leo ams Adalitem); , , {nt tafiles~ listbox .toms.Coun, tmay be part of2.0 Framework. Int Ibelieveyou can makea reference tothe VB6 dll or you tan wtte your own method where you check each individual, ‘character tose ifs mumerieor not emer Qin Question 27: Losing 3KB when Writing ‘am reading then writing toa fle Thave a 468 fle that Tam, prooassing, The resting ie missing KB. 1 am having problem comparing the files been itis ao big, | Here is myende: SeamReader reader ~new SteamReadefle_ name, | Encoding UTF, false, 100000) ‘SweamWrtr converted file = now StreamWrierle-pame. ot, fase, Encoding UTES, 10000); ‘converted Me Autfluh = ruse hile (reader EndOPSream) f converted. fle Wrt(eaderRead.ine) , reader Cone Fender Dispose): Eonvered file Fish, ‘converted fle.Chse): ‘onverted_ fle Disposed: "have used this on a 400M file and there was nolos of data, Is there a solution fr this? ‘Az You might also want to look at possible differences in how “Tne-separator’ are being handled, You can read in by ‘cariage returns and writing out with none, Now, the ie sizes ane the | Chockif the size you are ooking ati the actual size ofthe files, ‘ot ‘size on disk whichis sometimes shown, Since es ‘usualy stored in blocks of ak, a variance ofles than lecan be expected with regards to sizeon disk. ‘Also, jst to be onthe safe side, move the “reader clos “reader dispose” to fr the FiushO™. ad eri ues Question 28: Create updates made a ‘Setup Projet inVinual Studio 200s for my Tid ahora wel but when im goin to diabetes an snoeatin iver of my apatin my ents hve update ne pation and then rental the nev 096, 1 get the llowing ero when Isto instal iy ap aan: “sqnother version of tis products already installed Installation “arate re cannot continue. To configure or remove the ot erelon ofthis product, use Add/Remove Programs on {he Control Pane” “What should do to make the new release be installed over the oldone? ‘As You need to increment the version number of 00" ‘As eaton Then, wil install you want. us} Sudo has topped autodcrementingaer version 6, Mian sai conte we for etoing that ecto “The procedure might be similar to Visual Studio 2005, Seleet your Setup Project’ and then Took atthe properties Seto ec ahould be property called Version”. Tacrement vrindow Thine tat makes sense forthe changes youve made. ‘o your ui and ‘play sts and then you shouldbe alls oiterew uone Question 29: Icon shows as an icon with no picture ‘have been working on an application for some time, but now I fm testing deployment [find thatthe ioon shows ok asa ‘horteut of the desktop but notin the ‘start menu where itTooks ite scent ner. veal nied ag ‘small on (2646), the program has a good icon correct picture) ‘fviewed ina folder on detall view. But fT switch to tls view, then the fon looks bad (like there has been no picture drawn on it)and vie venea if] use gaxg2. I want my program toshow the ‘correct feon no matter how its viewed How can Ido that ‘At You need to create an con fle that contains multiple ton formats Take &lookat“Asialis Jon studio". An eon file can contain more than eon, “Typically an fon ile wll contain the following: Full Color Alpha Blended WindowsXP Ieons ull Color (Not alpha blended) 256 Colors 8 olors land Monochrome icons atthe following sizes: 6x6 saa ou Thisallows the OS or oftware to choose the most applicable icon for its display needs. mm | efile extension of this eis". eerie Questions Question 30: Binding data textbox format ‘Ym binding a textbox to a“Correney datatype (KE "Curreney Geta type") ina Berosot Access database. Everything works 25 expected except forthe format ofthe currency fl in the text ‘bone want to display 2 decimal places like"#. #2". ‘No matter what [enter oF routines add it will work to append "oo" tothe textbox sting even when the vac is dollars. The Dining seems to strip sway any zeros. roo became10.1,20.00became20, ‘Any ideas how I can solve this? Az Try wsing“0.00" instead of 4.09". Iheiewe"#"is reserved for plaesholdere that are OPTIONAL, whereas “0” wed for placeholders that are REQUIRED. When binding to the acess database you must create *ConvertEventHandlers to intercept the Format’ and "Parse! that occur atomaticlly during the binding proces. First, create separate binding Binding b= new Binding Tet tview *AscetsDatabaseColumName"), “Then, rete ne “Convert veniHandles” er the Format and "Parse! vente that osu daring binding: ‘Format = new ConvertEvenHandler(DecimalToCurrencyStig) [Parse + new ConvertEventandle( Cenc StringoDesima)s “The, bind thease wo the textbox: exon Dataindings Ad), Here are the conversion funetions: ‘private void Decimal FoCareneyString objet sender, ConvetvenArgs cevent) c itceventDesireType = ypeofstrng) ctu: emacs (deta) ent Vat Testing vat void CureneyStingToDsina bet ender, {anvetvemrgs event) one . ec Deseo posi) sm Pande Veet) Nanbye Cun lh Make sure to reference System Globalization” to over *Numbersiyes.Curreney.” using "System, Globalization ows advil ald stored nan ‘Aces atbat wl omert to ‘Currency’ format in & textbox. bese wll convert | Question 31: Selecting from list box with right mouse button eft click on in tem in litho it select the item. Clicking the right mouse btton's detectable i the listbox Dut does not select the item, {Is theres way to override thi listbox behavior, nd select an item with the right mouse button? ‘At Inyourright-button event handler, set the"Selectedindex” property fr the control lHyou are having a problem determining which tem was being selected when the right mouse button was licked Inthe Iithox contro, you ean golve that by adding the listbox TopIndex" with the'Y mouse position divided by the selected item'sheight. Thi will give you the tem that was clicked by the right mouse button oyou could assign the Selectodindex” Question 32: Compiling C# project on the DOS prompt How can Tcompile end execute an MDI projet onthe DOS. prompt? At You can use the following Jou TargetFleexe SoureF lcs sce 8 compiler XE compiler) een Qetins Question 33: Add a horizontal break line between Menu Items 11am adding the “menuitems" tothe “contextMenu" of alittle system tray application I would ike toad a seperator between to "Menultem Heres thecode: this somteeMenul Melts. AddRangenew System Windows Fonns Menuiten(]{ ‘hismencten, ‘hismenulicn?, ms, ‘tis menutiens, thismeoule bis menaitems}), ‘have tried Dut that adds vertical break and creates 2 columns of my ‘popupmens! How can tell itto puta horizontal separator between 2 "Menultems"? ‘A: Tay something ike adding a" tothe value ofa menu item, just ke adding “Open or "Est" under the "Fle" menu; smenoltem™ erin Quen Question 34: Reading XML file and | exporting onto an Access db {'m tying to build an application which basically oedsto read In an XML document, extract the necessary data, export ‘Access database, and ultimate produc of Cytal Report from the information on the databace. ‘The XML. document is very large, and the "wanted" data are spread out eeros the nested XML aga How do To about grabbing only the data that I want, and then ‘exporting those data on appropriate fields on an Access able? ‘musing Ce for this, I'm looking at “Net Libraries” called: "XPath, kmlNodeReader’, and ‘XmlDataDocument™.n conjunction, these seems todo what I want, but hove would Igo bout grabbing the elements that I want and inert them onto the "appropriate elds inside the Acone table? Do actually need an Access database to produce the Crystal Report in the frst place? Az The general dea i to se"XmlValidatingReader” object along with"XmTextReader” object to read your file alittle itt ‘time. For each node thet gets read (and the node could one be ‘of several different types elements attributes, comments ete) you would append ittoa ‘StringBuffer (see the example or *KmnValidatingReader.Read” method in the" NET” help). ‘When yousee that you get the end element node for your XML record (ike ), you would then load iiato a *XiiDocument object via the ‘Load method (one ofits coverioads takes a String), and then use ‘XPath’ queries against Your document to extract the elements you're interested in and ‘ite them toyour Access database, Question 35: Defining collections ant understand something about defning collections Here isan example: sublet Anal ColectonBase ‘tev ima NewAina; List Adnew Animal , , How can *ColectionBas” class implement “IList‘interface fit doesn't implement all of "Tiss" methods? How is that possible? ‘List property’ returns a variable of types" which points to ‘an object fom whieh this‘Lst propery’ was called from? Am ight? How can 1 use “List Add" method fT haven't defined it yet? Whereis thi method defined? ‘At Ifyou drive a lass from some base, the methods provided by the base are automatically derived aswell unless you overide them. The, your methods take precedence, C¥'sineritance ‘model issimilarto C++. ‘members ofthe clas will appear in drop doven box. You can also ty the following: public clas animals ColletonBase t ‘setup the clas by cling base constructor and sting nner fist (Gerved om collection bare) new ay Tit ‘public animal: base) e Ce ern Qn this Aner et = new Army; } Hoverloadea constructor isnot necessary rai inaisthrtin bo) hiner = , iden et user se Hist implementation force them to use ary lst provided by CollestonBase derived clas (his is actualy level Ss) potested verde List List public void Addanimal ) identi yourself ‘ "is nnerList. Ada ’ ‘Moers derived property pati animal Gent) t stu (animalhis nner make the cass sof by being ableto ceract a animal t cera location a he aay expose these if you want to be able todo other stu ike searching public rapist anil ary wt ret Innere ) ene Quetons Question 36: Code for testing if an “OleDbConnection” is open or close | tried the following: eo ste— Cd sal onm: ‘That did worked atl. How can Lorretthe syntax? ‘At Ieshouldbe: It (con Site == ComesionStte Case) t ‘onl Open: , Personally, think better decign is ealled fr here. You should ‘know at any pont in yourcode whether aconneetion is ‘open. The problem shat you are probubly passing around the shme connection to various methods, and at some point you cant ‘be sure what stateit isin, Streamline your code so that ‘obvious, thi wl help wih malntainability and fexbiity down the road. Ce meni Quon Question 37: Simple basic form Thavea“mainmenu(mn¥Main) with a menu option “Seareh(mnMainSearchy" on the“mainform({rmMaln)" 1 need to know howto have an ‘on click function ofthe ment option of “manMainSeareh" to have the "Seareh form(frmSeareh) be loaded with fous. frmMain” i stil i the background with out focus How can lencoute thet? ‘Az Youstllcan double click onthe menu item to open the ode" windows. Then you need to make an instanceof your search form Tike the following: fimSsarch f= new FmSear Shows Question 38: Casting & WMI Problem ‘Theep getting a casting exception inthe following section ofthe cade, ean’ seem to convert rom the object to int. Is there any way of geting the iret element from queryCallection other than having to enumerate through it? Management Objetolletion queryColecton = query Get); Int tempi: Object foreah(Managemen Object mola query Colleton) ¢ obj ~ mo nvokeMethod( "Terminate ull Az The best wayto do conversions ist utilize the ‘Convert ‘lass. Inyour eae, you ean do something Ike this tempt = Conver Tlat2(0); For mor information, check ‘help’ forthe Convert class. Question 39: ADO Init posible to create an Access DB "on the yusing ADO? aot, is there anyother method? ‘Az You can use ADOX (COM) objects todo it. See ADOX APL Reference in MSDN library for more details. evi Quins Question 40: Show result to a label ‘come from a Cr+ builder environment and {was convinced to private void bttont_liek(objec Sener, System Even Aras) ¢ ouble x2 = Conver TeDoublento Test Souble 2 ~ Conver TeDoubletextBox2 Text) ‘ouble x= Convert ToDoubefextBox3 Tet) ‘ouble xx = Conver TaboubletetBoxd Tex) ‘double yy = Convert ToDoabletextBoxs Text} ‘double xy = Convert ToDouble(extBox6.Tet) double dxzdeyzdydyy, Bl, 8280 6s is (oz ee yey ne aye yn ye yey -ye "Sx dyn tx ay baayy tenet ay toa xO=(O1*dyez-b2 "dhyana + dye deny. 20=(b1 * haz 82 * dja) dyna * day aye * a) = Math Srtax x) * (4930) -(%-0) *(9-90) I= Math Squat Powtx 0.2)" (94-90) > Math Powe) Ty = Math rth Poway 30.27 (yy y0) + Man Powe2)): Te Math Sqr(MathPow(x2-x0.2)+ (92-0) + Math Powe) {20 Conver ToDouble abel. Tea) 40> Conver ToDoabletabl28 Tet: Is there a solution for thie? At Try reversing the assignment at the end Instead of: X0> Convert TeDoubelbel27 Text) 30 Convers TeDoublelabel28 Tex) try Iabea7-Text = x0 Testing: Tobe Text = O.TeSting Ce tee Quine Question 41: Saving the properties of a class ‘Lmade a new lass with alot of data, Now, Lwant to save this class data toa fle. How should I attack’ this problem? ot have to write each and every property data ofthe class toa file, orean I save the whole class a 0? ‘What isthe best way to save efile for security eatons? I don't want a tet Ml Az What you are trying to dos clled “serialization” and you ‘an find itvery easily in MSDN online. ically, you markyourclass with the “Serialized” attribute, and ‘then ise something ike ths MyObject oj = new MyObjexQ: [Farmar formatter ~ new Binary Formate), ‘Seam sear ~ new Flesteam(MyFilein" FleMode Crete, Fileaccess Writ, Fleshare Nowe) oat Serlizetsteam, oh) seam. Clo, ‘There are some other formatters available, including an XML. you want asafer way, you can use erypt streams to write dat, “NET” framework supports different enerypting methods, both ‘smmmetric and asymmetric, lke RSA for example. Ce mare Quast Question 42: Using a class in a code 1am developing web application using VS.Net and Ce.1 understand how to use other system objects such asdatabase ‘communication ‘Now, Ihave written my own clas, and “VS.Net” created the namespace “GabeC™. My lass ealled"ComFunes™T havea *ComFunes" constructor, and a publi string is"Open(int smyVariableyfunetion. ‘am having trouble on understanding how Ian use this class and funetion from my “efault.apx.cs" page. 1 don’t understand how VS.Net and Ce know where to find "ComFune". For example, [use VB 6.0 quitea btand iff writes allclled"ComPunee" and before I can use it (early bind t nya) I need toad tas a reference tothe project. In C#, before can use ADO, Tneed tad somethinglike ‘sing “System.Data SqlClen” atthe top ofthe lass. guess 1 sssume that since "System, Data SqlClent” isa eystem Object ‘VSNet knows were to find | want to create an object that hands all my database work for ‘meso can seit in multiple applications. ft createa DLL or Class (which shouldbe doing?) ina project ofits own, how do tse itin my otherprojects? As You need to instantiate copy of your elas ‘ComFunes MyConFunes = new ComFucs) Andithen, tcallyourmethod: ‘Sing Ret = MyComFuncsxOpen$2) Away to remember things ike this it think ofthe elas sa cookiecuter that stamps out (instantiate objects that you can eter Quine ‘Inyour visual studio projet window, expand the "References” seition. Right dick, and select “Add | Reference” Once you've ‘done that, you can insert the "Using blah bah statement atthe top of your code. Question 43: Screen size simpy need to get the scren size. {remember iaVBt goes ke “seren with & sree. eg." Hove sano that? ‘At You can uso "Sereen, Bounds. Width and *Sereen Bounds Height”. Ce tein Qin Question 44: Adding a new “XmINode” toa file How can adda new node toanexistingxml le? XmlNode lass has a method “AppendChild(XmlNode node)", but cant ereatea new node CinlNode newNode = new XmiNode() because "KmiNode" is an abstract clas. Is there some way tocreatea new node? At Try this: XmlNode newElem = dc. CreteNode(XmiNods Type Bement, "NodeName Youcan also create sn clement ike this: Xnilemen newElem = do. CreateElement(NodeName! ‘You canalso take look at MS help fr more information: {//MSNSCCMS.MSDNVS/pref/bml fre fSystemxmalXmlDoe ‘mentClassCreateElementTopic htm Ce teeien Quins Question 45: Accessing labels on form havea windows form ealed"Main‘with label call “Progress also havea Component called "Export". Inside "Export have function "PopulateDate", ‘Onbutton click in main, cll the “PopulateData” funtion, bic oid Pope) ‘ int uBound ~ Sectors.GetUpperBound(0); wed : meow Main Press. Tet = Bound) ’ How can I acess this abe in these circumstances? Question 46: ‘Type or name space error message 1am ereting my frst Project in Ce. My objective isto create (GUI that wll interact withthe SQL server db. [have crested "Client project, 50 far so good, added sproect'DataAccess'that includes all elases that do the ‘comnectionta the db. ‘Now, my problem isto connect between the ‘lien andthe “DataAcces projects. Inthe Client side added: Using DataAccess,Connection, ‘Building the solution raised an error: ‘The type or namespace name "DataAcoes' could not be found (are you missinga using directive or an assembly reference?) How can I connect with ‘DataAcoes! project? As You need toda a reference othe ‘DataAcoes project, there aretwo ways todo this. ‘This presumes you have built the“Data Aces project which should bea "Class Library” prolect. When you build a class Iibrary, it ereatesa DLL in the Debug of Release deecory Ifyou don'texpeet to make changes to‘DataAccess’ you can add ‘reference to your solution by right elicking on ‘References the Solution View and choose ‘Add Reference’ fom the men. ‘This brings up the "Add Reference" form. Click the “Browse” Dutton on the right and navigate tothe DataAcces’ project directory and find the“DataAcocs din the Debug or Release Airectory. You still have to put the "using DataAccess" in your code ‘The second way to do thisisto ad the DataAccess project to your Client project. Inthe Solution Explorer view, rightclick the “Client Solution” st Fern Qin the top ofthe tree. A menu should appear. Select "Add...> Existing Project™ Navigate tothe “DataAcess” project and add itto your Client solution ‘Onthe main menu, Project > Add Reference, brings up the same “add Reference’ frm in the prot e-mail Now, choose the "Projects" tab at the top. Your newly added projet should appear. Select lick selecton the Fight, a then ‘OK atthebottom. Youareseto rol. ‘You stil need to add "using DataAccess” i'you don't want to explicitly reterto the namespace, evi Quins Question 47: C# exception ‘heard that using exceptions in C++ sometimes causes ‘unpredictable results, even suspending the system, Rarely of ‘course, but canbe destructng in cases ofbusines projec. ‘The alternatives writing a module fr error handling not using exceptions ata hiss 8 more difficlt ay. ‘Were there any tweaks donein“.NET (Ct) with exceptions, perhaps making them less dangerous to use and more reliable? Is there short overview of exception dificlties in use and potsibleerros concerning them? As Exceptions are much better integrated int the NET cavironment. Nomore having to choose between Wing exceptions and C++ exception (neither of which were that fun to ‘work with) 1've pretty much decided that excptions are there to catch programmer errors, not user errors. Ifa ser supplies bad input, then my code should have caughtit. Ifa network resource is ‘unavallable, of ithe database connect string wrong, then an txcoption should catch. (One thing that i ite unusual in NET exceptions isthat the varlable Scope spans the ty, catch, and fnally Blocks. Soyo ¢an'tdo something like this! nyt ‘SalConnecton My Connect ~ new SlConnestion(connettrng) 1 eto Exception 6) ( MessageBox Show(e Message), ) MyConnect Clots ‘because the compiler wil sormplan abou 9 instanceof MyConnet ‘Sng found forthe Clove method. Do something like hs SelConnection MyConnest~ ls ot

You might also like