SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
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
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
Introduction
Presenter
David McCarter
Microsoft MVP
(g)host
Serge Baranovsky
Principal, SubMain
6/3/2014 Copyright © SubMain 2014 3
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
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 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
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
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
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# 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
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
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
 <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
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
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
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
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
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
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
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
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
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
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
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 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
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
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
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
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

Contenu connexe

Dernier

Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 

Dernier (20)

Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 

En vedette

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 

En vedette (20)

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 

Webcast: Implementing Microsoft Design Guidelines with CodeIt.Right

  • 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. 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. Introduction Presenter David McCarter Microsoft MVP (g)host Serge Baranovsky Principal, SubMain 6/3/2014 Copyright © SubMain 2014 3
  • 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. Why We Need Coding Standards (Guidelines) 6/3/2014 Copyright © SubMain 2014 5
  • 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. 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. 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. 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. Microsoft Design Guidelines Overview 6/3/2014 Copyright © SubMain 2014 10
  • 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. 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. 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. 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. Microsoft Design Guidelines 6/3/2014 Copyright © SubMain 2014 15
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Refactoring to Patterns - CodeIt.Right 6/3/2014 Copyright © SubMain 2014 27
  • 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. 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. 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. 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. 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. 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