Best Practices for.NET Development Thom Robbins trobbins@microsoft.com.

Post on 11-Jan-2016

214 views 2 download

transcript

Best Practices for .NET Development

Thom Robbinstrobbins@microsoft.com

What we will cover Design Guidelines Memory Management Data Access Internet Services Threading Security

Session Prerequisites

Know VB .NET or C# Be familiar with .NET Base Class Libraries Be familiar with XML

Level 300Level 300

So Why This Presentation? You know you are a VB programmer if…

You ever had to use the On Error Goto statement You never wrote a multi-threaded app

You know you are a C++ programmer if… You ever had to check an HRESULT every 2 lines

of code 30% of your code was releasing objects from

memory You know you are an ADO programmer if…

You had to convert between a Recordset and a DOM and transform the XML 5 times in between

Agenda

.NET Design Guidelines Memory Management Data Access Internet Services Threading Security

.NET Design GuidelinesNaming Conventions

Hungarian notation is out! For public interfaces, use PascalCasing For private members, use camelCasing Use underscore “_” character to denote

private class members Use camelCasing for all method

parameters

.NET Design GuidelinesNaming Conventions

public class Customer{ private string _password;

public void SetPassword(string newPassword) { _password = newPassword; }}

.NET Design GuidelinesClass Members Usage

Don’t use public fields, use properties No write-only methods, use a method Only use properties for setting and

retrieving values Allow properties to be set in any order Use a consistent ordering and naming

pattern for parameters

.NET Design GuidelinesBase Classes vs. Interfaces

Only Use Interfaces When… Unrelated classes want to support a protocol Aggregation is not appropriate

Provide class customization through protected methods

.NET Design GuidelinesError Raising and Handling

Exceptions are not for flow of control! Exceptions are “exceptional” Derive new custom exceptions from the

ApplicationException class

Agenda

.NET Design Guidelines Memory Management Data Access Internet Services Threading Security

Memory Management Avoid Finalize() Only use Finalize() with Dispose()

public void Dispose(){ // Clean up unmanaged resources GC.SuppressFinalize(this);}

protected override void Finalize(){ // Clean up unmanaged resources base.Finalize();}

Agenda

.NET Design Guidelines Memory Management Data Access Internet Services Threading Security

Data AccessAccessing Relational Data

Always use the optimal Managed Provider Pick DataReader over DataSet when

possible Used stored procedures when possible Do NOT use dynamic connection strings

Data AccessXML Data

Use the XmlDataDocument for XML/DataSet integration DOM DataSet DOM

Don’t use DOM if you don’t need it Only necessary for in-memory editing

XmlReader is faster than DOM

Agenda

.NET Design Guidelines Memory Management Data Access Internet Services Threading Security

Internet ServicesWebClient vs. WebRequest

Use WebClient for simple request and response operations

Use WebRequest for more complex operations Asynchronous requests, setting headers, etc.

Internet ServicesGeneral Tips

Don’t pass credentials every time Don’t type cast to descendant classes,

such as HttpRequest In ASP.NET, use the asynchronous

methods of GetResponse and GetResponseStream

As a good starting point, use 8 connections/processor

Agenda

.NET Design Guidelines Memory Management Data Access Internet Services Threading Security

ThreadingGeneral Tips

Avoid locks whenever possible Don’t provide static methods that alter

static state Asynchronous invocation via delegates

are the preferred threading mechanism

ThreadingSynchronization

Starvation is caused by multiple threads contending for a resource

The Monitor and ReaderWriterLock are designed to prevent starvation

Agenda

.NET Design Guidelines Memory Management Data Access Internet Services Threading Security

SecurityKey Concepts

Use the principal of least privilege Don’t run Visual Studio with admin

privileges Use the runas utilityC:\>runas /user:timmc\administrator cmd

Enter password for timmc\administrator:

Lock down security policy early

SecurityCode Access Security

Access to a protected resource The ability to perform a protected

operation

FileIOPermission permission = new FileIOPermission(PermissionState.None);permission.AllLocalFiles = FileIOPermissionAccess.Read;

SecurityRole-Based Security

Imperative (old way)

public void DoTransaction(){ IPrincipal principal = Thread.CurrentPrincipal; if (!principal.IsInRole("Managers")) { throw new SecurityException("Not a " + "manager!"); } // OK, do the transaction...}

SecurityRole-Based Security

Imperative (new way)

public void DoTransaction(){ PrincipalPermission permission = new PrincipalPermission(null, "Managers"); permission.Demand(); // Now do the transaction...}

SecurityRole-Based Security

Declarative

[PrincipalPermission(SecurityAction.Demand, Role="Managers")]void DoTransaction(){ // this time, really // do the transaction...}

Session Summary Write consistent and predictable code Write scalable, high-performance code Write secure code

For More Information… MSDN Web site at

msdn.microsoft.com

MSDN Magazine http://msdn.microsoft.com/msdnmag/

For More Information… Microsoft Visual Studio .NET Documentation

http://msdn.microsoft.com/library/default.asp?url=/nhp/Default.asp?contentid=28000451

MS PressEssential Resources for Developers

To find the latest developer related titles visitTo find the latest developer related titles visit

www.microsoft.com/mspresswww.microsoft.com/mspress