Microsoft Design Guidelines with CodeIt.Right
http://submain.com/webcasts/microsoft-design-guidelines-with-codeit.right/ for the webcast recording and slides download
6/3/2014 Webcast Housekeeping
Audio Connect via VoIP Plug in a headset or turn up your speakers Select “Headset/Mic” in Audio Options Connect via Phone Select “Dial In” in Audio Options Call 1 (949) 229-4400 PIN: 1066921# Asking A Question Use the Ask a Question button in the top left corner Questions will be addressed at the end of the webcast Recording A recording download link will be sent to all registrants within a few days
6/3/2014 Copyright © SubMain 2014 2 Introduction
Presenter (g)host
David McCarter Serge Baranovsky Microsoft MVP Principal, SubMain
6/3/2014 Copyright © SubMain 2014 3 David McCarter [email protected]
@realdotnetdave davidmccarter C# Microsoft MVP Developer/ Architect/ Consultant & Professional Code Reviewer Rock The Nation Conference Tour http://bit.ly/dNdRTNT David McCarter’s .NET Coding Standards http://bit.ly/dpmbooks dotNetTips.com 700+ Tips, Tricks, Articles, Links! Open Source Projects: CODEPLEX.COM/DOTNETTIPS
6/3/2014 Copyright © SubMain 2014 4 Why We Need Coding Standards (Guidelines)
6/3/2014 Copyright © SubMain 2014 5 Benefits
Code Clarity/Easier to Understand Easier to Maintain Reduce Bugs Simplify Code Reviews Shorter learning curve for new team members Consistency across large and distributed teams Comply with internal or regulatory quality initiatives Produces more stable and reliable code
6/3/2014 Copyright © SubMain 2014 6 Business Benefits
Improve software quality Accelerate time to market Enhance customer satisfaction Reduce long term cost Improve productivity
6/3/2014 Copyright © SubMain 2014 7 Why Coding Standards Fail
Developers kept forgetting to abide the 35% guidelines
Resistance among the team members 23%
Couldn't get a concensus on which standard 26% to follow
Management thought is was too expensive 10% and not worth the investment
Other 6%
Source: SubMain survey of developers and teams 6/3/2014 Copyright © SubMain 2014 8 Implement Coding Standards
1. Get the business owner’s buy-in 2. Get initial consensus 3. Choose a base standard to follow a. Customize the standard (optional) 4. Create our own team guidelines document a. Prioritize what’s most important 5. Implement Code Reviews 6. Use code generation 7. Review status and give feedback http://submain.com/webcasts/coding-standards-in-the-real-world/ for the webcast recording, slides and ebook download
6/3/2014 Copyright © SubMain 2014 9 Microsoft Design Guidelines Overview
6/3/2014 Copyright © SubMain 2014 10 Overview
Guidelines for designing libraries that interact with the .NET Framework Most code should be in DLL’s (libraries), not in the application http://submain.com/fwlink/std/ms Most popular coding standard among C# and VB teams Not just for frameworks and libraries Unified programming model Microsoft uses for .NET Framework itself Guidelines are organized: Do, Consider, Avoid, Do Not
6/3/2014 Copyright © SubMain 2014 11 Categories
Naming Guidelines Design Guidelines for Exceptions Naming assemblies, namespaces, types, Designing, throwing, and catching and members in class libraries exceptions Type Design Guidelines Usage Guidelines Using static and abstract classes, interfaces, enumerations, structures, and Using common types such as arrays, other types attributes, and collections, supporting serialization, and overloading equality Member Design Guidelines operators Designing and using properties, methods, constructors, fields, events, operators, Common Design Patterns and parameters Choosing and implementing dependency properties and the dispose pattern Designing for Extensibility Subclassing, using events, virtual members, and callbacks, and explains how to choose the mechanisms that best meet your framework's requirements 6/3/2014 Copyright © SubMain 2014 12 What is CodeIt.Right
Automated way to ensure your source code adheres to (your) predefined design requirements style guidelines best coding practices Static Code Analysis and Metrics Automatic and safe refactoring of issues into conforming code Automated Code Review process
6/3/2014 Copyright © SubMain 2014 13 What is CodeIt.Right - continued
Instant Code Review – real-time code checking OnDemand Analysis Source Control Check-In Policy Build Process Integration Hundreds of rules Security, Performance, Usage, Design, Maintainability, Exception Handling, Globalization, Async, and more
6/3/2014 Copyright © SubMain 2014 14 Microsoft Design Guidelines
6/3/2014 Copyright © SubMain 2014 15 Naming Guidelines
Capitalization Rules PascalCasing – used on all public member, type & namespaces camelCasing – parameter names Use “_” (underscore) to prefix private field names. Not “m_”. Namespaces and Assemblies
6/3/2014 Copyright © SubMain 2014 16 Type Design Guidelines
Leave at default type of Int32 Enum default value Use the value 0 and set it to a “not chosen” value
Public Enum WorkItemStatus Undetermined 0 value Completed Queued Executing Aborted End Enum
6/3/2014 Copyright © SubMain 2014 17 Member Design Guidelines
Do not call code from constructor Only set parameters Incorrect public class FileCache { public FileCache() { var cacheDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); if (Directory.Exists(cacheDir) == false) { Directory.CreateDirectory(cacheDir); } } }
6/3/2014 Copyright © SubMain 2014 18 Member Design Guidelines
Do not call code from constructor Only set parameters Correct public class FileCache { public string FilePath {get; private set}; public FileCache(string path) { this.FilePath = path; No code called } }
6/3/2014 Copyright © SubMain 2014 19 Designing for Extensibility
Sealed Classes Don’t seal classes unless they are: Static class public sealed class Person {} Stores sensitive data Inherits many virtual members (makes sealing members easier) Class is an attribute that requires fast runtime look-up Sealed classes could provide some performance improvement but limits developers from inheriting that type Do not declare protected members Used for inheritance only
6/3/2014 Copyright © SubMain 2014 20 Design Guidelines for Exceptions
Use the “newer” TryParse method on value types to avoid Exceptions
DateTime dateValue if (DateTime.TryParse("11/11/14", out dateValue)) { Console.WriteLine("{0}).", dateValue); } else { Console.WriteLine("Unable to parse string."); }
6/3/2014 Copyright © SubMain 2014 21 Usage Guidelines
Overload Equality & Hashtag Operators on Types
class Point { protected int x, y; public Point(int xValue, int yValue) { x = xValue; y = yValue; } public override bool Equals(Object obj) { if (obj == null || GetType() != obj.GetType()) {return false;} Point p = (Point)obj; return (x == p.x) && (y == p.y); } public override int GetHashCode() { return x ^ y; } }
6/3/2014 Copyright © SubMain 2014 22 Common Design Patterns
using(var sqlDataReader = new SqlDataReader) Make sure you call { Dispose on types that //SqlDataReader code goes here implement using(var connection = new SqlConnection) IDisposable! { Can create virtual //SqlConnection code goes here memory leaks using(var BMSConnection = new SqlConnection) • Use the “using” { statement //SqlConnection codes here } Calls Dispose on BMSConnection } Calls Dispose on connection } Calls Dispose on sqlDataReader 6/3/2014 Copyright © SubMain 2014 23 Common Design Patterns - continued
public class Base: IDisposable • Implement { public void Dispose() IDisposable type { • To ensure resources Dispose(true); are cleaned up GC.SuppressFinalize(this); Signals Garbage Collector } protected virtual void Dispose(bool disposing) { if (disposing) { // Free other state (managed objects) } } ~Base() Garbage Collector Will Call { Dispose (false); } } 6/3/2014 Copyright © SubMain 2014 24 Notes for VB Developers
Enable Object Strict Insures strict object checking is on… just like it always is on in C# NO Goto statements! Dim sum as Integer Use Exit statements Dim number as Integer Exit Do Do number = number + 1 Exit While sum = sum + number Exit For If number = 100 Exit Do Exit Sub, Function End If Loop
6/3/2014 Copyright © SubMain 2014 25 And not only VB Developers
Use Case instead of chains of If statements
If value = 1 Then Select Case value ‘’ Do work Case 1 Else If value = 2 Then ‘’ Do work ‘’ Do Work Case 2 Else If value = 3 Then ‘’ Do work ‘’ Do Work Case 3 End If ‘’ Do work End Select Select Case Put the normal case first - both more readable and more efficient Order cases by frequency - cases evaluated in the order that they appear in the code
6/3/2014 Copyright © SubMain 2014 26 Refactoring to Patterns - CodeIt.Right
6/3/2014 Copyright © SubMain 2014 27 Serialization Pattern - Demo
Not as easy as you might think Any class that might be serialized must be marked with SerializableAttribute Applies to serializing to disk, via a service To control serialization process implement ISerializable Implement GetObjectData Populates SerializationInfo with data needed to serialize object There is more to do it properly…
6/3/2014 Copyright © SubMain 2014 28 Asynchronous Programming
Microsoft Async – originally designed for EAP – “event- based pattern” – no more, don’t do that! Current Microsoft Async implementation is TAP – “task- based async pattern” Best practices – use TAP not EAP Don’t create “Async Sub” methods (aka void-returning asyncs) except for top-level event handlers Call an API that returns a Task? Almost always await it either immediately or later Async methods should have the suffix “Async” and return Task or Task
6/3/2014 Copyright © SubMain 2014 29 Asynchronous Programming – contd.
Async confusing? CodeIt.Right will guide CodeIt.Right Async rule set: Async method should have "Async" suffix Async method should have await statement Async method should return Task or Task
Just the ASP.NET/Security category: Do not disable custom errors Custom error DefaultRedirect should be specified Disable anonymous access Always define a global error handler EnableEventValidation should be True Page ValidateRequest should be True ValidateRequest should be True Page ViewStateEncryptionMode should be Always ViewStateEncryptionMode should be Always Form authentication Protection should be All EnableViewStateMac should be True Avoid the DataBinder.Eval method EnableViewState should be True Avoid the Page.DataBind method Compilation Debug should be False Avoid setting the AutoPostBack property to True Form authentication should not contain credentials Do not use deprecated properties of Response object Disable form authentication EnableCrossAppRedirects Do not use SaveAs method to store uploaded files Form authentication RequireSSL should be True MVC controller action -> Use ValidateAntiforgeryTokenAttribute Form authentication SlidingExpiration should be False MVC controller action -> Enable request validation Http cookies HttpOnlyCookies should be True Review deny and permit only usage Http cookies RequireSSL should be True Review visible event handlers Trace should be disabled GetObjectData is not marked with SecurityPermissionAttribute Role manager CookieProtection should be All Secure serialization constructors Role manager CookieSlidingExpiration should be False Should have identical link demands to base method Page EnableViewStateMac should be True Wrap vulnerable finally clauses in outer try Page EnableEventValidation should be True Type, Security transparent code should not assert Http runtime EnableHeaderChecking should be True and more – 54 in total! No worries – we’ve got you covered! 6/3/2014 Copyright © SubMain 2014 31 CodeIt.Right Benefits
Improve Product Quality at the Source Comply with internal or regulatory quality initiatives Decrease the cost and time of Code Reviews Reduce QA testing and focus on meeting requirements Continuous Code Quality Solution
6/3/2014 Copyright © SubMain 2014 32 http://submain.com/webcasts/microsoft-design-guidelines-with-codeit.right/ Q&A for the webcast recording and slides download
Questions?
Email - [email protected] 1 (800) 936-2134 Video - submain.com/codeit.right/video Download the free CodeIt.Right trial at submain.com/codeit.right Contact David McCarter: [email protected]
6/3/2014 Copyright © SubMain 2014 33