ravs kaur test lead microsoft corporation tl60
TRANSCRIPT
Improving Code Quality With Code Analysis
Ravs KaurTest LeadMicrosoft Corporation
TL60
Agenda
Benefits of Code Analysis Integrating into team’s workflow Expanding Code Analysis Best Practices Q & A
Drive Quality Upstream
Development
Test
Release
Software Phase
Cost of Bugs
Drive Quality Upstream
Development
Test
Release
Software Phase
Cost of Bugs
Make Your Code Secure
Windows SQL Server 2000
Exchange Server
0
10
20
30
40
50
60
70
Number of Security Bul-letins Pre SDL (Year: < 2000)
Windows
SQL S
erver 2
000
Exchan
ge Se
rver
010203040506070
Number of Security Bul-letins Post SDL (Year: >2003)
Source: http://msdn.microsoft.com/en-us/library/ms995349.aspx
Make Your Code Secure
Source: http://blogs.technet.com/security/archive/2008/05/14/microsoft-vista-vs-windows-xp-sp2-vulnerability-report-2007.aspx
Make Your Code Secure
void LogError(wchar_t *component, wchar_t *error){ wchar_t buffer[256]; swprintf_s(buffer, sizeof(buffer), L"%s: %s\n",
component, error); AppendMessageToLog(buffer);}
void LogError(wchar_t *component, wchar_t *error){ wchar_t buffer[256]; swprintf_s(buffer, _countof(buffer),
L"%s: %s\n", component, error); AppendMessageToLog(buffer);}
warning C6057: Buffer overrun due to number of characters/numberof bytes mismatch in call to 'swprintf_s'
Make Your Code Secure
protected void Page_Load(object sender, EventArgs e) { string userName = Request.Params["UserName"]; string commandText = "SELECT * FROM Contacts WHERE ContactFor = '" + userName + "'"; SqlCommand command = new SqlCommand
(commandText, this.connection);
SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { ListBox1.Items.Add
(new ListItem (reader.GetString(0)));
} }
Make Your Code Secure
protected void Page_Load(object sender, EventArgs e) { string userName = Request.Params["UserName"]; string commandText = "SELECT * FROM Contacts WHERE ContactFor = '" + userName + "'"; SqlCommand command = new SqlCommand
(commandText, this.connection);
SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { ListBox1.Items.Add
(new ListItem (reader.GetString(0)));
} }
CA2100 : Microsoft.Security : The query string passed toSystem.Data.SqlClient.SqlCommand..ctor in Page_Load could contain the following variables this.get_Request().get_Params().get_Item(...). If any of these variables could come from user input, consider using a stored procedure or a parameterized SQL query instead of building the query with string concatenations.
Make Your Code Secure
protected void Page_Load(object sender, EventArgs e) {
string userName = Request.Params["UserName"]; string commandText = "SELECT * FROM Contacts
WHERE ContactFor = @userName";
SqlCommand command = new SqlCommand
(commandText, connection); command.Parameters.Add(new SqlParameter
("@userName", userName)); SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) { ListBox1.Items.Add
(new ListItem(reader.GetString(2)));
} }
Make Your Apps Reliable
public class EquationBuilder { public override string ToString() { string result = CalculateResult().ToString(); switch (operatorKind) { case EquationOperator.Add: return left + " + " + right +
" = " + result; case EquationOperator.Subtract: return left + " - " + right +
" = " + result; default: throw new NotImplementedException(); }
} …
}
Make Your Apps Reliable
Make Your Apps Reliable
public void DisplayMultiplyResult() {
EquationBuilder equation = new EquationBuilder
(left, EquationBuilder.EquationOperator.Multiply, right);
ResultsBox.Text = equation.ToString(); }
public class EquationBuilder { public override string ToString() { string result = CalculateResult().ToString(); switch (operatorKind) { case EquationOperator.Add: return left + " + " + right +
" = " + result; case EquationOperator.Subtract: return left + " - " + right +
" = " + result; default: throw new NotImplementedException(); }
} …
}
CA1065 : Microsoft.Design : 'Class1.ToString()' creates an exception of type 'NotImplementedException'. Exceptions should not be raised inthis type of method. If this exception instance might be raised, change this method's logic so it no longer raises an exception.
Make Your Apps Reliable
public class EquationBuilder { public override string ToString() { string result = CalculateResult().ToString(); switch (operatorKind) { case EquationOperator.Add: return left + " + " + right +
" = " + result; case EquationOperator.Subtract: return left + " - " + right +
" = " + result; default:
Debug.Assert(false, "Unexpected operator!");
return "Unknown"; }
} …
}
Make Your Apps Reliable
void TraceInformation(char *message, int &totalMessages)
{ // Only print messages if there are
// more than 100 of them or the trace // settings are set to verbose
if (TRACE_LEVEL > 3 ||
totalMessages++ > 100) { printf(message); } }
Make Your Apps Reliable
warning C6286: (<non-zero constant> || <expression>) is always a non-zero constant. <expression> is never evaluated
and might have side effects
void TraceInformation(char *message, int &totalMessages)
{ // Only print messages if there are
// more than 100 of them or the trace // settings are set to verbose totalMessages++;
if (TRACE_LEVEL > 3 || totalMessages > 100)
{ printf(message); } }
Make Your Apps Reliable
public FldBrwserDlgExForm(): SomeSystem.SomeWindows.SomeForms.SomeForm {
this.opnFilDlg = new opnFilDlg(); this.fldrBrwsrDlg1 = new fldrBrwsrDlg1(); this.rtb = new rtb(); this.opnFilDlg.DfltExt = "rtf"; this.desc = "Select the dir you want to use as default"; this.fldrBrwsrDlg1.ShowNewFldrBtn = false; this.rtb.AcpectsTabs = true;
}
Make Your Code Maintainable
CA1704 : Microsoft.Naming : Correct the spelling of 'Acpects' in member name 'rtb.AcpectsTabs‘
CA1704 : Microsoft.Naming : Correct the spelling of 'Brwser' in type name 'FldBrwserDlgExForm'.
CA1704 : Correct the spelling of 'Brwsr' in type name 'fldrBrwsrDlg1'.
CA1704 : Correct the spelling of 'Btn' in member name 'fldrBrwsrDlg1.ShowNewFldrBtn’
CA1704 : Correct the spelling of 'desc' in member name 'FldBrwserDlgExForm.desc'
CA1704 : Correct the spelling of 'Dflt' in member name 'opnFilDlg.DfltExt'
CA1704 : Correct the spelling of 'Dlg' in type name 'FldBrwserDlgExForm'.
CA1704 : Correct the spelling of 'Fil' in type name 'opnFilDlg'.
CA1704 : Correct the spelling of 'Fld' in type name 'FldBrwserDlgExForm'.
CA1704 : Microsoft.Naming : Correct the spelling of 'opn' in type name 'opnFilDlg'.
CA1704 : Microsoft.Naming : Correct the spelling of 'rtb' in type name 'rtb'.
public class FolderBrowserDialogExampleForm : System.Windows.Forms.Form { // Constructor. public FolderBrowserDialogExampleForm() { this.openFileDialog1 = new OpenFileDialog(); this.folderBrowserDialog1 = new FolderBrowserDialog(); this.richTextBox1 = new RichTextBox(); this.openFileDialog1.DefaultExt = "rtf"; // Set the help text description this.folderBrowserDialog1.Description =
"Select the directory that you want to use as the default.";
// Do not allow the user to create new files this.folderBrowserDialog1.ShowNewFolderButton = false;
this.richTextBox1.AcceptsTab = true; }
}
Make Your Code Maintainable
Code Analysis In VS Team System
Managed C++
C#
VB T-SQL
Native C
Native C++
Code Analysis in
VSTS
Integrating Code Analysis Into Your Team's Workflow
demo
Run Code Analysis Fix or baseline Create work items for future tracking Set up Code Analysis check-in policy Set up Team Build
with Code Analysis enabled
Set Code Analysis For Your Team
Customize your rule set Choose multiple rule sets Fine tune your existing rule set
Focus on areas of higher risk Calculate Code Metrics to track
overall maintainability
Expanding Analysis
Customizing Analysis
Managed Source Code
Assemblies
Analysis Object Model
Rules
Annotations In Native C/C++
Document assumptions and expectations Explicitly state the contracts between
implementations and clients Code Analysis leverages annotations
for more accurate analysis
Annotations In Native C/C++
LinkedList* AddTail (LinkedList* node, int value)
{ LinkedList *newNode = NULL; // finds the last node while ( node->next != NULL ) { node = node->next; } // appends the new node newNode = AllocateNode(); newNode->data = value; newNode->next = 0; node->next = newNode; return newNode; }
Annotations In Native C/C++
LinkedList* AddTail ([Pre(Null=Maybe)] LinkedList* node,
int value) { LinkedList *newNode = NULL; // finds the last node while ( node->next != NULL ) { node = node->next; } // appends the new node newNode = AllocateNode(); newNode->data = value; newNode->next = 0; node->next = newNode; return newNode; }
Annotations In Native C/C++
LinkedList* AddTail ([Pre(Null=Maybe)] LinkedList* node,
int value) { LinkedList *newNode = NULL; // finds the last node while ( node->next != NULL ) { node = node->next; } // appends the new node newNode = AllocateNode(); newNode->data = value; newNode->next = 0; node->next = newNode; return newNode; } warning C6011: Dereferencing NULL pointer 'node': Lines: 35, 38
Annotations In Native C/C++
[returnvalue:Post(Null=Maybe)] LinkedList* AllocateNode(); LinkedList* AddTail (LinkedList* node,
int value) { LinkedList *newNode = NULL; // finds the last node while ( node->next != NULL ) { node = node->next; } // appends the new node newNode = AllocateNode(); newNode->data = value; newNode->next = 0; node->next = newNode; return newNode; }
Annotations In Native C/C++
[returnvalue:Post(Null=Maybe)] LinkedList* AllocateNode(); LinkedList* AddTail (LinkedList* node,
int value) { LinkedList *newNode = NULL; // finds the last node while ( node->next != NULL) { node = node->next; } // appends the new node newNode = AllocateNode(); newNode->data = value; newNode->next = 0; node->next = newNode; return newNode; }
warning C6011: Dereferencing NULL pointer 'newNode': Lines: 35, 38, 44, 45
Best Practices
Focus on the most critical issues Run Code Analysis with Microsoft Minimum
Recommended Rules and dial it up from there Get into a known state
Fix or Baseline and track deferred work Use Code Analysis early and often Prevent new issues
Set up Code Analysis check-in policy Don’t defer potential security issues Enable Code Analysis in Team Builds
Related SessionsSession Title Speaker Day Time Location
TL47 Visual Studio Team System: A Lap Around VSTS 2010 Cameron Skinner 10/27 11:00 AM – 12:15PM Room 153
TL03 Microsoft Visual Studio Team System: Software Diagnostics and Quality for Services
Habib Heydarian; Justin Marks
10/27 03:30 PM – 04:45 PM Room 515A
PC58 Framework Design Guidelines Brad Abrams, Krzysztof Cwalina
10/27 05:15PM – 6:30 PM Room 403AB
TL59 Visual Studio Debugger Tips & Tricks John Cunningham 10/28 12:45PM – 01:30 PM Room 409A
TL61 Panel: The Future of Unit Testing Euan Garden, Jim Newkirk, Peter Provost, Nikolai Tillmann
10/29 12:00 PM – 12:45 PM Room 406A
TL24 Improving .NET Application Performance and Scalability
Steve Carroll;Ed Glas
10/29 01:15 PM – 02:30 PM Room 153
TL51 Research: Contract Checking and Automated Test Generation with Pex
Mike BarnettNikolai Tillmann
10/30 08:30 AM : 9:45AM Room 403
VSTS 2010 Hands On Labs
HOL Code Title
TLHOL07 VSTS 2010: Project Planning, Management, and Design
TLHOL08 VSTS 2010: Architecture Tools
TLHOL09 VSTS 2010: Team Foundation Server
TLHOL10 VSTS 2010: Software Quality
TLHOL11 VSTS 2010: Diagnostics and Performance
Forums http://social.msdn.microsoft.com/forums/en-U
S/vstscode/threads/ Code Analysis and Code Metrics Blogs
http://blogs.msdn.com/fxcop CTP Walkthrough Feedback
Email: [email protected]
Other Resources
Evals & Recordings
Please fill
out your
evaluation for
this session at:
This session will be available as a recording at:
www.microsoftpdc.com
Q & A
(USE THIS SPACE FOR PRODUCT LOGOS WHEN WHITE BACKGROUND
IS EQUIRED)DELETE WHITE RECTANGLES IF NOT
BEING USED
© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market
conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
TL60