Tips for great. NET Programming

Source: Internet
Author: User
Tags config expression file system soap connect split web services win32
Tips for great. NET Programming
Whether you re interested in Windows Forms, asp.net, Web Services, or the. NET Framework, this 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 H As yet to explore and understand most of this incredible volume of software. What might appear to being a bug or a design flaw at the A might considered after the a significant, more th Oughtful look.
In light of this inevitable refinement process, sharing tips with other developers, although far from providing the Defini tive solution you might being looking for, are a way to steer your right direction the the The Plication. I ve compiled a list of tips to make your. NET development more effective and productive. To help as many developers as possible, the tips span of technology s whole spectrum-from ado.net to ASP.net, from the CL R to the Framework, and from Windows Forms to Web Services. Here they are, counting up to the ones I anticipate'll have the most impact.
Tip 1:shape up Your DataGrid s Footer
The DataGrid control might feature a footer-that are, a row that summarizes part of the content shown in the page. The footer is hidden unless your enable it by setting the Showfooter property to True. Once you did, the footer appears, but it has exactly the same number of columns as other rows. If It 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 to 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 your intervene when the footer are being created, then grab the control instance the representing row. Then you can remove or add as many cells as your need. Don t forget to set the "ColumnSpan" original number of columns to avoid rendering problems such as having T He footer line look shorter or longer than the rest of the grid.


Tip 2:use the Cache Object
In Active Server Pages (ASP), for were used to employing the Application object to detect global events and store Applicat Ion-wide data. Given many users from different pages can access the same data cell, you must use Lock and Unlock methods to serialize ACC ESS 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 Bo Undaries. Both don t fully support Web farm and Web garden scenarios. A Web farm is a Web server architecture in which multiple servers host a application. In a Web garden scenario, multiple processes on the same server host a application.
Unlike the Application object, the Cache object isn t instantiated as soon as the the the the the application is loaded. The Cache object gets into the game only if you use it. In addition, the Cache object has features to minimize the amount of memory's its data items occupy. You can set a relative or absolute expiration the date for cached items as as, as associate them with a priority and a decay Factor. Then your 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, 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.exeServes you a class this 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 your from making calls to A. NET Web Service using plain get or POST requests. Incidentally, POST commands transport SOAP payloads.
Can build this feature into the proxy class directly by setting The/protocol switch to HttpGet or HttpPost when calli ng the Wsdl.exe utility. The source code for the wrapper class behaves accordingly. You can also call a Web Service using the XMLHttpRequest object (in) 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, your 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 sessions object refers to a configurable software entity your can map to an in-process or out-of-process mod Ule. The session object reads a number of runtime settings can be store in the WEB Server S framework installation The application S BIN directory from the web.config file. This file determines the settings for a 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 I n the framework path.
One thing you can customize are whether the session Manager should identify client sessions using cookies (the default) or Not. This is 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 your must fetch the data all at once. Although this isn t such a big issue with a few dozen, it records a becomes with problem of thousands. In this case, you might want to fetch records manually and cache them on disk, but off the DBMS.
You are must inform the DataGrid control of this particular behavior. Fortunately, the DataGrid provides for a allowcustompagination property so, when set to True, changes the internal Beha Vior of the control quite a bit. When you are set this property to True, the grid always reads records found in the DataSource property from the. It s your responsibility to replenish this container with fresh data belonging to the current page. Normally, the grid itself fetches only the records which pertain to the "page from" DataSource property.


Tip 6:load Key Info from Database
The DataTable object lets your 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 are 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" D Atabase server for a batch update.
Tips for great. NET Programming (continued)
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 are automate the discovery of this information, and consequently the execution of your of code, by fetching the setting Ngschemaaction the data adapter that performs query:
SqlDataAdapter da = new SqlDataAdapter (strcmd,strconn);D ataset ds = new DataSet ();d A. MissingSchemaAction = Missingschemaaction.addwithkey;da. Fill (ds, "MyTable");



Tip 7:request Selected Checkboxes
In any ASP application, your have several checkboxes, all with the same name:
<input type= "checkbox" Name= "foo" value= "..." >

You can get the corresponding values of the checkboxes this have been selected upon form posting with a single line of cod E:
<%a =split (Request.Form ("foo"), ",")%>

Request.Form ("foo") returns a comma-separated string formed by the value strings all checked items. You have this string to the VBScript s-Split function and get a easily manageable structure, such as an array.
The same code won t work in asp.net if you have 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 of the <asp> namespace.


Tip 8:automate master/detail views
If you have a Windows Forms application which uses the DataGrid control to display master/detail tables, chances are your CA n 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 T He detail table. Let S assume your have Customers and Orders tables with a custid field in common. Create a relation in terms of a ado.net DataRelation object:
The DS is a 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 a ARRA Y with the child rows according to the relation using the DataRow S-getchildrows method. For Windows Forms, this programmatic approach be buried in this code:
Dgrid.datasource =dsdgrid.datamember = "Customers.ordersbycustomer"

When your associate the detail grid with a 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 on the file system level. According to the specified parameters, a notification object signals the status of the applications whenever a file is CRE Ated, modified, renamed, or deleted.
It s difficult for Win32 to know the name of the file being involved and the reason for the event involvement Er windows NT and Windows 2000. All this has been superseded in. NET FileSystemWatcher class:
FileSystemWatcher watcher = new FileSystemWatcher (); watcher. Path = "c:\\"; watcher. Filter = "*.txt"; watcher. NotifyFilter = Notifyfilters.lastwrite;

Tips for great. NET Programming (continued)
Once the object is configured and you begin watching:
Watcher. EnableRaisingEvents =true;
Any detected event causes a application event to fire. Your register for the events of your need like this:
Watcher. Changed + = new FileSystemEventHandler (onchanged);

The handler S event arguments supply all of 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 are classes live in the System.CodeDom.Compiler namespace. This code snippet shows you to obtain a 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 are 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. can use the class CompilerResults to learn more about the newly generated assembly.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.