29
VS 2012 Sandeep Joshi Visual Studio ALM MVP [email protected] @sandeepmvp (Blog at : http://blogs.msdn.com/sajoshi) Ensure and enable Quality

Ensure code quality with vs2012

Embed Size (px)

DESCRIPTION

This slide covers Code Quality with VS2012.

Citation preview

Page 1: Ensure code quality with vs2012

VS 2012

Sandeep JoshiVisual Studio ALM [email protected]@sandeepmvp (Blog at : http://blogs.msdn.com/sajoshi)

Ensure and enable Quality

Page 2: Ensure code quality with vs2012

PresenterSandeep JoshiProfile

Sandeep Joshi is a passionate technologist with 12+ years of experience in enterprise application development and design. His core focus is Application Lifecycle Management and he is a Microsoft Most Valuable Professional (MVP) for Visual Studio ALM.

He contributes to various user groups and communities in Singapore & India and speaks at major technology events. He writes about Visual Studio ALM, Windows 8 and .NET at MSDN & his blog.

He can be reached at [email protected].

Page 3: Ensure code quality with vs2012

AgendaI. Quality Demystified

II. Code Analysis in VS2012

III. Code Metrics and Maintainability

IV. Code Coverage

V. Code Clone Analysis

VI. Q & A

Page 4: Ensure code quality with vs2012

Quality - Demystified Quality is often non measurable

‘Code that smells’

Proper Solution vs. Quick Fix

Better crafted software

Drive quality ‘upstream’

By following proven processes

By Behavioral Changes

Page 5: Ensure code quality with vs2012

Drive Quality Upstream

Development

Test

Release

Software Phase

Cost o

f Bu

gs

Page 6: Ensure code quality with vs2012

Drive Quality Upstream

Development

Test

Release

Software Phase

Cost o

f Bu

gs

Page 7: Ensure code quality with vs2012

Drive Quality Upstream Find Problems before you make them Code Analysis Code Metrics Code Clone Analysis

Don’t let bugs out of your sight Unit Testing and Code Coverage Test Impact Analysis Coded UI Tests Performance Tests

Don’t let bugs get into your builds Gated Check-In

Page 8: Ensure code quality with vs2012

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'

Page 9: Ensure code quality with vs2012

Make Your Code Secureprotected 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.    

Page 10: Ensure code quality with vs2012

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)));

} }

Page 11: Ensure code quality with vs2012

Make Your Apps Reliable

Page 12: Ensure code quality with vs2012

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

Page 13: Ensure code quality with vs2012

Make Your Apps Reliable

public void DisplayMultiplyResult() {

EquationBuilder equation = new EquationBuilder

(left, EquationBuilder.EquationOperator.Multiply, right);

ResultsBox.Text = equation.ToString(); }

Page 14: Ensure code quality with vs2012

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

Page 15: Ensure code quality with vs2012

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

Page 16: Ensure code quality with vs2012

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

Page 17: Ensure code quality with vs2012

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

Page 18: Ensure code quality with vs2012

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'.

Page 19: Ensure code quality with vs2012

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

Page 20: Ensure code quality with vs2012

Enabling Code Analysis in VS2012

demo

Page 21: Ensure code quality with vs2012

Code Analysis Best PracticesFocus on the most critical issues

Run Code Analysis with Microsoft Minimum Recommended Rules and dial it up from there

Get into a known stateFix or Baseline and track deferred work (create work items)

Use Code Analysis early and oftenPrevent new issues

Set up Code Analysis check-in policyDon’t defer potential security issuesEnable Code Analysis in Team Builds

Page 22: Ensure code quality with vs2012

Code Metrics and Maintainability

Set of software measures that provide Better insight of codeIndicates which types and/or methods should be reworked or more thoroughly tested

Offers details on:Maintainability Index Cyclomatic ComplexityClass CouplingLines of CodeDepth of Inheritance

  Maintainability Index

Cyclomatic Complexity

Class Coupling

Green > 60 < 10 < 20

Yellow 40 - 60 10 - 15  

Red < 40 > 15 > 20

Page 23: Ensure code quality with vs2012

Code Coverage

Code coverage has been a very useful metric in detecting the efficacy of your unit tests.

tells if your code is being adequately exercised via your tests

Visible changes in VS2012No .testsettings overheads for code coverageSupport in Visual Studio’s Test Explorer windowNative is a first class citizenThe .coverage file is leaner and meanerSupport in the new test executor command line (vstest.console.exe)Support in Team Build

Page 24: Ensure code quality with vs2012

Code Metrics and Code Coverage in VS2012

demo

Page 25: Ensure code quality with vs2012

Code Clone AnalysisCode clones are separate fragments of code that are very similarVisual Studio can help you find

code clones so that you can refactor themclones of a specific fragment, or find all clones in your solutionfragments which differ in the names of variables and parameters, and in which some statements have been rearranged

The code clone analyser searches for duplicate code in Visual C# and Visual Basic projects throughout your Visual Studio solution.

Page 26: Ensure code quality with vs2012

Code Clone Analysis in VS2012

demo

Page 27: Ensure code quality with vs2012

Q & A

Call to actionInstall Visual Studio 2012 & .NET Framework 4.5

You can even use it for your Production environment & get support from Microsoft

Bake code quality right into estimation

Page 28: Ensure code quality with vs2012

Related Content

http://msdn.microsoft.com/en-us/vs11trainingcourse_makingdevsmoreproductive_topic2

http://msdn.microsoft.com/en-us/vs11trainingcourse_makingdevsmoreproductive_topic7

http://msdn.microsoft.com/en-us/vs11trainingcourse_makingdevsmoreproductive_topic3

http://msdn.microsoft.com/en-us/vs11trainingcourse_makingdevsmoreproductive_topic4

http://msdn.microsoft.com/en-us/vs11trainingcourse_makingdevsmoreproductive_topic5

http://msdn.microsoft.com/en-us/vs11trainingcourse_makingdevsmoreproductive_topic6

Page 29: Ensure code quality with vs2012

© 2012 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.