Your SlideShare is downloading. ×
0
Microsoft Design Guidelines
with CodeIt.Right
6/3/2014
http://submain.com/webcasts/microsoft-design-guidelines-with-codeit...
Webcast Housekeeping
6/3/2014
Audio
 Connect viaVoIP
 Plug in a headset or turn up your speakers
 Select “Headset/Mic” ...
Introduction
Presenter
David McCarter
Microsoft MVP
(g)host
Serge Baranovsky
Principal, SubMain
6/3/2014 Copyright © SubMa...
David McCarter
dotnetdave@live.com
 C# Microsoft MVP
 Developer/ Architect/ Consultant &
Professional Code Reviewer
 Ro...
Why We Need Coding
Standards (Guidelines)
6/3/2014 Copyright © SubMain 2014 5
Benefits
 Code Clarity/Easier to Understand
 Easier to Maintain
 Reduce Bugs
 SimplifyCode Reviews
 Shorter learning ...
Business Benefits
 Improve software quality
 Accelerate time to market
 Enhance customer satisfaction
 Reduce long ter...
Why Coding Standards Fail
35%
23%
26%
10%
6%
Developers kept forgetting to abide the
guidelines
Resistance among the team ...
Implement Coding Standards
6/3/2014
1. Get the business owner’s buy-in
2. Get initial consensus
3. Choose a base standard ...
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 (librari...
Categories
 Naming Guidelines
 Naming assemblies, namespaces, types,
and members in class libraries
 Type Design Guidel...
What is CodeIt.Right
 Automated way to ensure your source code adheres to
 (your) predefined design requirements
 style...
What is CodeIt.Right - continued
Instant Code Review – real-time code checking
OnDemand Analysis
Source Control Check-I...
Microsoft Design Guidelines
6/3/2014 Copyright © SubMain 2014 15
Naming Guidelines
Capitalization Rules
 PascalCasing – used on all public member, type & namespaces
 camelCasing – para...
Type Design Guidelines
Leave at default type of Int32
Enum default value
 Use the value 0 and set it to a “not chosen” ...
Member Design Guidelines
Do not call code from constructor
 Only set parameters
Incorrect
6/3/2014
public class FileCach...
Member Design Guidelines
Do not call code from constructor
 Only set parameters
Correct
6/3/2014
public class FileCache
...
Designing for Extensibility
SealedClasses
 Don’t seal classes unless they are:
 Static class
 Stores sensitive data
 ...
Design Guidelines for Exceptions
Use the “newer”TryParse method on value types to
avoid Exceptions
6/3/2014
DateTime date...
Usage Guidelines
Overload Equality & Hashtag Operators onTypes
6/3/2014
class Point
{
protected int x, y;
public Point(in...
Common Design Patterns
6/3/2014
using(var sqlDataReader = new SqlDataReader)
{
//SqlDataReader code goes here
using(var co...
Common Design Patterns - continued
6/3/2014
public class Base: IDisposable
{
public void Dispose()
{
Dispose(true);
GC.Sup...
Notes forVB Developers
Enable Object Strict
 Insures strict object checking is on… just like it always is on in C#
NO G...
And not onlyVB Developers
Use Case instead of chains of If statements
6/3/2014
If value = 1 Then
‘’ Do work
Else If value...
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
Seria...
Asynchronous Programming
Microsoft Async – originally designed for EAP – “event-
based pattern” – no more, don’t do that!...
Asynchronous Programming – contd.
Async confusing? CodeIt.Right will guide
 CodeIt.Right Async rule set:
 Async method ...
ASP.NET/Security
 Do not disable custom errors
 Disable anonymous access
 EnableEventValidation should beTrue
 Validat...
CodeIt.Right Benefits
Improve Product Quality at the Source
Comply with internal or regulatory quality initiatives
Decr...
Q&A
Questions?
Email - customer-service@submain.com
Video - submain.com/codeit.right/video
Download the free CodeIt.Right ...
Upcoming SlideShare
Loading in...5
×

Webcast: Implementing Microsoft Design Guidelines with CodeIt.Right

281

Published on

David McCarter and Serge Baranovsky discuss Microsoft Design Guidelines, the most popular coding standard among C# and VB teams, provide recommendations, show how CodeIt.Right finds code issues, fixes them and provides painless experience when implementing Microsoft coding standards. In this webcast they cover:

» Benefits of coding standards
» Microsoft Design Guidelines overview
» Microsoft Guidelines category review and examples
» Additional notes for VB developers
» Demo using CodeIt.Right to find and resolve code issues
» Bonus #1 - ASP.NET Security rules
» Bonus #2 - Asynchronous programming best practice ruleset
» Bonus #3 - Refactoring to Patterns

Visit http://submain.com/webcasts/microsoft-design-guidelines-with-codeit.right/ for the webcast recording and slides download.

Published in: Software, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
281
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
7
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Webcast: Implementing Microsoft Design Guidelines with CodeIt.Right"

  1. 1. Microsoft Design Guidelines with CodeIt.Right 6/3/2014 http://submain.com/webcasts/microsoft-design-guidelines-with-codeit.right/ for the webcast recording and slides download
  2. 2. Webcast Housekeeping 6/3/2014 Audio  Connect viaVoIP  Plug in a headset or turn up your speakers  Select “Headset/Mic” inAudio 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 Copyright © SubMain 2014 2
  3. 3. Introduction Presenter David McCarter Microsoft MVP (g)host Serge Baranovsky Principal, SubMain 6/3/2014 Copyright © SubMain 2014 3
  4. 4. David McCarter dotnetdave@live.com  C# Microsoft MVP  Developer/ Architect/ Consultant & Professional Code Reviewer  RockThe Nation ConferenceTour  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 @realdotnetdave davidmccarter Copyright © SubMain 2014 4
  5. 5. Why We Need Coding Standards (Guidelines) 6/3/2014 Copyright © SubMain 2014 5
  6. 6. Benefits  Code Clarity/Easier to Understand  Easier to Maintain  Reduce Bugs  SimplifyCode 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
  7. 7. 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
  8. 8. Why Coding Standards Fail 35% 23% 26% 10% 6% Developers kept forgetting to abide the guidelines Resistance among the team members Couldn't get a concensus on which standard to follow Management thought is was too expensive and not worth the investment Other 6/3/2014 Source: SubMain survey of developers and teams Copyright © SubMain 2014 8
  9. 9. Implement Coding Standards 6/3/2014 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 Copyright © SubMain 2014 9
  10. 10. Microsoft Design Guidelines Overview 6/3/2014 Copyright © SubMain 2014 10
  11. 11. 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# andVB 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
  12. 12. Categories  Naming Guidelines  Naming assemblies, namespaces, types, and members in class libraries  Type Design Guidelines  Using static and abstract classes, interfaces, enumerations, structures, and other types  Member Design Guidelines  Designing and using properties, methods, constructors, fields, events, operators, and parameters  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  Design Guidelines for Exceptions  Designing, throwing, and catching exceptions  Usage Guidelines  Using common types such as arrays, attributes, and collections, supporting serialization, and overloading equality operators  Common Design Patterns  Choosing and implementing dependency properties and the dispose pattern Copyright © SubMain 2014 12
  13. 13. 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
  14. 14. 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
  15. 15. Microsoft Design Guidelines 6/3/2014 Copyright © SubMain 2014 15
  16. 16. 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  <Company>.(<Product>|<Technology>)[.<Feature>][.<Subnamespace>]  Microsoft.Advertising.Mobile.UI  dotNetTips.Utility.Portable.Windows.Extensions Don’t forget about spelling of types! Can’t be changed (easily) after going into production. 6/3/2014 Copyright © SubMain 2014 16
  17. 17. Type Design Guidelines Leave at default type of Int32 Enum default value  Use the value 0 and set it to a “not chosen” value 6/3/2014 Public Enum WorkItemStatus Undetermined Completed Queued Executing Aborted End Enum 0 value Copyright © SubMain 2014 17
  18. 18. Member Design Guidelines Do not call code from constructor  Only set parameters Incorrect 6/3/2014 public class FileCache { public FileCache() { var cacheDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); if (Directory.Exists(cacheDir) == false) { Directory.CreateDirectory(cacheDir); } } } Copyright © SubMain 2014 18
  19. 19. Member Design Guidelines Do not call code from constructor  Only set parameters Correct 6/3/2014 public class FileCache { public string FilePath {get; private set}; public FileCache(string path) { this.FilePath = path; } } No code called Copyright © SubMain 2014 19
  20. 20. Designing for Extensibility SealedClasses  Don’t seal classes unless they are:  Static class  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 public sealed class Person {} Copyright © SubMain 2014 20
  21. 21. Design Guidelines for Exceptions Use the “newer”TryParse method on value types to avoid Exceptions 6/3/2014 DateTime dateValue if (DateTime.TryParse("11/11/14", out dateValue)) { Console.WriteLine("{0}).", dateValue); } else { Console.WriteLine("Unable to parse string."); } Copyright © SubMain 2014 21
  22. 22. Usage Guidelines Overload Equality & Hashtag Operators onTypes 6/3/2014 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; } } Copyright © SubMain 2014 22
  23. 23. Common Design Patterns 6/3/2014 using(var sqlDataReader = new SqlDataReader) { //SqlDataReader code goes here using(var connection = new SqlConnection) { //SqlConnection code goes here using(var BMSConnection = new SqlConnection) { //SqlConnection codes here } } }  Make sure you call Dispose on types that implement IDisposable!  Can create virtual memory leaks • Use the “using” statement Calls Dispose on BMSConnection Calls Dispose on connection Calls Dispose on sqlDataReader Copyright © SubMain 2014 23
  24. 24. Common Design Patterns - continued 6/3/2014 public class Base: IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // Free other state (managed objects) } } ~Base() { Dispose (false); } } • Implement IDisposable type • To ensure resources are cleaned up SignalsGarbageCollector GarbageCollectorWill Call Copyright © SubMain 2014 24
  25. 25. Notes forVB Developers Enable Object Strict  Insures strict object checking is on… just like it always is on in C# NO Goto statements! Use Exit statements  Exit Do  ExitWhile  Exit For  Exit Sub, Function 6/3/2014 Dim sum as Integer Dim number as Integer Do number = number + 1 sum = sum + number If number = 100 Exit Do End If Loop Copyright © SubMain 2014 25
  26. 26. And not onlyVB Developers Use Case instead of chains of If statements 6/3/2014 If value = 1 Then ‘’ Do work Else If value = 2 Then ‘’ Do Work Else If value = 3 Then ‘’ Do Work End If Select Case value Case 1 ‘’ Do work Case 2 ‘’ Do work Case 3 ‘’ Do work End Select SelectCase  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 Copyright © SubMain 2014 26
  27. 27. Refactoring to Patterns - CodeIt.Right 6/3/2014 Copyright © SubMain 2014 27
  28. 28. 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
  29. 29. Asynchronous Programming Microsoft Async – originally designed for EAP – “event- based pattern” – no more, don’t do that! Current Microsoft Async implementation isTAP – “task- based async pattern” Best practices – useTAP not EAP  Don’t create “Async Sub” methods (aka void-returning asyncs) except for top-level event handlers  Call an API that returns aTask? Almost always await it either immediately or later  Async methods should have the suffix “Async” and returnTask orTask<T>  Async method contains only one await operator? (“return await <expr>”) then “return <expr>” and make your method non-async Easy way to still shoot yourself in the foot! 6/3/2014 Copyright © SubMain 2014 29
  30. 30. 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 returnTask orTask<T>  Async method - avoid "out" and "ref" parameters  Async method - await for completion  Await statement - method should be async  Async method - call Start on theTask  Async method - do not useTask.Yield  Async method - do not useTask.Wait  Async method should not be Sub  Async method parameters should be the same to synchronous counterpart  Async method - transform to non-async if simple 6/3/2014 Copyright © SubMain 2014 30
  31. 31. ASP.NET/Security  Do not disable custom errors  Disable anonymous access  EnableEventValidation should beTrue  ValidateRequest should beTrue  ViewStateEncryptionMode should be Always  EnableViewStateMac should beTrue  EnableViewState should beTrue  Compilation Debug should be False  Form authentication should not contain credentials  Disable form authentication EnableCrossAppRedirects  Form authentication RequireSSL should beTrue  Form authentication SlidingExpiration should be False  Http cookies HttpOnlyCookies should beTrue  Http cookies RequireSSL should beTrue  Trace should be disabled  Role manager CookieProtection should beAll  Role manager CookieSlidingExpiration should be False  Page EnableViewStateMac should beTrue  Page EnableEventValidation should beTrue  Http runtime EnableHeaderChecking should beTrue 6/3/2014  Custom error DefaultRedirect should be specified  Always define a global error handler  PageValidateRequest should beTrue  PageViewStateEncryptionMode should beAlways  Form authentication Protection should beAll  Avoid the DataBinder.Eval method  Avoid the Page.DataBind method  Avoid setting theAutoPostBack property toTrue  Do not use deprecated properties of Response object  Do not use SaveAs method to store uploaded files  MVC controller action -> UseValidateAntiforgeryTokenAttribute  MVC controller action -> Enable request validation  Review deny and permit only usage  Review visible event handlers  GetObjectData is not marked with SecurityPermissionAttribute  Secure serialization constructors  Should have identical link demands to base method  Wrap vulnerable finally clauses in outer try  Type, Security transparent code should not assert  and more – 54 in total! No worries – we’ve got you covered! Just the ASP.NET/Security category: Copyright © SubMain 2014 31
  32. 32. 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
  33. 33. Q&A Questions? Email - customer-service@submain.com Video - submain.com/codeit.right/video Download the free CodeIt.Right trial at submain.com/codeit.right Contact David McCarter: dotnetdave@live.com 6/3/2014 1 (800) 936-2134 Copyright © SubMain 2014 33 http://submain.com/webcasts/microsoft-design-guidelines-with-codeit.right/ for the webcast recording and slides download
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×