10 tips for great .net programming
whether you re interested in windows forms, asp.net, web services, or the .net framework, these tips help you exploit the still young .net technology.
by dino esposito
the .net framework is larger than ever and filled with a huge number of classes and methods, but the developer community has yet to explore and understand most of this incredible volume of software features. what might appear to be a bug or a design flaw at first might be considered a significant strength after a second, more thoughtful look.
in light of this inevitable refinement process, sharing tips with other developers, although far from providing the definitive solution you might be looking for, is a way to steer you in the right direction when you build your the first .net application. i ve compiled a list of 10 tips to make your .net development more effective and productive. to help as many developers as possible, the tips span the technology s whole spectrum—from ado.net to asp.net, from the clr to the framework, and from windows forms to web services. here they are, counting up to the ones i anticipate will have the most impact.
tip 1: shape up your datagrid s footer
the datagrid control might feature a footer—that is, a row that summarizes part of the content shown in the page. the footer is hidden unless you enable it by setting the showfooter property to true. once you do, the footer appears, but it has exactly the same number of columns as other rows. if this is fine with you, it isn t a problem. otherwise, you ll need to add more fields to the footer or remove existing ones.
onitemcreated is the key event to hook up. it s the event handler s signature: void itemcreated(object s,datagriditemeventargs e)
this code lets you control the creation process for the footer and any other datagrid item: listitemtype itemtype = e.item.itemtype;if (itemtype == listitemtype.footer){ e.item.cells.removeat(1); e.item.cells.removeat(1); cellsummary.columnspan = 3; e.item.cells[0].text = "...";}
make sure you intervene when the footer is being created, then grab the control instance representing the footer row. then you can remove or add as many cells as you need. don t forget to set the columnspan property to the original number of columns to avoid rendering problems such as having the footer line look shorter or longer than the rest of the grid.
tip 2: use the cache object
in active server pages (asp), you were used to employing the application object to detect global events and store application-wide data. given many users from different pages can access the same data cell, you must use lock and unlock methods to serialize access and avoid conflicts and unpredictable results. in asp.net, together with the application object, you have the cache object, which has similar characteristics but ends up replacing the application object in more than one instance.
both the cache and application objects are collection data containers that make content visible across page and session boundaries. both don t fully support web farm and web garden scenarios. a web farm is a web server architecture in which multiple servers host an application. in a web garden scenario, multiple processes on the same server host an application.
unlike the application object, the cache object isn t instantiated as soon as the first page of the application is loaded. the cache object gets into the game only when you use it. in addition, the cache object has features to minimize the amount of memory its data items occupy. you can set a relative or absolute expiration date for cached items as well as associate them with a priority and a decay factor. then you have greater control over the status of your global data and can implement a special policy to degrade gracefully under low memory conditions. additionally, the cache object manages thread-safe objects and doesn t require lock and unlock.
tip 3: call a service with get or post
a web service is primarily a url that you connect to using http. when you create a proxy class for a given web service, unless you specify otherwise, the command-line tool wsdl.exe serves you a class that uses the soap protocol to make remote calls to the web service.
although the soap protocol is the expected standard for remote procedure calls, nothing prevents you from making calls to a .net web service using plain get or post requests. incidentally, post commands transport soap payloads.
you can build this feature into the proxy class directly by setting the /protocol switch to httpget or httppost when calling the wsdl.exe utility. the source code for the wrapper class behaves accordingly. you can also call a web service using the xmlhttprequest object (see resources) and either plain script or compiled code: set http =createobject("microsoft.xmlhttp")http.open "get",_ "http://server/service.asmx/methodname",falsehttp.send ""msgbox http.responsetext
by using xmlhttprequest, you have the chance to connect to web services from win32, script, and, in general, non-. net code.
tip 4: use cookieless sessions
in asp.net, the session object refers to a configurable software entity you can map to an in-process or out-of-process module. the session object reads a number of runtime settings you can store in the web server s framework installation tree or in the application s bin directory from the web.config file. this file determines the settings for a number of asp.net components. if you put a copy of config.web in your application s local subtree, the settings end up overriding the default ones set in the framework path.
one thing you can customize is whether the session manager should identify client sessions using cookies (the default) or not. this line in the application local config.web file sets the session manager to work without cookies:
<sessionstate cookieless="true"/>
tip 5: use custom grid pagination
the web form datagrid control has built-in support for pagination. it displays a pager bar automatically and, with limited help from your code, it shows pages of records of the given size. however, by default, all the necessary records are cached in the datagrid object s datasource property. this means you must fetch the data all at once. although this isn t such a big issue with a few dozen records, it becomes a problem with thousands of records. in this case, you might want to fetch records manually and cache them on disk, but off the dbms.
you must inform the datagrid control of this particular behavior. fortunately, the datagrid provides for an allowcustompagination property that, when set to true, changes the internal behavior of the control quite a bit. when you set this property to true, the grid always reads records found in the datasource property from first to last. it s your responsibility to replenish this container with fresh data belonging to the current page. normally, the grid itself fetches only the records that pertain to the page from the datasource property.
tip 6: load key info from database
the datatable object lets you set in-memory primary keys on a given table. this action speeds up the search on both the datatable and related dataview objects. another good reason to have in-memory keys is to automatically prevent duplicate insertions that violate table integrity. then you have plenty of time to fix the table, even properly warn the user, before the data is actually submitted to the database server for a batch update.
10 tips for great .net programming (continued)
you can set this information manually in your fetching code:
//ds is an existing dataset
datacolumn[] keys == new datacolumn[1];
datatable dt = ds.tables["mytable"];
keys[0] == dt.columns["id"];
dt.primarykey = keys;
you can have the primary key information detected and set automatically while filling the data set. you automate the discovery of this information, and consequently the execution of your fetching code, by setting the missingschemaaction property of the data adapter that performs the query:sqldataadapter da = new sqldataadapter(strcmd,strconn);dataset ds = new dataset();da.missingschemaaction = missingschemaaction.addwithkey;da.fill(ds,"mytable");
tip 7: request selected checkboxes
in any asp application, you have several checkboxes, all with the same name:<input type="checkbox" name="foo" value="...">
you can get the corresponding values of the checkboxes that have been selected upon form posting with a single line of code: <%a =split(request.form("foo"),",") %>
request.form("foo") returns a comma-separated string formed by the value strings of all checked items. you pass this string to the vbscript s split function and get an easily manageable structure, such as an array.
the same code won t work in asp.net if you use the <asp:checkbox> server control. to make it work, stick with the htmlinputcheckbox control and write code such as this: <input type="checkbox" runat="server" name="foo"value="...">
even though the asp:checkbox and input type="checkbox" server tags evaluate to the same html code, asp.net ensures unique ids and names for the tags output by asp:checkbox and any other control in the <asp> namespace.
tip 8: automate master/detail views
if you have a windows forms application that uses the datagrid control to display master/detail tables, chances are you can have the framework synchronize the views automatically for you.
the key is creating a data relation between the two tables and using a composed expression to define the data source for the detail table. let s assume you have customers and orders tables with a custid field in common. you create a relation in terms of an ado.net datarelation object://ds is an existing datasetdim dc1,dc2 as datacolumndc1 =ds.tables("customers").columns("custid")dc2 =ds.tables("orders").columns("custid")dim r as datarelationr =new datarelation("ordersbycustomer",dc1,dc2)ds.relations.add(r)
whenever you have a datarow object representing one row on the master table—customers, in this case—you can obtain an array with the child rows according to the relation using the datarow s getchildrows method. for windows forms, this programmatic approach is buried in this code: dgrid.datasource =dsdgrid.datamember = "customers.ordersbycustomer"
when you associate the detail grid with an expression such as mastertable.relation, its content is refreshed automatically and properly.
tip 9: handle file change notification
.net integrates the functionality of win32 file notification objects into the filesystemwatcher class. those kernel objects are responsible for notifying client applications about changes detected at the file system level. according to the specified parameters, a notification object signals the status of the applications whenever a file is created, modified, renamed, or deleted.
it s difficult for win32 to know the name of the file being involved and the reason for its involvement with the event under windows nt and windows 2000. all this has been superseded in .net thanks to the filesystemwatcher class: filesystemwatcher watcher = new filesystemwatcher();watcher.path ="c://";watcher.filter ="*.txt";watcher.notifyfilter = notifyfilters.lastwrite;
10 tips for great .net programming (continued)
once the object is configured, you begin watching:
watcher.enableraisingevents =true;
any detected event causes an application event to fire. you register for the events you need like this:watcher.changed += new filesystemeventhandler(onchanged);
the handler s event arguments supply all the file and event information you need.
tip 10: compile code on the fly
the .net framework exposes classes that let you compile code in a specified language. these classes live in the system.codedom.compiler namespace. this code snippet shows how to obtain an in-memory running instance of the c# compiler: csharpcodeprovider csc = new csharpcodeprovider();icodecompiler icc = csc.createcompiler();
next, you ll set some input parameters through the compilerparameters class: compilerparameters co = new compilerparameters();co.outputassembly ="foo.exe";co.referencedassemblies.add("system.dll");
you must specify at least the name of the executable, set generateexecutable to false if you want a dll, and add the list of assemblies to reference: icc.compileassemblyfromfile(co, csfile);
to run the compiling process, use compileassemblyfromfile() and pass it the parameters and the source file name. you can use the class compilerresults to learn more about the newly generated assembly.