Continuous Integration in NET Marcin Kawalerowicz

naamiburo 44 views 82 slides Apr 10, 2025
Slide 1
Slide 1 of 82
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82

About This Presentation

Continuous Integration in NET Marcin Kawalerowicz
Continuous Integration in NET Marcin Kawalerowicz
Continuous Integration in NET Marcin Kawalerowicz


Slide Content

Continuous Integration in NET Marcin
Kawalerowicz pdf download
https://ebookgate.com/product/continuous-integration-in-net-
marcin-kawalerowicz/
Get Instant Ebook Downloads – Browse at https://ebookgate.com

Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
Continuous Improvement in the Mathematics Classroom
Jenkins
https://ebookgate.com/product/continuous-improvement-in-the-
mathematics-classroom-jenkins/
ebookgate.com
Russia China Relations in the Post Crisis International
Order 1st Edition Marcin Kaczmarski
https://ebookgate.com/product/russia-china-relations-in-the-post-
crisis-international-order-1st-edition-marcin-kaczmarski/
ebookgate.com
Haskalah and Hasidism in the Kingdom of Poland A History
of Conflict Marcin Wodzinski
https://ebookgate.com/product/haskalah-and-hasidism-in-the-kingdom-of-
poland-a-history-of-conflict-marcin-wodzinski/
ebookgate.com
Continuous Casting 1st Edition Wolfgang Schneider
https://ebookgate.com/product/continuous-casting-1st-edition-wolfgang-
schneider/
ebookgate.com

Pro ASP NET Web API HTTP Web Services in ASP NET 1st
Edition Tugberk Ugurlu
https://ebookgate.com/product/pro-asp-net-web-api-http-web-services-
in-asp-net-1st-edition-tugberk-ugurlu/
ebookgate.com
Intelligence Integration in Distributed Knowledge
Management Dariusz Krol
https://ebookgate.com/product/intelligence-integration-in-distributed-
knowledge-management-dariusz-krol/
ebookgate.com
Improvisational Design Continuous Responsive Digital
Communication Suguru Ishizaki
https://ebookgate.com/product/improvisational-design-continuous-
responsive-digital-communication-suguru-ishizaki/
ebookgate.com
B2B Integration Gunjan Samtani
https://ebookgate.com/product/b2b-integration-gunjan-samtani/
ebookgate.com
Mastering ASP Net with VB Net 1st Edition A. Russell Jones
https://ebookgate.com/product/mastering-asp-net-with-vb-net-1st-
edition-a-russell-jones/
ebookgate.com

Continuous
Integration
in .NET



MARCIN KAWALEROWICZ
CRAIG BERNTSON












MANNING
Greenwich
(74° w. long.)

brief contents

PART 1

MAKE IT HAPPEN ...........................................................1

1

■ Understanding continuous integration 3
2 ■ Setting up a source control system 29
3
4 ■
■ Automating the build process
Choosing the right CI server
66
89
5 ■ Continuous feedback 120
6 ■ Unit testing continuously integrated code 144

PART 2

EXTEND IT ................................................................165

7


8





Performing integration, system, and
acceptance testing 167
Analyzing the code 199
PART 3

SMOOTH AND POLISH IT ............................................225

9
10


■ Generating documentation
Deployment and delivery
227
240
11
12 ■
■ Continuous database integration
Extending continuous integration 260
276


vii

contents

preface xv
acknowledgments xvii
about this book xix
about the authors xxii
about the cover illustration xxiii

PART 1 MAKE IT HAPPEN ...............................................1

1

Understanding continuous integration 3
1.1 What does it mean to integrate continuously?



4
Defining continuous integration 4

CI and your
development process 5

Do I need to build with every
change? 7

Overcoming team objections 8

It’s all
about reducing risk 10
1.2
1.3 A simple Hello World–type CI example 12
CI tools 13
Essential tools 14

Code-analysis tools 18
Testing tools 20

Other tools 20
1.4 A project for CI: leasing/credit calculator 20


1.5
Calculation core
Summary
27
21

Calculators 26


ix

x


CONTENTS

2

Setting up a source control system 29
2.1 Choosing the right source control system for you



30
Benefits of source control systems 31

Source control
aspects to consider 32
2.2 Setting up a Subversion source control server 35
Installing VisualSVN Server 35

Creating users
and groups 37

Creating the repository 37
Keeping a healthy repository 39
2.3 TortoiseSVN and working with the repository 42
Subversion client: TortoiseSVN 42

Creating a
working copy 43

Committing changes 45

Updating
and committing files 48

Referencing 50
2.4 Setting up Team Foundation Server 53
Installing TFS 2010 53

TFS collections 55
Using Visual Studio Team Explorer 58

Managing TFS
source control 61

Locking and shelving 63
2.5 Summary 64

3

Automating the build process 66
3.1 Build automation 67
Make and its children 67

It’s not an Ant 68
3.2 The Microsoft worker: MSBuild 70
First encounters with MSBuild 71

Using predefined tasks to
extend an MSBuild script 73

MSBuild Community Tasks 76
3.3 The happy couple: Visual Studio and MSBuild 78
Examining a project file 79

Examining the
solution file 81

Starting an MSBuild script with
Visual Studio 82
3.4 Extending MSBuild by writing and using custom tasks 83

3.5
Implementing a custom task
Summary
88
84

Putting it all together 86

4

Choosing the right CI server 89
4.1 A quick review of the CI process 90
4.2 Examining the CI server possibilities 92
Manual integration build or your own CI server? 92
CI servers for .NET 94

CONTENTS


xi

4.3

Continuous integration with CruiseControl.NET

95
Starting with CCNet 96

Configuring CCNet 97
Triggering builds 100
4.4 Continuous integration with TeamCity 102
Running TeamCity 102

Configuring a project 104
Pre-tested commit 110
4.5 Continuous integration with Team Foundation
Server 2010 113
TFS and build controllers 113

Configuring TFS
build agents 115

TFS build configuration 116
4.6 Summary 119

5

Continuous feedback 120
5.1 Knowing the state of your CI process 121
5.2 Continuous feedback with CruiseControl.NET 122
The CCNet Web Dashboard 122

Getting feedback
with CCTray 126

Alternative feedback
mechanisms with CCNet 128
5.3 Continuous feedback with TeamCity 129
TeamCity web feedback 130

The TeamCity Windows Tray
Notifier 132

Alternative notifications with TeamCity 134
5.4 Continuous feedback with Team Foundation Server 135
TFS tray notification 136

Getting build details from
the TFS website 137
with TFS 137

Alternative feedback mechanisms
5.5 Extending build notifications 139
Providing feedback via an LED message board 139
Providing feedback via SMS notifications 142
5.6 Summary 142

6

Unit testing continuously integrated code 144
6.1 Unit testing from a bird’s- eye view 145
6.2 First encounters with unit testing 146
The search for perfect unit test material 147
Testing with NUnit 149
CruiseControl.NET 151


Marrying NUnit with
Examining test coverage 154

xii


CONTENTS

6.3

Microsoft unit testing framework

157
Creating unit tests the Microsoft way 157

Testing on
TFS 2010 160

MSTest in non-TFS environment 161
6.4 Summary 164

PART 2 EXTEND IT.....................................................165
7
Performing integration, system, and acceptance testing 167
7.1 Extending your CI test repertoire 168
Beyond unit tests in CI 169

Involving the customer or
domain expert in the CI testing process 171
right failing 172

Right timing,
7.2 Up close and personal with integration tests in CI 173
Performing integration testing 173

From mocking
to integration testing 176
7.3 Testing the user interface 180
Testing Windows Forms with White 180

Silverlight
test automation 182

Testing a web application with
Selenium 185

Integrating UI tests into the CI process 189
7.4 Acceptance testing with FitNesse 192

7.5
Preparing the FitNesse framework
Summary
197
192

FitNesse and CI 196

8

Analyzing the code 199
8.1 Analyzing object code with FxCop



200
Using Visual Studio Code Analysis 200

Setting up
continuous FxCop code analysis 203
with CI servers 206

Integrating FxCop
8.2 Analyzing C# with StyleCop 209
Using StyleCop 209

Continuous StyleCop analysis 210
8.3 Custom FxCop and StyleCop rules 213
Developing a custom FxCop rule 214

Developing a
custom StyleCop rule 216
into the CI process 217

Incorporating custom rules
8.4 Extending code analysis 218
Static analysis with NDepend 218
duplication with TeamCity 223

Analyzing code
8.5 Summary 224

CONTENTS


xiii

PART 3 SMOOTH AND POLISH IT ................................225

9

Generating documentation 227
9.1 XML documentation 228
Common XML documentation tags 228

Formatting text
in XML comments 231
9.2 Sandcastle 233

9.3
Building with Sandcastle
Summary
239
235

Sandcastle in CI 237

10

Deployment and delivery 240
10.1 Creating an installer for your Windows application
Creating a Microsoft Installer package in Visual Studio
Continuously creating installation files 243
10.2
Windows Installer XML toolset 244




2 41



241
Creating an installer using WiX 245

Automating WiX
with CI 247
10.3 ClickOnce deployment 248
Creating a ClickOnce deployment 248
in a CI scenario 251

ClickOnce
10.4 Web Deployment Tool 253
Visual Studio 2010 and MS Deploy 254
the build server 256

MS Deploy on
10.5 Summary 258

11

Continuous database integration 260
11.1 What is continuous database integration? 261
11.2
11.3

11.4
Rolling your own continuous database integration
Continuous database maintenance with
RoundhousE 264
Continuous database maintenance with
Visual Studio 266
262
Getting started with database projects 266

Generating test
data 268

Unit testing stored procedures 271

Putting Visual
Studio database maintenance into CI 274
11.5 Summary 275

xiv





12


CONTENTS

Extending continuous integration 276
12.1 Speeding up CI 277
12.2 Seven deadly sins of slow software builds 278
Making a build script drive your build 279

Getting rid of
build-script targets’ side effects 279

Multiplying updated
files 279

Pass-based builds 280

Output in the
source directory 281

Monoliths 281
Bad dependencies 282
12.3 Scaling CI 282
Build-agent theory 282

Scaling TeamCity 283
12.4
12.5 Legal roadblocks 287
Maturity model for CI 288
Building 289

Deploying 290

Testing 291
Reporting 292
12.6 Summary

index
295
293

preface

After completing my master’s degree, I moved from Poland to Germany and began
working as a .NET developer for a company full of experts in … Clarion. The Clarion
folks were developing the company’s flagship—very successful leasing software—and I
was left to do “the rest”: a bit of interfacing with web services (no way to do it from
Clarion at that time), a rewrite of a Pocket PC leasing calculator, a piece of a website
for a customer in Switzerland, and so on.
Over time, I was given more and more small software gems to manage. “How about
introducing a source-control system?” I thought. I was uneasy about the “zip and store
on a share” method my old friends were using. Fortunately, my bosses were open-
minded, and I was given a free hand. I could do whatever I wanted to make my work
life easier. And believe me, there was a lot to change! I started with Visual SourceSafe
and a plug-in for Visual Studio. This made a difference, but I didn’t stop searching.
It was a time of Agile hype. The popularity of test-driven development was increas-
ing, and my adventure with unit testing began. We moved from Visual SourceSafe to
Subversion, and about that time I saw some information about CruiseControl.NET. It
was a
build server. I thought that was cool: all I had to do was write a build script and
check the source into the version-control system, and CruiseControl.NET would
detect my changes, pull the source, and perform the build; it would include the tests
automatically, deploy the created bits to the test server, and tell me right away if some-
thing was wrong. I knew this continuous integration (CI) process would change the
way software was developed on my team. All the pains of late consolidation were allevi-




xv

xvi


PREFACE

ated: we had a fairly ready, tested piece of software every time we checked in to the
source- control system.
I had to learn MSBuild to write my build scripts. The learning curve wasn’t too
steep; soon, I had a custom-built script for every project we worked on. I was lucky to
have virtually no hardware limits from my bosses. I got a fairly old server and created
my first build machine. Boy, was it cool to see all the “yet another successful build”
messages from the Windows tray-notification tool.
From day one, I was a fan of and a believer in the CI concept. I’m strongly con-
vinced that it was the sole attraction that kept me in the Chaos Developer Club in
those days. Now I’m running my own company, and one of the most important tools
in my repertoire is the CI server.
Back in 2007, I wrote an article about CI for a Polish computer magazine. It reso-
nated in the community and was generally well received. Sometime after that, a
friend suggested that the topic was worth more exploration —perhaps in a book. I
couldn’t have agreed more. I ran the idea by a few Polish publishers, but they all
said the topic was too specific for the Polish market. “Well,” I thought, “if the Polish
market is too narrow, how about the global market?” It was the first time I’d consid-
ered writing the book in English. I was concerned because English isn’t my mother
tongue. I knew the language well enough to read just about anything written in Eng-
lish, but would I be able to write in it? With the support of Manning, and Craig as
coauthor, I decided to give it a try. You are holding the result!
M
ARCIN KAWALEROWICZ

acknowledgments

Writing a book is a long and arduous process. Many people were involved and we’re
sure to forget someone here. Our sincere thanks to all of you.
We must acknowledge the entire staff at Manning, especially Emily Macel who
guided us through most of the writing process, and Michael Stephens for his support
and patience when things got tough. There were others, including Maureen Spencer,
Karen Tegtmeyer, Christina Rudloff, Tiffany Taylor, Katie Tennant, Mary Piergies, and
Dennis Dalinnik, who helped along the way, and of course, publisher Marjan Bace
who green-lighted the project.
Thanks to all the technical reviewers listed here and to Margriet Bruggeman and
Nikander Bruggeman who did a final technical proofread of the manuscript shortly
before it went to press. Your valuable feedback made this book better: Erik D. Lane,
Craig Smith, Rob Reynolds, Aleksey Nudelman, Darren Neimke, Dave Corun, Jonas
Bandi, Derik Whittaker, Sebastien Vaucouleur, Amos Bannister, Philippe Vialatte, Eric
C. A. Swanson, Marc Gravell, Anil Radhakrishna, and Lester Lobo.
Finally, we would like to thank all of the readers of Manning’s Early Access Pro-
gram (MEAP) who added comments and corrections to our manuscript via the Author
Online forum.

Marcin Kawalerowicz
I would like to thank the people who made me the developer I am today: Pawe?
Jackowski (without you, I wouldn’t have become a software developer and this
book wouldn’t have been written), Jacek Jarczak (my long- time friend and business



xvii

xviii


ACKNOWLEDGMENTS

associate), Bernhard Korn (a man I’ve learned a lot from), and Harald Cich (my
first boss at C.I.C. Software GmbH; his brilliant mind was always open to innova-
tion). Thanks also to Michal Sodomka, Blaz
˙ej Choros´, Mateusz Loskot, Aleksej Kir-
schner, Lukasz Stilger, Tomasz Rospond, and my fellows at CODEFUSION.
Thanks to the people who made me the person I am today: my parents, Bar-
bara and Krzysztof; my lovely wife, Sylwia; and my daughter (born between chap-
ters 8 and 9), Zosia.

Craig Berntson
First and foremost, I need to thank my coauthor. Marcin made the initial contact
with Manning and got the project started. Being almost half a world apart didn’t
help, but we were able to meet briefly in Germany. It’s mostly through his work that
we finally got to the end of this journey.
I had other help with my research and with answers to many questions about
different tools and how things work. David Starr and Richard Hundhausen were
great sounding boards.
Thanks to all the people on the C# and VB.NET Insiders lists for answering my sim-
plest of questions about the CI process in their environments. Also, thanks to the peo-
ple at Microsoft, JetBrains, and ThoughtWorks for making great products.
Finally, a personal thank you to the people close to me: my coworkers and manag-
ers for putting up with hearing me talk about this project; and most of all to Jason,
Johnathan, and especially Laurie for supporting me in this effort.

about this book

Continuous integration is what it is, regardless of whether it’s done in .NET or some
other technology. It’s a set of best practices aimed at easing the integration pains that
arise during the course of a software project. .NET has its own set of tools to make CI
happen, but the basic rules stay the same: use a source-control system, build by issuing
one command, test, analyze, and deploy. Be ready.

Who should read this book?
This book is for developers who want to dive into state-of-the-art CI techniques. It pro-
vides simple guidance on how to create a full CI process with minimal effort and cost.
The book wasn’t written for experienced build masters and old- time CI practitioners,
but we hope they will find some gems of knowledge as well.

Roadmap
The book is divided into three parts:
Part 1 “Make it happen” includes chapters 1-6
Part 2 “Extend it” consists of chapters 7-8
Part 3 “Smooth and polish it” covers chapters 9-12
Marcin wrote chapters 2 through 10. Craig contributed chapters 1, 11, and 12.
Chapter 1 lays the foundation. It describes the CI process and gives you advice
about how to introduce it to your company. We’ll show a simple way to set up a CI pro-
cess using a CMD file.



xix

xx


ABOUT THIS BOOK

Chapter 2 describes the sine qua non for CI: a source-control system. You’ll learn
what the code repository is and how to use it. We’ll help you choose the right tool for
your needs. We’ll describe Subversion and TFS source control as examples of source-
control systems that are ready to be used in CI.
Chapter 3 goes deep into build automation. We’ll describe how to set up a system
that lets you build an entire project using one command. We’ll present MSBuild as our
tool of choice.
In chapter 4, we’ll help you choose a CI server. We’ll describe how to install and set
up CruiseControl.NET, TFS in its basic configuration, and JetBrains TeamCity.
In chapter 5, we’ll examine the responsiveness of CI servers. We’ll look at the feed-
back mechanisms available in these systems, including web- based reports, system tray
notifications, email, and SMS notifications. At the end, you’ll use a USB LED toy to get
immediate feedback from your system.
Chapter 6 describes unit testing and how it’s a characteristic of the CI process.
You’ll use NUnit and MSTest to build a simple test suite, and you’ll integrate the test
results with the CI server. We’ll examine test coverage and sending reports as feedback
to developers. You’ll learn how to mock some of the tests and how doing so affects the
CI process.
In chapter 7, we’ll extend your test repertoire with integration, system, functional,
and acceptance tests. You’ll use various frameworks to test various technologies: White
to test Windows Forms and Silverlight, Selenium to test Web Forms, and FitNesse to
establish user-acceptance testing. You’ll learn if and when it’s OK to introduce these
kinds of tests to the CI process.
Chapter 8 describes how to perform static code analysis. You’ll analyze precom-
piled .NET intermediate language using FxCop. We’ll show how to use StyleCop to
analyze C# code even before it’s precompiled. And we’ll explain how to use NDepend
to do additional analysis. We’ll provide information about how to extend and inte-
grate this analysis with CI.
Chapter 9 describes XML comment notation and how to generate MSDN-style doc-
umentation from it. We’ll show you how to generate documentation continuously.
Chapter 10 deals with deployment and delivery, including using Visual Studio to
create setup files, and using WiX and MS Deploy. We’ll show you how to use these tech-
niques on the CI server.
Chapter 11 deals with continuous database integration. We’ll show you how to main-
tain a database using Visual Studio and how to perform tests at the database level.
Chapter 12 is about extending CI. We’ll explain how to deal with slow builds, how to
scale the CI process, and how to check the maturity of the CI process you’re using.

Code conventions and downloads
All source code in listings or in text is in a fixed-width font like this to separate it
from ordinary text. Code annotations accompany many of the listings, highlighting

ABOUT THIS BOOK


xxi

important concepts. In some cases, numbered bullets link to explanations that follow
the listing.
This book includes a fair amount of source code that is available for download.
The source code illustrates the techniques described in the book. It is
not produc-
tion code. We provide many configuration files, especially for CruiseControl.NET.
You can access the source code from the publisher’s website at www.manning.com/
ContinuousIntegrationin.NET.


Author Online
Purchase of Continuous Integration in .NET includes free access to a private web forum
run by Manning Publications where you can make comments about the book, ask
technical questions, and receive help from the authors and from other users. To
access the forum and subscribe to it, point your web browser to www.manning.com/
ContinuousIntegrationin.NET. This page provides information on how to get on the
forum once you are registered, what kind of help is available, and the rules of conduct
on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialog between individual readers and between readers and the authors can take
place. It is not a commitment to any specific amount of participation on the part of
the authors, whose contribution to the book’s forum remains voluntary (and unpaid).
We suggest you try asking them some challenging questions lest their interest stray!
The Author Online forum and the archives of previous discussions will be accessi-
ble from the publisher’s website as long as the book is in print.

about the authors

MARCIN KAWALEROWICZ has a master’s degree in computer science from the Technical
University of Opole, Poland, and more than eight years of experience in software
development. He started programming in PHP and Java during his studies. After grad-
uation, he lived and worked in Munich, Germany, where he learned the basics of .NET
development. He’s back in Poland now, writing software and running his own com-
pany, CODEFUSION. Through his German contractors, he worked for the financial
branch of a large car manufacturer based in Munich and an even bigger credit bank
based in Zurich, Switzerland. He writes about the stuff that matters on his blog,
www.iprogrammable.com, and contributes articles to Polish computer magazines.
Marcin lives in Silesia, Poland, with his wife and daughter.

CRAIG BERNTSON has been writing software for over 25 years. He’s worked in several dif-
ferent fields and felt the same pain in his processes that you have. He has been named
a Microsoft Most Valuable Professional (MVP) every year since 1996 and is currently an
MVP for Visual C#. He speaks at developer events across the US, Canada, and Europe
and has written articles for several magazines. This is his second book; he forgot every-
thing he said about never doing it again after the first one. Craig is active in his local
developer community, helps organize Utah Code Camp, and speaks at and attends sev-
eral area .NET and software craftsmanship groups. Craig lives in Salt Lake City, Utah,
where he works for a Fortune 100 company developing database software in C# and
C++ for use in hospitals worldwide. He blogs at www.craigberntson.com/blog.



xxii

about the cover illustration

The figure on the cover of Continuous Integration in .NET is captioned “Bride from Sinj
in Dalmatia, Croatia.” The illustration is taken from a reproduction of an album of
Croatian traditional costumes from the mid-nineteenth century by Nikola Arsenovic,
published by the Ethnographic Museum in Split, Croatia, in 2003. The illustrations
were obtained from a helpful librarian at the Ethnographic Museum in Split, itself sit-
uated in the Roman core of the medieval center of the town: the ruins of Emperor
Diocletian’s retirement palace from around AD 304. The book includes finely colored
illustrations of figures from different regions of Croatia, accompanied by descriptions
of the costumes and of everyday life.
Sinj is a small town in the center of an area in Dalmatia known as Cetinska krajina, a
group of settlements situated on a fertile plain through which the river Cetnia passes.
Sinj lies between four mountains which give the area its specific sub- Mediterranean
climate. The town grew around an ancient fortress (held by the Ottomans from the
sixteenth century until the end of seventeenth century) and a Franciscan monastery
with the church of Our Lady of Sinj, a place of pilgrimage.
The bride on the cover wears a red cap over which she ties a blue scarf, and a white
dress embroidered with red wool that she wears over a white shirt. She has tied a red
linen apron around her waist and added a long, dark blue vest decorated with red
wool. A small bouquet of flowers completes the bridal costume.
Dress codes and lifestyles have changed over the last 200 years, and the diversity by
region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants
of different continents, let alone of different hamlets or towns separated by only a few



xxiii

xxiv


ABOUT THE COVER ILLUSTRATION

miles. Perhaps we have traded cultural diversity for a more varied personal life—
certainly for a more varied and fast-paced technological life.
Manning celebrates the inventiveness and initiative of the computer business with
book covers based on the rich diversity of regional life of two centuries ago, brought
back to life by illustrations from old books and collections like this one.

A









Part 1



Make it happen








technically savvy programmer and project manager once asked how
we’d describe continuous integration (CI) to someone who had never heard of
it. We said there are two types of answers, and which one to give depends on how
much time the listener has. The longer answer starts with part 1 of the book.
The shorter one is not really an answer—it’s another question that can give you
an idea about what CI is. Do you remember the last time you released software?
That’s the time in the project when you gather all the bits and pieces required to
deliver the software to the customer. Was it painful? Yes? Well, that’s where CI
can come to the rescue.
In the first part of this book (chapters 1 through 6), we’ll lay the groundwork
for a well-designed CI process in .NET. You'll learn the basics required for any CI
system. We’ll start by looking at CI in general. We’ll define the term and talk a lit -
tle about how to do CI in .NET. After that, we’ll introduce the source control sys-
tem as part of the CI tool chain that can’t be omitted. We’ll help you choose the
right one and introduce it into your day-to-day work.
As a second ingredient that’s required for CI, we’ll describe build automa-
tion. We’ll show why you need a single command-build process and how modern
XML-based build systems are perfect for the .NET CI process. You'll also find out
how to choose the right CI server to bind all the ingredients into one.
We'll then look at unit testing—what it is and how to use it in CI. You’ll
learn to write unit tests and automate their execution. We’ll discuss CI servers
and their ability to give immediate feedback about the state of the build pro-
cess. It’s a core concept of the CI process that every degradation in code qual-
ity should be immediately visible, so the team can react as swiftly as possible to

2


PART 1


Make it happen

make obstacles disappear. This is the purpose of controlling and reporting mecha-
nisms in modern CI servers. We’ll look at how you can extend these reporting capa-
bilities with your software.
After reading this part of the book, you’ll be able to set up your own CI process
using free or inexpensive software. You’ll understand what the CI process is and
how to use it to your team’s benefit. And you’ll be ready to extend CI to better suit
your needs.

Understanding
continuous integration








This chapter covers


■ Continuous integration theory
A Hello World CI example
A preliminary list of CI tools





As developers, we’re interested in creating the best possible applications for our cus-
tomers with the least amount of work. But with applications becoming more com -
plex and having more moving parts, creating great applications is getting harder,
even with advances in tools such as Visual Studio and the .NET Framework.
One of the keys to improving applications and productivity is to automate some
of the work. Continuous integration (CI) is one of the best ways to do this.
Have you ever written code that did its small task perfectly, but then discovered
unexpected side effects when you integrated that piece of code with the rest of the
application? Do you always have success integrating your code with code from
other developers? Have you ever shipped an application, only to find that it didn’t
work for the customer but you couldn’t duplicate the error? Can you always pre-
dictably measure the state of the code for your current project? CI helps alleviate
these problems and more.
In this chapter, you’ll learn what CI is all about, why should you use it, and how
to overcome objections to its adoption from your team. We’ll briefly introduce you


3

4


CHAPTER 1


Understanding continuous integration

to several free or low-cost tools such as CruiseControl.NET, Subversion, MSBuild, Team
Foundation Server, and TeamCity that are part of a complete CI process. Throughout
the rest of the book, we’ll explain in detail how to use these tools.
This chapter also demonstrates a simple CI process through an example using
batch files. We’ll also get started on a more complex Visual Studio Solution that we’ll
use to demonstrate various CI tools and techniques. But before we do any of that, you
need to understand exactly what CI is.

1.1








1.1.1

What does it mean to integrate continuously?
When you adopt CI, it’s likely that you’ll make major changes in your development
processes because you’ll move from a manual system to an almost completely auto-
mated system. Along the way, you may meet resistance from your team members. This
section provides you with reasons to use CI and how to overcome objections. But
before we take you there, we need to define CI.

Defining continuous integration
One of the best definitions of continuous integration comes from Martin Fowler
(www.martinfowler.com/articles/continuousIntegration.html):

Continuous Integration is a software development practice where members of a team
integrate their work frequently, usually each person integrates at least daily—leading to
multiple integrations per day. Each integration is verified by an automated build
(including test) to detect integration errors as quickly as possible. Many teams find that
this approach leads to significantly reduced integration problems and allows a team to
develop cohesive software more rapidly.

This definition contains an important phrase: “multiple integrations per day.” This
means that several times each day, the CI system should build and test the application.
But multiple integrations per day isn’t where you begin your journey into CI; we rec-
ommend against this because many shops not using CI will meet enough resistance
just automating the build, let alone doing multiple builds per day. (We’ll talk more
about overcoming team resistance later in this chapter.) Ideally, you should set up
your CI process just as you create software: by taking small steps, one at a time.
Here is another definition:

CI is the embodiment of tactics that gives us, as software developers, the ability to make
changes in our code, knowing that if we break software, we’ll receive immediate feedback …
[It is] the centerpiece of software development, as it ensures the health of software through
running a build with every change.
—Paul Duval, Continuous Integration
(Addison-Wesley, 2007)

The key phrase here is “the centerpiece of software development.” This means what-
ever development process and methodology you use, CI is a key part of it.

What does it mean to integrate continuously?


5

Our definition is similar to those we’ve mentioned. Here’s how we define continu-
ous integration:

An automated process that builds, tests, analyzes, and deploys an application to help
ensure that it functions correctly, follows best practices, and is deployable. This process runs
with each source-code change and provides immediate feedback to the development team.
As we were discussing this definition, we wondered what a build is. Is it the same as
clicking Build on the Visual Studio menu, or something more? We finally decided that
the definition varies depending on what you’re doing. Early in the development pro-
cess, a build can be as simple as compiling and unit testing the code. As you get closer
to release, a build includes additional and more complete testing and running code
metrics and analysis. You can also go as far as combining all the different files into an
install set and making sure it works correctly.
Finally, don’t get caught up with the meaning of
continuous. CI isn’t truly continu-
ous, because integration occurs only at specific intervals or when triggered by a spe-
cific event. Integration is continuous in that it happens regularly and automatically.
Now that you know what CI is, let’s see how it changes your development process.

1.1.2

CI and your development process
Is your development process agile? Do you use extreme programming (XP), scrum,
or something else? Is your company deeply rooted in waterfall methodologies? Does
your process fall somewhere between agile and waterfall?
It really doesn’t matter which methodology you use, because you probably follow
pretty much the same process when it comes to writing code:
1
2
3
4
5
6


7
8
Check out the needed source files from your source code repository.
Make changes to the code.
Click Build on the Visual Studio menu, and hope everything compiles.
Go back to step 2. You did get compile errors, didn’t you?
Run unit tests, and hope everything is green. We hope you’re running unit tests.
Go back to step 2. Unit tests do fail. In this case, you’ll see red. Perhaps in more
ways than one.
Refactor the code to make it more understandable, and then go back to step 5.
Check the updated code into the source code repository.
When you start using CI, you’ll follow the same process. But after you check in the
source code, you’ll take additional steps (see figure 1.1).
9


10 11
12
An automated system watches the source control system. When it finds changes,
it gets the latest version of the code.
The automated system builds the code.
The automated system runs unit tests.
The automated system sends build and test results to a feedback system so that
team members can know the current status of the build.

6


CHAPTER 1


Understanding continuous integration


































Figure 1.1 In the CI process, developers check code into the version control
repository. The automated CI system polls the repository for changes and then builds
and tests the code. Results are posted to a feedback system where team members
can see the results.


At this point, you may be asking yourself several questions, such as, “Why do tests need
to be run multiple times?” or “Why can’t I just click Build in Visual Studio?” The
answer to these questions is the same: automating the building, testing, and running
of other processes through CI ensures that the code from multiple people integrates,
compiles, and functions correctly, and that it can be reproduced the same way every
time on a different machine than your workstation. Also, consider that you may have
an application with many assemblies. When you click Build, you may only build the
assemblies you’re responsible for. Even if you’re a one- person shop, adopting CI will
improve the quality of your software.
Automating the build and the unit tests are steps in the right direction, but a good
CI process can do more— and eventually you’ll want it to, so you can maximize its
usefulness. Things like running code-analysis tools, running tests in addition to unit

What does it mean to integrate continuously?


7

testing, building an install package, and simulating an install on the customer’s PC are
all possible through a CI process. But you won’t do all these things with every change.

1.1.3

Do I need to build with every change?
The CI steps we’ve outlined make it sound like every time a developer checks in
code, a build is triggered. This is the ultimate goal and the reason it’s called
continu-
ous integration
. Reread the quote from Paul Duval: he says you should build “with
every change.” Martin Fowler says, “multiple integrations per day.” That’s pretty close
to continuous. But, remember, continuous is the eventual goal. You don’t want to
start there.
One way to begin to set up your CI system is to start by getting the latest changes
from source code and building the application. Then add unit tests. And only do this
daily at first. You can call this a
daily build; but as you’ll see in a moment, a daily build
includes other things that don’t run when you do the incremental build.
When you have this build running every day, add two or three builds per day that
only build and test. It won’t take long, and you’ll be building continuously and adding
different builds to do different things. The exact types of builds you need depend on
your environment and applications. Some of the more common builds are listed in
table 1.1.

Table 1.1

Some of the different types of builds you can do with CI

Build type

Continuous/Incremental


Daily/Nightly


Weekly


Release


QA

Staging

How it’s used

Runs when code is checked in. Does a quick compile and
unit test.

Does a compile and full suite of unit tests and possibly
additional testing such as FitNesse.

Does a compile, full unit testing, and additional testing
such as FitNesse.

Creates an install set and then runs and tests the inst
all process.

Creates a build just for the QA team.

Builds and copies assemblies to a staging server.


The most important build, and the one you want to get to, is the continuous or incre-
mental
build. This build is automatically triggered whenever source code is checked in
to the repository. Because this build can potentially run several times per day, and one
build may run immediately upon completion of another, you want the continuous
build to run quickly—preferably in under 5 minutes. This build should get the
updated code, rebuild the assembly it’s in, and then run some preliminary unit tests.
Reports are sent to the feedback mechanism.

8


CHAPTER 1


Understanding continuous integration

Next is the daily build, often called the nightly build. Rather than running whenever
the code changes, the daily build is scheduled to run once per day, usually in the
middle of the night. Because you don’t need to worry about the next build starting
immediately, the daily build typically runs a complete suite of unit tests against all the
code. Depending on your environment, you may want to add additional automated
tests or code analysis.
Another build type is the
weekly build, which runs automatically and usually on the
weekend. Once a week, you should run a code analysis and additional tests with tools
like Selenium, FitNesse, and NUnitForms. You may also want to create documentation
with Sandcastle or do continuous database integration. As you get closer to your
release date, you may want to run the weekly test build more often. You’ll also want to
run a
release build.
The purpose of the release build is to create and test an install set. The release
build is typically manually triggered. But after the build is started, all the other steps
are handled automatically. In a release build, you’ll build all the source code, incre-
ment the version number, and run a full suite of tests. You’ll then create the install set
and simulate the install. Good CI server software will have a way to check if the install
was successful and then roll back the changes, so that the test system is ready for the
next round of install testing.
Your environment may require other types of builds. For example, you may have a
build that copies assemblies to a QA environment after the build. Or you can copy files
to a staging or production server. The bottom line is that many different types of
builds are needed for different purposes. But because steps are automated, you can be
sure that things are done the same way every time.
As you introduce CI and different types of builds, some team members may resist the
changes. It’s important to overcome these objections so your CI process is successful.

1.1.4

Overcoming team objections
With all these builds going on and developers having to change their routine and
check in code more often, you may get objections from team members. Some com-
mon objections are as follows:










CI means increased maintenance.
Someone will have to maintain the CI system. This will take them away from
programming duties. At first, there will be extra overhead to set up the system;
but when a project is fully integrated, your team will save time because it will be
faster and easier to test the application and detect and fix bugs. Many teams
report that after the CI process is running, maintenance takes less than an hour
per week.
This is too much change, too fast.
It’s difficult to adapt to the new way of doing things. Don’t implement every-
thing at once. Start out with a simple build once per day, and then add unit test-
ing. After the team is comfortable with this, you can add one or two additional

What does it mean to integrate continuously?


9

builds per day or start doing code analysis. By taking the process in baby steps,
you’ll get more buy-in into the process.
















CI means additional hardware and software costs.
Start out small with an old PC as your CI server if you need to. Eventually, you’ll
want better hardware so that you can run builds quickly (remember, the inte-
gration build should run in under 5 minutes); but for a build two or three times
a day, older hardware will work. If you use the tools we discuss here, your soft -
ware costs will be minimal.
Developers should be compiling and testing.
We’re not taking those responsibilities away from developers. We’re moving
much of the grunt work to an automated system. This allows programmers
to use their brains to solve the business problems of the application. This
makes the developers more productive where it counts: writing and debug-
ging code.
The project is too far along to add CI.
Although it’s better and easier to place a new project under a CI process, the
truth is, most of the work we do is maintenance on existing projects. An
existing project may not have unit tests, but you’ll still use source control and
need to do builds. You can benefit from CI no matter how far along your
project is.
One of the authors once worked in an environment where each developer was respon-
sible for a different executable in a 15-year-old C++ application. Each executable was
built locally and then copied to a shared folder on the network where QA picked it up
and tested it. Problems arose because each developer used a different version of third-
party components, and each developer used different compiler switches. This meant
that if one developer was on vacation, and a bug in their code needed to be fixed, it
was difficult to reproduce their development environment on another developer’s
workstation. It was so troublesome that management finally decided that unless the
customer was down due to the bug, the fix would wait for the responsible programmer
to get back to the office. If CI had been in place, many of the issues with the software
wouldn’t have happened.
Here are several reasons to use CI in your development process:









Reduced risks —By implementing good CI processes, you’ll create better software,
because you’ll have done testing and integration earlier in the process, thus
increasing the chances of catching bugs earlier. We’ll talk more about reducing risks in the next section.
Deployable software —If you automate the installation process, you’ll know that
the software installs as it should.
Increased project visibility —The feedback mechanism allows project members to
know the results of the build and where the problems are. Bugs can be fixed
sooner rather than later, reducing costs and the time spent fixing bugs.

10


CHAPTER 1


Understanding continuous integration



Fast incremental builds —In October 2009, ZeroTurnaround released results of a
survey of more than 500 Java developers. In the survey, 44% said their incre-
mental builds took less than 30 seconds, and another 40% said build times were
between 1 and 3 minutes. The overall average build time was 1.9 minutes.
1
Although the survey was for Java apps, there’s no reason not to believe your
.NET projects will have fast incremental build times. Fast incremental build
times means you get build and test results sooner, helping you to fix bugs ear-
lier in the development process.

Don’t let team objections get you down. The initial resistance will eventually give
way to acceptance as the team works with the CI system. Virginia Satir, a family ther-
apist, developed the Satir Change Model, which shows how families deal with
change. Steven Smith wrote that the same model can be used to show how new tech-
nology is adopted (http://stevenmsmith.com/ar-satir-change-model/). The change
process involves five steps:

1


2


3


4


5
Late status quo —Everyone is working in the current process and knows how
it works.
Resistance —A new element is introduced. People are hesitant to change how
they’re working. The late status quo works fine. Why change it?
Chaos —The new element is adopted. There is no longer a normal way of doing
things. Daily routines are disrupted.
Integration —People slowly become adjusted to the new way of doing things. It
gets easier to do their jobs with the new methodology.
New status quo —The new element becomes fully integrated into the system. Peo-
ple now look at it as normal.
Almost every team has adopted new methodologies at one time or another. This pro-
cess should sound familiar to you.
As you meet resistance from the team, be persistent in implementing the changes.
Team members will eventually accept them. Some team members will adopt CI more
quickly than others, who may need more convincing. Perhaps you should show them
how CI reduces risk in the development process.

1.1.5

It’s all about reducing risk
Your customer doesn’t like risk. Your manager doesn’t like risk. Your project manager
should have plans in place to mitigate risk. In the end, you shouldn’t like risk either.
CI is all about reducing risk.
Perhaps the biggest risk in software development is schedule slippage—in other
words, the project being delivered late. Because of the feedback mechanism in the CI


1



Alex Handy, “Survey finds that incremental Java builds are speeding up,” Software Development Times, Oct. 29,
2009, www.sdtimes.com/link/33867.

What does it mean to integrate continuously?


11

process, team members always know the status of the current build, which helps you
know whether the project is getting behind schedule. Feedback mechanisms will be
presented in chapter 5.
The next biggest risk is bugs. It’s been shown that the later in the process you find
a bug, the more costly it is to fix. Some estimates suggest that it costs as much as
$4,000 to fix a single bug in internal, home -grown corporate web applications. In
2005, a well-known antivirus company had a bug in an update. That single bug caused
customers to lose confidence in the antivirus software and forced the company to
lower its quarterly income and revenue forecasts by $8 million. Do you want your
company to experience similar costs? One of the caveats of CI is that bugs are fixed as
soon as they’re reported. By integrating and testing the software with each build, you
can identify and fix bugs earlier in the process. We’ll discuss unit testing in chapter 6
and application testing in chapter 7.
Have you considered how many different code paths exist in your application?
Have you tested each
if/else combination? How about every case of a switch
statement? In his book Testing Computer Software (John Wiley & Sons, 1999), Cem
Kaner mentions a 20-line program written by G. J. Meyers that has 100 trillion
paths.
Code coverage is a methodology that checks which paths are tested and which
aren’t. A great thing about code coverage is that you can automate it in your CI pro-
cess. It’s impossible to test every combination; but the more you test, the fewer
issues will be uncovered by your customers. Code coverage will also be presented in
chapter 6.
Another risk is database updates. It’s never easy to add columns to a table or new
tables to a database. With continuous database integration, you’ll know that database
changes work properly and without data loss. We’ll discuss continuous database inte-
gration in more detail in chapter 11.
Developers often hate coding and architectural standards, but they have a useful
purpose: they ensure that the application follows best practices, which in turn makes
the application perform better and makes it easier to maintain. Code reviews catch
some of these issues; but because code reviews are a manual process, things are
missed. Why not automate standards compliance as part of your CI process? We’ll
cover code analysis in chapter 8.
Comments are rarely put in code, and documentation is generated even less often.
Many people say that if you’re agile, you don’t have documentation, but this isn’t true.
Agile says that you value working software over documentation. But some documenta-
tion is still needed, especially if you’re creating assemblies for use by other developers.
Here’s another opportunity for automation in your CI process, and one that’ll be cov-
ered in chapter 9.
How do you know that your installation process works correctly? There are few
things that frustrate users more than when they can’t install an application. Create
and test the entire installation process in your CI system. We’ll cover deployment and
delivery in chapter 10.

12


CHAPTER 1


Understanding continuous integration

Finally, CI also increases visibility. It’s easier to see problems hiding in the project
that without CI wouldn’t be found until much later in the development process, when
they would be harder and much more costly to fix.
Now that you know what continuous integration is and how it can improve your
development process, let’s see CI in action.

1.2

A simple Hello World–type CI example
It seems that just about every computer book starts with a Hello World application. To
help you understand the CI process, we’ve developed a simple C# application and sim-
ulated a CI server using a Windows script. Make sure you have .NET Framework 4.0
Extended installed. Throughout the book, we’ll use Visual Studio 2010. If you have it
installed, you’re good to go.
To install the demo, create a miniCI folder, and then copy the demo files into it. To
run the demo, open a command window, change the directory to the miniCI folder,
and type
Build. The results are shown in figure 1.2.
The build script is an old command- line batch file. We used this tool to show you
how easy it is to create something that resembles the CI process. We aren’t the only
ones to try something like this: there are PowerShell scripts made to do the CI server’s
job (see http://ayende.com/Blog/archive/2009/10/06/texo- ndash-my-power-shell-
continuous-integration-server.aspx). The CI script, shown next, verifies that the input
and output folders exist, compiles the Equals.cs file into an .exe, and then runs it to
























Figure 1.2 The miniCI application builds updated files, tests and deploys them, and
then keeps checking for changes in the source code files.

CI tools


13

verify that it works. The application takes two parameters and returns true if they’re
equal or false if they aren’t.

Listing 1.1

Script for the miniCI demo system

@echo off
cls
echo Setting up environment
if not exist work md work
if not exist deploy md deploy
if not exist equals.cs echo Dummy >> work\ equals.cs
:Start
echo Checking for changes in files
fc equals.cs work\ equals.cs /b > nul
if not errorlevel 1 goto :End
echo Compiling
copy equals.cs work\ equals.cs

B
Verifies build
environment
C:\Windows\Microsoft.NET\ Framework\v3.5\ Csc.exe work\ equals.cs
echo Testing
equals.exe test test

C
Builds
source file
if errorlevel 0 goto :TestPassed
echo Test failed. Application not deployed
goto :End
:TestPassed
copy equals.exe deploy\ equals.exe
echo Test passed. Application deployed.
:End
ping 1.1.1.1 - n 1 - w 5000 > nul
goto :Start

In the CI script, you verify that the work area on the build server is set up correctly
B. The original source file is compared to the file in the work area. If it’s different,
it’s copied to the work area. To detect the differences, you can use the fc.exe tool
that comes with Windows, which compares two text files, prints the differences on
screen, and redirects the output of the command to the null device to hide it from
the user. The new work- area source file is then compiled into an .exe and tested
C.
To test the application, the script uses a little fake: it outputs 0 if the strings are iden-
tical. This is because you have to check the error level in the batch file. If the pro-
gram returns something bigger than 0, you’ll assume it’s an error. If the test is
successful, the .exe is copied to the deploy folder. The feedback mechanism is also
updated with the result.
Now that you’ve seen a simple example of how CI works, it’s time for us to intro-
duce you to the tools that do the real work in continuous integration.

1.3

CI tools
A complete CI process consists of several tools. You can buy expensive CI systems
that are feature rich and often easy to set up and maintain; or you can use tools
that aren’t as feature rich and often require some work to set up but are either

14


CHAPTER 1


Understanding continuous integration

free or low cost. Either way, no one tool does everything you need in a complete
CI system. In this book, we’ll work with free or low-cost tools and show you how
they work and how to integrate them into a fully functional CI process. In this sec-
tion, we’ll give a brief introduction to several tools, starting with those that you
must have.

1.3.1

Essential tools
Five tools are required to get started with CI. At a minimum, you should have these
tools as part of your initial CI setup.
S
OURCE CODE CONTROL
The first essential tool is source control. Source control systems are most often used
to store each revision of the source code so that you can go back to any previous ver-
sion at any time. But you should also use the source control system to store cus-
tomer notes, development documentation, developer and customer help files, test
scripts, unit tests, install scripts, build scripts, and so on. In fact, every file used to
develop, test, and deploy an application should be saved into source control. There’s
a debate in the developer community about whether this should include binaries
that you can build; that decision is up to you and should be based on the needs of
your team.
You have many source control options, ranging from high- end enterprise tools
from IBM Telelogic that integrate with requirements and bug-reporting systems, to
Visual SourceSafe (VSS) from Microsoft, which has been around for years. You can
spend thousands of dollars on these tools or find ones like Subversion and Git that are
open source and free. Even if you don’t use CI, you should have source control, no
matter the size of your team.

NOTE

Microsoft discontinued the aging and not well-respected VSS in early
2010 and replaced it with Team Foundation Server Basic. But many teams
continue to use VSS and have no plans to change in the near future.

This book looks at mostly free tools from the Subversion family and mostly paid tools
related to Microsoft Team Foundation Server (TFS). If you choose Subversion, make
sure you also install another tool such as AnkhSVN (http://ankhsvn.open.collab.net/),
VisualSVN (www.visualsvn.com/visualsvn/), or TortoiseSVN (http://tortoisesvn.tigris.
org/) that integrates into Windows Explorer or Visual Studio and makes it easy to work
with Subversion. TortoiseSVN (see figure 1.3) seems to be the most popular (according
to StackOverflow
2 and SuperUser3), so that’s what we’ll use for our examples. If you’re
using TFS and have Visual Studio 2010 installed, you’re ready to go.




2
3




http://stackoverflow.com/questions/108/best-subversion-clients-for-windows-vista-64bit
http://superuser.com/questions/33513/which-subversion-client-should-i-use

CI tools

CONTINUOUS INTEGRATION SERVER
The second and most important tool you need is one
to drive your CI process. This sits on the CI server,
watches for changes in the source code repository, and
coordinates the other steps in the CI process. It also
allows on- demand builds to be made. Essentially, this
application is the traffic cop of any CI system. The CI
server software typically has its own feedback mecha-
nism that’s used to aggregate feedback from the other
tools and provide it to the feedback mechanism.
The most common CI tools for .NET development
are Team Foundation Server from Microsoft and open
source tools such as CruiseControl.NET and Hudson.
TeamCity is another application that sits between
these two options, because it’s free for small teams but
requires licensing fees as the size of the team or num-
ber of projects increase. We’ll discuss CI servers in
more detail in chapter 4. Most CI tools are driven by a
configuration file (see figure 1.4) that specifies when
a build should take place and what specific steps are
taken during the build or integration process.
F
EEDBACK MECHANISM
The feedback mechanism is another essential part of
the CI process. Your team needs to know the status of
any build at any time, especially when the build fails.
There are many ways to provide feedback to the team,
and we’ll discuss them in chapter 5. But the most com-
mon method is through a website.


15


































Figure 1.3 TortoiseSVN
integrates into Windows Explorer
to make it easy to manage your
Subversion repository.
BUILD MANAGER
Next, you need something to do the actual build. The two most common options are
MSBuild and NAnt. MSBuild is part of the .NET Framework, so it’s free and most closely
matches what happens when you click Build from the Visual Studio menu. NAnt is
designed after the Java tool Ant. It’s an open source solution, but it has received few
updates in the past couple of years. Both applications are controlled by XML configu-
ration files, but you can find GUI tools such as MSBuild Sidekick (see figure 1.5) to
make the configuration files easier to maintain.
The build- manager application takes a Visual Studio solution or individual proj-
ect files and calls the correct compiler, generally C# or VB.NET. The compilers
come free as part of the .NET Framework. Some shops use MSBuild for the actual
compilation of the source and then use NAnt for the remaining steps, such as run-
ning unit tests.

16


CHAPTER 1


Understanding continuous integration































Figure 1.4































Part of the XML configuration file for CruiseControl.NET


UNIT TEST FRAMEWORK
The last essential tool you need is a unit testing tool. The two most common options
are MSTest and NUnit (see figure 1.6), but there are others such as MbUnit and
xUnit.net. These tools run the unit tests that you write for your application and then
generate the results into a text file. The text file can be picked up by your CI server
software; a red/green condition for fail/succeed is reported to the team through the
feedback mechanism.
Although NUnit has a GUI tool, it can also be run as a console application as part of
your CI process. Many of the tools we’ll discuss in this book have both a GUI and a
command-line version. The command- line tools provide results as text or XML files
that can be processed by your CI server software; the results are displayed using the
feedback mechanism.
Now that you know the required tools, let’s turn our attention to other tools that
will help you write better code: code- analysis tools.

CI tools


17






























Figure 1.5
























Figure 1.6






























MSBuild Sidekick from Attrice makes it easy to develop and maintain MSBuild scripts.
























NUnit runs unit tests on your code and reports the results as red/green for failure or success.

18

1.3.2





Code-analysis tools


CHAPTER 1


Understanding continuous integration
Code analysis plays an important part in the development process. Code from multi-
ple team members should use the same naming conventions. And the code should fol-
low best practices so that it’s robust, performant, extensible, and maintainable.
Several code-analysis tools can assist in the process.
The first, FxCop (see figure 1.7), a free tool from Microsoft, analyzes code and
reports possible issues with localization, security, design, and performance. The tool is
targeted at developers creating components for other developers to use, but applica-
tion teams are finding FxCop a useful part of their CI process.
Another free Microsoft tool is StyleCop (see figure 1.8). It comes with Visual Stu-
dio and is delivered with a set of MSBuild plug- ins for standalone usage. This tool
checks your code against best-practice coding standards. It compares your code to rec-
ommended coding styles in several areas including maintainability, readability, spac-
ing, naming, layout, documentation, and ordering.
Both of these tools generate analysis reports that can be used by your CI server soft-
ware and integrated into the build report available via the feedback mechanism.
NCover (see figure 1.9) is a coverage tool that checks that all code paths are
being tested. So is NCover an analysis tool or a testing tool? The truth is, it’s a little
of both.
NCover uses either MSTest or NUnit to run the tests and can integrate with several
CI server applications. But there are additional test tools, and they’re the subject of
the next section.























Figure 1.7 FxCop reports problems in code that can be issues with design, performance, security,
or localization.

CI tools


19




























Figure 1.8



























Figure 1.9




























The StyleCop GUI integrates with Visual Studio and reports issues with coding style.



























NCover reports the results of testing code paths through the application.

20

1.3.3





Testing tools


CHAPTER 1


Understanding continuous integration
Earlier in the chapter, we talked about unit testing tools as an essential part of the CI
process. But other test tools can be run against your code to help ensure that the
application functions correctly.
One such tool is Selenium, an open source tool developed by ThoughtWorks. Sele-
nium has record and playback capabilities for authoring tests that check web applica-
tions. If you’re creating WinForms, Windows Presentation Foundation (WPF) or
Silverlight applications, you may be interested in White: it allows testing of your UI
classes. Finally, there’s FitNesse. This testing tool allows you to specify the functionality
of the application; then tests are run against the code to ensure that it works as speci-
fied. Chapter 6 is devoted to showing how to integrate these tools with your CI process.
There are also several other tools you can add to your CI system.

1.3.4
























1.4

Other tools
Have you ever put XML comments into your code? You can, and then extract them and
compile them into useful documentation. That’s the purpose of Sandcastle. These
comments are most often added by component and framework vendors for building
help files. But they can also be useful for other team members or even for yourself
when you have to make changes to a module a month from now.
You can also automate the building of your deployment. It doesn’t matter if you
use ClickOnce, Visual Studio Installer, WiX, Inno Setup, or something else. Having
your CI process automatically build the application, create the install set, and then test
the install are big steps to ensuring a good, solid application.
The tools presented here are by no means an exhaustive list. You can find many
tools for things like code visualization, performance testing, static analysis, and more
through a web search. Some of the tools cost several thousand dollars, and others are
free. In this book, we take the low-cost approach and discuss tools that are free or
available at a minimal cost. Tools like this emerge continuously in the community. To
keep track of what’s new and hot, you can check community sites like StackOverflow
and ALT.NET (http://altdotnet.org/).
Now that you’ve been introduced to many of the tools you’ll be using in your CI
process, it’s time to introduce you to the project we’ll use throughout the book.

A project for CI: leasing/credit calculator
To better understand the CI process, you should have a simple but real-world example
of software that you can put under source control in the next chapter and eventually
integrate continuously. At this early point, you’ll only create a Visual Studio solution
and the project files. You’ll add the code in later chapters.
You want a sample application that isn’t trivial but is as easy as possible for demon-
stration purposes. How about a leasing/credit calculator? It may not be a tool that’ll
prevent the next worldwide financial crisis, but it’s a piece of software that’ll provide a
straightforward answer to a simple question: how much will you pay monthly for your
dream car or house?

22


CHAPTER 1


Understanding continuous integration















Figure 1.11
Different project directory organization
structures. Files can be grouped in
logical collections. Pick a pattern that
suits you.


Organizing your files in logical groups makes the solution directory tidy. For example,
source files go in a directory called src, and documentation-related stuff goes in the doc
directory. Of course, this isn’t divine knowledge, and you may have a good reason to do
it differently. You may want to put the documentation in another repository or to not
have a separate source directory. It’s up to you, but you should at least think about it.
O
RGANIZING THE PROJECT STRUCTURE
Here are the steps to organize the project:
1


2


3


4







5



6


7
Launch Visual Studio, and create a new solution. Select File > New > Project from
the Visual Studio menu. The New Project dialog box opens (see figure 1.12).
In the Installed Templates list, select Other Project Types > Visual Studio Solu-
tions, and then choose Blank Solution.
Enter
Framework for the solution name and C:\Dev\ for the location, and
click OK.
To add the financial-calculation library to the newly created solution, first
choose File > Add > New Project. Then choose Visual C# > Windows, select
Class Library, and name the library CalcCore. (In a real solution, you may have
other libraries parallel to the core— for example, a project containing database-
access classes or controls ready for reuse in various projects.) Your Solution
Explorer should look similar to figure 1.13.
You need to change some Visual Studio defaults to give better results when you
build the project and put it under the CI process. From the Solution Explorer,
right-click the CalcCore project, and select Properties.
Switch to the Build tab. Under Errors and Warnings, check if the warning level
is set to 4 (see figure 1.14).
Under Treat Warnings as Errors, select All.

A project for CI: leasing/credit calculator


23






















Figure 1.12 You should start with a blank solution. Doing so will give you the ability to name it
differently than the project inside and to place the projects where you want them. Don’t take a shortcut
by creating a project first and letting Visual Studio create the solution file for you. You'll end up with
the Solution Explorer window shown.

These settings will cause the compiler to throw an error every time your code
contains the slightest warning (including the least severe and even informa-
tional warnings). It’s because the number
of warnings have the tendency to grow
and in end effect can be completely
ignored. If you’re conscious that there’s
no way around the warning you can always
suppress it by typing its number into the
“Suppress warnings” text box. You do this
to eliminate unnecessary noise. If you’re
like many developers, you have a tendency
to stop reacting to too-frequent stimula-
tion. Soon enough, you’ll have dozens of
warnings and miss an important one that
may lead to a problem. And you don’t
need any problems, do you?
Figure 1.13 The initial project
structure in the Visual Studio Solution
Explorer. Remember, it’s not necessary
to correspond to the folder structure on
the hard drive.

NOTE

Pay close attention to the platform shown in figure 1.15. In Visual
Studio 2010, it defaults to x86 by executable .NET applications and to Any
CPU for class libraries. This is different than in Visual Studio 2008, which
defaults to Any CPU. If your assembly doesn’t use native Windows func-
tionality, it’s safer to set it to Any CPU. It'll run properly on either a 32- or
64-bit processor.

24


CHAPTER 1


Understanding continuous integration


























Figure 1.14 Build properties set the right way. All warnings are treated as errors and
given the maximum warning level. This setup is used for every configuration defined.


8













9


10


11


12


Signing the assembly with a strong key gives your assembly a globally unique
name. It makes identification and administration easier. It makes it possible to
create a reference to an explicit version of software, and it prevents others from
spoofing your libraries. Without a strong name, you won’t be able to add a
library to the Global Assembly Cache (GAC), which may be a good idea for the
financial-calculation library. But keep in mind that signing the library will make
the versioning more complex. You can’t call a nonsigned library from a signed
one. The general rule of thumb is to sign the libraries and leave the executables
alone; you’ll have to decide for yourself what to do.
To sign the assembly, switch to the Signing tab (see figure 1.15), and select
the Sign the Assembly check box.
From the Choose a Strong Name Key File drop-down list, select New. The Cre-
ate Strong Name Key dialog box opens.
Enter CalcCore for the Key File Name, and deselect Protect My Key File with a
Password. Press Enter in the resulting dialog box (shown in figure 1.15).
Delete the default Class1.cs file. You need to add a new program file that’ll
eventually contain the code.
Delete all unused references. Everything that’s mentioned in the references is
loaded into memory at runtime. If it isn’t needed in your program, it will have
nothing to do in memory.

A project for CI: leasing/credit calculator


25





























Figure 1.15 It’s worth signing your reusable assemblies. Doing so makes it possible to reference them
using strong assembly names.


13


14

Right-click the CalcCore project, and select Add > New Folder from the context
menu. Name the folder Math.
Create a class called
Finance inside the
folder. Did you notice that the namespace
in the new program file contains the path
to the file? It’s generally a good idea to
have the path and namespace match.
Using folders, you won’t clutter your solu-
tion with files, and it’ll be easier to man-
age a lot of files in the Solution Explorer
window. Your Solution Explorer should
look like figure 1.16.
The
Finance class will contain simple financial
mathematical operations. The implementation
details are irrelevant now; we’ll pay closer atten-
tion to the financial library in chapter 6, where
you’ll write unit tests for the library.
Figure 1.16 Model solution with no
unnecessary references. The project is
signed and uses folders (that match the
namespaces).

26


CHAPTER 1


Understanding continuous integration

Now, let’s create two additional projects that you’ll put together with the core
library in the source control repository.

1.4.2

Calculators
You’ll need a user interface for the library. Using the same technique as for the frame-
work solution and core project, you’ll create two user interfaces: one for Windows and
one for the web.
Follow these steps:
1


2


3
4
5
Create a new blank solution and name it WindowsCalculator . From the Visual
Studio menu, select File > Add > Project...
Select Visual C# > Windows > WPF Application from the list of project templates
(see figure 1.17).
Name the project
WinCalc.
Set the location to C:\Dev\ .
Set the warning level as you did for the CalcCore project in the previous sec-
tion. Don’t sign the executable project.
You now need to create a web application for the web-base UI for the calculator project:
1 Create a new blank solution and name it WebCalculator. From the Visual Stu-
dio menu, select File > Add > Project.




























Figure 1.17




























Create a Windows Forms application for the finance calculator project.

Another Random Scribd Document
with Unrelated Content

capitano imperiale aveva lasciato capire, che non avrebbe esitato a
fare davvero, quando avesse potuto esser sicuro della corona
promessagli; ma non s'era mai illuso fino a credere che questa
sicurezza vi potesse esser davvero. Il Morone invece, come succede
spesso ai più furbi, s'era molto illuso, non però quanto s'è voluto
supporre da alcuni scrittori. Egli non era affatto cieco alle difficoltà
cui s'andava incontro, e sapeva bene che avrebbe messo a rischio la
propria testa, se troppo scopriva il Pescara. Pure gli dava qualche
sicurtà il sapere quali ambiziosi desideri nel fondo del suo animo
questi nascondesse. E da un altro lato gli aveva pure fatto ben capire
che, quando l'impresa fosse stata per fallire, anch'egli sarebbe stato
pronto a gettarsi con tutte le sue forze a servizio dell'Imperatore. Per
tutte queste ragioni adunque, invitato dal Pescara ad andare a
conferire con lui, che si trovava ammalato nel castello di Novara,
v'andò col de Leyva, sebbene tutti lo avvertissero che correva alla
sua estrema rovina.
[451]
Il 13 ottobre ebbe un primo abboccamento, il 15 un secondo,
[452]
uscendo dal quale fu fatto prigioniero e menato nel castello di Pavia,
dove il 24 venne il Pescara col de Leyva e l'abate di Nazaria ad
esaminarlo. C'era poco da chiedere e poco da rispondere, perchè il
Pescara già sapeva tutto, e lo sapeva dal Morone stesso. Questi, non
ostante, scrisse di sua mano la propria confessione. Ed in essa, dopo
aver protestato contro la ingiusta violenza che subiva, contro la fede
tradita, diceva al generale di Carlo V, che non poteva rivelar nulla,
che già non gli avesse detto e ripetuto più volte. Esponeva tuttavia la
storia della congiura, ricordando l'offerta del regno di Napoli, le
trattative per la investitura di Milano allo Sforza, che aveva dichiarato
d'accettarla, continuando nel tempo stesso gli accordi per la guerra
nazionale contro l'Imperatore.
[453] Quest'ultima dichiarazione fu il
pretesto, di cui il Pescara si valse per andar subito a Milano, ed
impadronirsi della Lombardia.
Ognuno s'aspettava ora di sentire da un momento all'altro già messo
a morte il Morone, quando, con maraviglia universale, il Pescara
pubblicò un decreto del 27 ottobre, col quale dichiarava di volerlo

tenere presso di sè prigioniero, ed ordinava che non si toccassero
punto le proprietà di lui, lasciandole per adesso alla moglie ed ai
figli, usando loro ogni riguardo.
[454] Sentendosi poi vicino alla
morte, che lo colpì in fatti il 3 dicembre 1525, nella età di soli
trentasei anni, fece testamento, raccomandando all'Imperatore, non
solo la vita, ma anche la libertà del Morone, ed ogni benefizio che gli
si potesse fare, «perchè altrimenti mi riputerei essere caricato.»
[455]
L'abate di Nazaria ed il marchese del Vasto, dimostrando anch'essi
una singolare premura, scrissero subito al prigioniero, per avvertirlo
che il Pescara lo aveva raccomandato a Carlo V, ed aggiungevano
assicurazioni della loro buona disposizione. Lo stesso de Leyva, che
non gli era stato mai benevolo, scriveva da Milano il 25 marzo 1526:
«Si farà maniera che V. S. resterà contenta. Sicchè de novo la torno
a pregare, che stia de bon animo, che farò per lei tanto quanto
vorrei si facesse per me stesso, e me li raccomando.»
[456] Il Morone
tuttavia restò per ora in carcere, a disposizione del conestabile di
Borbone, che assunse il comando dell'esercito imperiale, e lo tenne
come ostaggio, a fin di cavarne danari, dei quali era anch'egli in una
estrema necessità. Ma dopo avere avuto da lui parecchie migliaia di
ducati, con promessa di altri fino a 20,000, firmò il dì 1º gennaio
1527 un decreto col quale, pure rimproverandogli la congiura, ed
accusandolo di pecunia indebitamente estorta in suo privato
vantaggio, n'esaltava l'ingegno, il coraggio, l'esperienza, i servigi
altra volta resi all'Imperatore. E concludeva poi che, per questi suoi
meriti, pei danari recentemente dati in momenti di estremo bisogno,
per la volontà dichiarata di volersi di nuovo rendere utile all'Impero,
lo liberava e gli faceva grazia generale di tutte le sue colpe.
[457] Ma,
quello che è ancora più, lo nominava poco dopo commissario
generale nell'esercito. Ed in questo ufficio noi lo troviamo sotto le
mura di Roma, quando il Borbone morì. Seguìto che fu poi il sacco
della Città eterna, e trovandosi Clemente VII chiuso in Castel
Sant'Angelo, il Morone ebbe parte principalissima nelle trattative
allora fatte per liberarlo. Aiutato dal suo ingegno, dalla sua attività,
dalla sua grande esperienza, salì sempre a maggior grado; fu come
la mente che dirigeva gl'imperiali nello strazio che fecero dell'Italia,

ed era presso l'esercito che assediava Firenze, il giorno 15 dicembre
1529, che fu l'ultimo della sua vita.
[458]
Tutto questo finì, com'era naturale, col lasciare mille dubbî, mille
incertezze sul suo carattere e sul vero significato della congiura;
incertezze e dubbî che crebbero assai più, quando si cominciò a
voler vedere un gran patriotta in un uomo che aveva mirato solo e
sempre a farsi strada nel mondo, che aveva mutato parte ogni volta
che lo richiedeva il proprio interesse, cui solo obbediva. Facendone
un patriotta, rimangono assolutamente inesplicabili la sua condotta e
quella anche del Pescara, del de Leyva, del Borbone. In fatti, come
mai il Morone, avvertito da tanti, sapendo con certezza che il Pescara
era ormai in perfetto accordo coll'Imperatore, si sarebbe andato a
mettere nelle mani di lui? Ed il Pescara, perchè lo avrebbe salvato e
raccomandato? Ammettere in questo scrupoli di coscienza sarebbe
assurdo. Non ne ebbe mai, e non c'era ragione d'averne allora, se
non ne aveva avuti prima. Anche più impossibile sarebbe
immaginare scrupoli o altro simile sentimento, per ispiegare la
condotta del de Leyva, del Borbone, dello stesso Carlo V, i quali non
avevano promesso nulla, e non dovevano usare riguardi ad un
cospiratore. Al patriottismo del Morone non credettero mai i
contemporanei che lo conobbero, neppure quelli stessi che lo
avevano inviato alla congiura. Il Guicciardini, nella sua Storia d'Italia,
dichiara di non aver capito la cecità con cui esso s'era andato a
mettere nelle mani del Pescara, del quale conosceva bene la crudeltà
e la mala fede. Nelle sue Legazioni, però, appena che lo seppe in
prigione, scrisse a Roma: «Io temo che con le sue girandole riuscirà
presto a consigliare ed a dirigere gl'imperiali a danno degli
alleati.»
[459] E così fu.
Ma se i contemporanei dovevano giudicar solo dalla conoscenza che
avevano del Morone, i documenti pubblicati ai nostri giorni ci
pongono in grado di vedere anche meglio come le cose veramente
andarono. Il Morone, che aveva servito molti padroni ed era
prontissimo a servirne altri, pensava a farsi sempre più potente,
servendo il duca di Milano, quando venne da Roma l'idea della lega e
l'offerta del regno di Napoli al Pescara. La lega e la guerra

corrispondevano ad un vero interesse nazionale, ad un bisogno che,
se non era fortemente sentito, era pure assai generalmente inteso
dagl'Italiani. Se il Pescara si faceva davvero promotore dell'impresa,
si poteva sperare di riuscire a buon fine, e, riuscendo, egli ed il
Morone sarebbero divenuti potentissimi. La proposta fu dunque fatta
ed accettata con la intesa tacita e vicendevole, che non potendosi
riuscire al fine voluto, si sarebbero ambedue rivolti a favorire
l'Imperatore. Di ciò, come abbiam visto, il Morone dette prova coi
fatti, quando pareva che il suo Duca morisse. Il Pescara, che si era
pure avventurato abbastanza, si pose anche subito al sicuro,
rivelando ogni cosa all'Imperatore. Aveva continuato ad avere od a
fingere d'aver parte nella trama, cavando intanto dai collegati i
danari che gli occorrevano a sostenere l'esercito, e così andando
innanzi, s'era sempre più persuaso che il Morone poteva, nelle mani
sue e degl'imperiali, riuscire un ottimo strumento a conquistare
l'Italia, appena che la vanità della congiura fosse apparsa evidente
anche a lui. Questi, in ogni caso, era anche, come si vide poi col
fatto, l'uomo più adatto ad indicare le persone da cui si potevano in
Italia estorcere danari, dei quali gl'imperiali avevano un bisogno così
grande ed urgente, che la mancanza di essi li pose più di una volta
sul punto di vedere sbandati i loro eserciti. Era poi egli stesso così
ricco da poter dare anche del suo, come fece più tardi col Borbone.
Così fu che, quando il Pescara lo ebbe nelle mani, iniziò il processo
più per forma e per cavarne danaro, per avere un qualunque
pretesto ad impadronirsi della Lombardia, che per la speranza di
poter nulla apprendere di nuovo. La benignità inaspettata e le
raccomandazioni insolite furono certo promosse dal desiderio che si
adoperasse a profitto degli imperiali un uomo il quale si era
dichiarato pronto a servirli, e poteva veramente riuscir loro di grande
utilità.
Questa congiura, che fu detta del Morone, prova che l'idea di
rendere l'Italia indipendente colle proprie forze, era allora nel
pensiero di molti, e poteva anche essere effettuata, quando vi fosse
stata sincera unione fra gl'Italiani, ed un uomo valoroso e grande
l'avesse deliberatamente sostenuta colle armi. Se l'Italia, in fatti, era

debole, i suoi nemici erano spesso in guerra fra di loro, e disordinati
per modo che più d'una volta si trovarono sul punto d'andare a
rovina, senza quasi essere combattuti da altri. Ma l'uomo necessario
non sorgeva, e quando si veniva alla prova dei fatti, ognuno voleva
operare a suo vantaggio esclusivo: così tutto andava a rifascio.
Questo concetto d'indipendenza nazionale, di cui pur tanto si parlò
dai tempi di Giulio II in poi, era allora vagheggiato dagl'Italiani più
per entusiasmo letterario, e per sostenere interessi locali o personali,
che per bisogno generale e fortemente sentito d'una patria comune.
Non si poteva quindi, in nessun caso, arrivare a grandi e durevoli
resultati. Lo stesso Machiavelli, fino a che restò segretario della
Repubblica fiorentina, non riuscì mai a vederlo chiaramente,
dimostrandosi anch'esso pronto a sacrificar tutto agl'interessi del suo
piccolo Comune. Uscito però d'ufficio, egli fu ben presto il solo che
comprendesse e sentisse fortemente l'idea nazionale, esponendola
senza incertezze o secondi fini, con sublime eloquenza cercando
convincerne gli altri. Ma perciò appunto dovette d'allora in poi passar
la sua vita d'illusione in illusione, di speranza in speranza, vedendo
un dopo l'altro svanire i sogni dai quali era sempre dominato. Nulla
però fa credere che egli si fosse un momento solo illuso sulla
condotta del Morone, quantunque la congiura si direbbe qualche
volta ispirata dal Principe e dai Discorsi. A lui dovette apparir chiaro,
che nessuno di coloro i quali vi presero parte, aveva pur l'ombra di
quel forte e sincero patriottismo, che egli sapeva essere più di ogni
altra cosa necessario a porre in atto la grande idea.
CAPITOLO XVI.

L'esercito imperiale s'avanza in Lombardia. — Il
Guicciardini Presidente della Romagna, poi
Luogotenente al campo. — Il Machiavelli rientra
negli affari. — Sua gita a Roma. — È inviato presso il
Guicciardini a Faenza. — Sua gita a Venezia. —
Corrispondenza col Guicciardini. — È nominato
Cancelliere dei Procuratori delle Mura. — Attende ai
lavori per le fortificazioni della Città.
L'esercito imperiale, padrone ormai del ducato di Milano, comandato
dal conestabile di Borbone, che aveva con sè il Morone,
s'apparecchiava baldanzoso ad andare oltre, e nuovi avvenimenti
sempre più funesti all'Italia erano inevitabili. A questi era rivolta
adesso l'attenzione dei politici italiani, che tutti in un modo o
nell'altro vi pigliavano parte. Anche il Machiavelli fu ricondotto ora in
mezzo agli affari, e più volte mandato al campo degli alleati, dove
trovò il Guicciardini luogotenente generale del Papa. Ambedue fecero
prova di tutta la loro energia, di tutto il loro ingegno, dimostrando
invano le migliori qualità del loro carattere. Il Machiavelli però era già
innanzi cogli anni e vicino alla morte, in condizione sempre
subordinata, a servizio d'uno Stato dipendente dall'autorità del Papa;
poteva quindi far poco altro che mostrare la sua buona volontà, il
suo ardente patriottismo, il suo dolore per le sorti infelici della patria.
Il Guicciardini era invece nel vigore delle forze, investito sempre di
altissimi uffici, e questo fu anzi il periodo più importante della sua
vita politica. Egli aveva in Roma un suo rappresentante nella persona
di messer Cesare Colombo, cui scriveva lettere continue, perchè ne
riferisse al Papa ed ai cardinali. Esse ci danno un ritratto fedele degli
avvenimenti del tempo, e sono una sicura testimonianza della sua
grande intelligenza politica, delle sue qualità di vero uomo di Stato.
Mandato governatore nell'Emilia, s'era fatto molto lodare per la
energia e prontezza dimostrate durante la guerra. Nel 1524 fu perciò
nominato Presidente della Romagna, con incarico di pacificare quel

paese lacerato dalle fazioni, insanguinato da continui delitti. E voleva
subito usare severità contro i colpevoli, per venir poi alla clemenza.
Ma quando ebbe a Forlì fatta eseguire la prima condanna capitale,
pronunziata contro uno «imbrattato nelle ribalderie insino agli
occhi,» dovette avvedersi d'andare incontro a difficoltà più gravi
assai che non pensava.
[460] I ribaldi ricorrevano al Papa per
protezione, si facevano raccomandare, ed ottenevano salvocondotti.
Ciò faceva subito crescere i delitti, e indeboliva l'autorità del
Presidente, che ne restava irritato e sgomento.
[461] Un Bastiano
Orsello, che aveva ammazzato l'avo, ed era accusato d'aver
commesso in un tumulto sedici o diciotto omicidi, oltre infinite
rapine, trovava anch'esso protezione in Giovanni dei Medici e nel
Papa.
[462] E mentre il Guicciardini si lamentava d'uno, facevasi
grazia ad un altro, tanto che egli esclamava sdegnato: «Meglio far
grazia a tutti gli assassini, invitandoli a far peggio! È stato per Dio!
un bel ghiribizzo. Si sono visti girare liberamente omicidi, che nelle
piazze di Forlì avevano giocato alla palla colle teste degli uccisi!»
[463]
Pure egli, profittando delle più gravi cure che assediavano il Papa,
andò innanzi per modo, che alla fine dell'anno potè annunziare di
aver pacificato la Romagna.
[464]
Ed allora la sua attenzione si rivolse agli avvenimenti che seguivano
fuori di quella provincia, dando giudizi e consigli così giusti, così
pratici, che paiono qualche volta addirittura profetici. Poco prima
della battaglia di Pavia, egli scriveva che, a suo giudizio, vincevano
gl'imperiali.
[465]
E quando la previsione s'era avverata, aggiungeva: «Ormai tutto
riuscirà a nostro svantaggio. Gl'Italiani non hanno forze per resistere,
ed il capitolare sarà la nostra servitù.
[466] Questo sarebbe il tempo
di audaci disegni, e io loderei chi pigliasse un partito nel quale la
speranza fosse uguale al pericolo.
[467] È vano sperare nei Francesi,
che non pensano mai al domani, e saranno pronti a tutto per liberare
il loro Re. Capisco che ora ogni buon cervello si smarrisce; ma chi si
avvede che stando fermo gli viene addosso la rovina, deve preferire i
più gravi pericoli alla morte sicura.»
[468] E quando venne notizia

della cattura del Morone, nel quale egli non ebbe mai fiducia,
scriveva: «Ormai gl'imperiali non aspettano più. Forse vorranno
subito rendersi padroni del Milanese, il che può loro riuscire per la
debolezza del Duca, e per qualche nuova girandola del Morone. Noi
non abbiamo nulla da sperare, perchè essi si spingeranno ancora più
innanzi ad occupare le terre della Chiesa, o a mutare lo Stato di
Firenze, o a qualche cosa anche peggiore, quando ne vedessino
l'occasione. Cesare vuol farsi signore d'Italia, e non potrà mai essere
amico di chi deve opporglisi. È vano sperare in un accordo colla
Francia, che ora è prostrata, perchè esso sarebbe sempre a nostro
danno. Nessun accordo riuscirebbe stabile, senza la liberazione del
Re, il quale poi non osserverebbe i patti che fossero a suo carico. Il
vero è che Cesare farà i fatti suoi, mentre gli altri stanno
addormentati, e così prevarrà contro tutti, non per maggior forza,
ma fatali omnium ignavia.»
[469] Queste parole sembrano preveder
chiaramente l'avanzarsi degl'imperiali fino al sacco di Roma ed
all'assedio di Firenze. Nè dalla sua opinione si rimosse il Guicciardini,
quando seppe che un messo dell'Imperatore faceva proposte
d'accordo, e che il Papa trattava. «L'Imperatore,» egli scriveva,
«vuole abbattere la Francia e i Veneziani, deve quindi assicurarsi
prima del Papa, e lo farà appena ultimata la faccenda di Milano. Egli
sarà in ogni caso l'arbitro d'Italia. Il Papa avrà di principe solamente
il nome, e verrà per ora tenuto a bada con proposte che finiranno in
sogni.
[470] Ma pur troppo io temo che si appiglierà al partito più da
poco. A chi ha paura della guerra bisogna mostrare i pericoli della
pace. La troppa prudenza è ora imprudenza, nè si possono più
prendere imprese misurate. È necessario correre alle armi, per
fuggire una pace che ci rende schiavi.»
[471] Ed anche questo
s'avverò. La guerra divenne inevitabile, ed il Guicciardini fu chiamato
a Roma, per essere prima consultato e poi mandato al campo come
Luogotenente generale. Egli allora affidò il governo della Romagna a
suo fratello Iacopo, cui lasciò scritte lunge e minute istruzioni, le
quali sono un'altra prova della sua attitudine a governare.
[472]
È questo il tempo in cui finalmente ricomparisce sulla scena politica il
Machiavelli. Noi lo troviamo col suo solito carattere, combattuto

sempre dalla fortuna, in uffici modestissimi, esaltato da un vivo
entusiasmo a favore della patria italiana, che invano cerca salvare,
dominato, trascinato da' suoi eterni ideali. Questi ideali, che assai
spesso lo fecero apparire visionario e fantastico ai suoi
contemporanei, paiono a noi poco meno che sublimi e profetici,
perchè sono più vicini al nostro che al suo tempo, e dimostrano più
una profonda visione dell'avvenire, che una conoscenza pratica del
presente. La quale conoscenza era invece la dote principale del
Guicciardini, che perciò ebbe maggiore fortuna e potenza. Più freddo
ed impassibile calcolatore, sembra qualche volta ripetere al suo
grande contemporaneo le parole di Dante a Farinata degli Uberti:
E' par che voi veggiate, se ben odo,
Dinanzi quel che il tempo seco adduce,
E nel presente tenete altro modo,
[473]
Il Machiavelli stesso più di una volta si accorse della contradizione in
cui si trovava, quando voleva a forza supporre i suoi contemporanei,
il suo paese, de' quali pur vedeva i difetti, troppo migliori che non
erano, e capaci di grandi, eroiche risoluzioni. Allora scoraggiato
s'abbandonava un tratto al suo spirito satirico, mordace, cinico, che
scoppiava improvviso, irresistibile. Ma poi tornava da capo a' suoi
ideali, nei quali ebbe fino alla morte una fede incrollabile.
Ai primi del 1525, quando non era anche ingrossata la marea delle
nuove calamità, egli meditava dolorosamente sugli avvenimenti che
seguivano alla giornata, e finiva l'ottavo libro delle sue Storie, che
arriva alla morte di Lorenzo il Magnifico. Voleva egli stesso
presentarle al Papa, cui le aveva dedicate, e cercare così di ricevere
qualche nuovo sussidio a continuarle. Ne tenne per lettera parola al
Vettori, che lo incoraggiò sempre assai poco. Pure il dì 8 marzo gli
scrisse da Roma, che il Papa gli aveva chiesto notizia delle Storie, e
che egli aveva risposto d'averne letto una parte, e giudicarle tali da
soddisfare; sconsigliava però il Machiavelli dall'andare in persona a
presentarle, non parendogli opportuno, rispetto ai tempi che
correvano. Ma il Papa invece aveva soggiunto: doveva venire, e sono

certo che i suoi libri debbono piacere ed essere letti volentieri. Pure il
Vettori, sempre freddo, concludeva la sua lettera col dire: è
necessario tuttavia non illudersi, perchè, venendo, c'è sempre il caso
di restare colle mani vuote, tali sono ora i tempi.
[474] Il Machiavelli,
dopo aver molto esitato, decise d'andare, e trovò non solo il Papa
ben disposto, ma anche Filippo Strozzi e Iacopo Salviati pronti ad
aiutarlo assai più efficacemente del Vettori, sempre largo di sole
parole. Il Salviati s'era già prima adoperato a fargli avere qualche
incarico; ma non era riuscito, perchè al Papa non piacque la
proposta.
[475] Filippo Strozzi fu invece più fortunato. Per mezzo di
Francesco del Vero potè far sapere al Machiavelli già ripartito da
Roma, che Sua Santità era pronta a concedergli un nuovo sussidio,
per fargli continuare le Storie.
[476] Il sussidio in fatti venne poi
concesso, e fu di altri cento ducati.
[477]
La ragione per la quale il Machiavelli, non ostante le buone
disposizioni del Papa, era ripartito da Roma senza nulla concludere a
proprio vantaggio, prima anche d'esser sicuro del sussidio per le
Storie, è tale che fa molto onore al suo carattere. Arrivato colà dopo
la battaglia di Pavia, quando gli animi di tutti gl'Italiani erano sospesi
per l'evidente pericolo di vedere da un momento all'altro l'esercito
imperiale avanzarsi minaccioso, egli quasi istantaneamente perdette
il pensiero de' suoi personali interessi, e ne abbandonò la cura agli
amici. Al Papa ragionò invece dei provvedimenti più necessarî a
prendersi nelle presenti condizioni, dei modi di fortificare Firenze
contro qualche improvviso assalto. A lui, ai cardinali, a quanti potè
vedere di coloro che frequentavano la Corte, espose con ardore la
sua vecchia idea della milizia nazionale, cercando persuadere ad
ognuno, come unico rimedio efficace sarebbe ora dar le armi al
popolo, chiamandolo alla difesa della patria minacciata dagli
stranieri. E con tanto calore, con tanta eloquenza ne parlò, che gli
parve finalmente d'esser riuscito a convincerne il Papa ed alcuni di
coloro che gli erano vicini. Nel giugno di quell'anno fu in fatti
mandato al Guicciardini in Romagna, con un Breve di Clemente VII
che lo chiamava dilectum filium Nicolaum Macchiavellum,
[478] per
esporgli il suo disegno, e cercare d'effettuarlo colà, dove il popolo

era assai armigero. Iacopo Salviati e lo Schonberg ne parlarono al
Colombo, invitandolo a scriverne anch'egli subito al Guicciardini. E
questi, che era forse la testa più fredda e pratica che avesse allora
l'Italia, gli rispondeva da Faenza il 15 giugno 1525: «Ho visto quel
che dicono circa la venuta del Machiavelli. Aspetterò il suo arrivo, per
intender prima il disegno suo, e dar poi il mio avviso; perchè è cosa
da considerarla bene, e così direte anche a loro. Intanto chiedete a
che fine mira il Papa con questa proposta; chè se ne spera rimedio ai
pericoli presenti, è provvisione che non può essere a tempo.»
[479]
Il 19 scriveva, che il Machiavelli era arrivato ed aveva esposto il
disegno dell'Ordinanza. «Certo, se questa cosa potesse condursi al
fine desiderato, sarebbe una delle più utili e più laudate opere che
Sua Beatitudine potesse fare. Ed a me non farebbe paura dar le armi
al popolo, se però fosse d'altra sorte che è questo, perchè allora con
pochi buoni ordini e con severità si provvederebbe a tutto. Ma la
Romagna, lacerata da nimicizie crudeli, è divisa in due grandi fazioni,
dette ancora dei Guelfi e dei Ghibellini, le quali s'appoggiano una alla
Francia, l'altra all'Impero. La Chiesa non ci ha veri amici, e però
quando si trovasse in guerra con Cesare, le sarebbe di grandissimo
pericolo avere armato gli amici di lui, sperando valersene a proprio
vantaggio. Questa impresa dovrebbe esser fondata sull'amore del
popolo, che in Romagna manca del tutto alla Chiesa. Qui non son
sicuri nè della roba, nè della vita, e guardano perciò sempre ai
principi stranieri, dai quali in tutta la provincia dipendono. Lo sperare
poi di comporre l'Ordinanza, come vorrebbe il Machiavelli, d'uomini
non legati a nessuna delle due fazioni, sarebbe lo stesso che non
voler trovare alcuno. Pure, se deve in ogni modo tentarsi l'impresa,
io mi ci metterò con ogni mia forza, e così dovrebbe fare Sua
Santità, perchè una volta che fosse iniziata, bisognerebbe tenerne
più conto che di qualunque altra cosa.» Aggiungeva poi che l'idea
d'addossare, come voleva il Papa, la spesa alle già troppo esauste
Comunità, era pericolosissima, e sarebbe riuscita solo ad irritarle, sin
dal principio, contro una istituzione cui bisognava invece affezionarle.
[480] Il 23 giugno tornava ad esprimere i suoi dubbi, invitando il
Colombo a far leggere la lettera prima allo Schonberg ed al Salviati,

riferendo i giudizî e le opinioni loro; poi al Papa, notando
attentamente «li moti e parole sue.»
[481] Mentre però egli era così
sospeso pel dubbio di vedere il Papa gettarsi, senza riflessione e
senza energia, in una impresa assai incerta, già in questo ogni
entusiasmo s'era spento come fuoco di paglia, specialmente quando
sentì che bisognava spendere. Non pensò più neppure a rispondere.
Laonde il Machiavelli, avendo invano aspettato lettere fino al 26
luglio, persuaso ormai che nè il Guicciardini, nè il Papa osavano dar
le armi al popolo, e non volendo invano perdere il suo tempo, se ne
tornò a Firenze, dichiarando tuttavia che sarebbe stato sempre
pronto ad ogni loro cenno.
[482] Fino alla morte egli non perdette mai
la sua fede nell'Ordinanza.
Da Firenze scrisse più volte al Guicciardini, senza per qualche tempo
tornare sull'argomento. Ragionavano fra loro d'affari privati e di
facezie, colle quali cercavano una distrazione dalle miserie in cui
l'Italia si trovava, e dai maggiori pericoli che la minacciavano. Non
potevano però fare che di tanto in tanto non parlassero anche di
questi pericoli, con animo assai addolorato. Il 17 agosto il Machiavelli
accennava al matrimonio proposto tra una delle figlie del Guicciardini
ed un ricco fiorentino; poi si rallegrava molto che all'amico fosse
piaciuta la sua Mandragola, tanto da volerla far rappresentare a
Faenza nel carnevale prossimo, e prometteva d'assistere alla
rappresentazione. Gli mandava una medicina, dalla quale diceva
d'avere molte volte ricevuto grande benefizio, massime quando
aveva troppo lavorato.
[483] Aggiungeva che forse andrebbe presto a
Venezia, nel qual caso si sarebbe, ritornando, fermato a Faenza per
rivedere gli amici.
Il 19 agosto, in fatti, dai Consoli dell'Arte della lana, e da quelli che i
Fiorentini avevano in Romania, chiamati anche Provveditori di
Levante, fu mandato a Venezia per un affare d'assai poco momento.
Alcuni mercanti fiorentini, tornando dall'Oriente, con molto danaro,
sopra un brigantino veneto, arrivati che furono in un porto di quella
repubblica, trovarono il brigantino padroneggiato da un G. B. Donati,
che accompagnava l'oratore turco. Questo Donati li chiamò, e dopo

aver loro «fatto sopportare molte cose indegne, non che altro di
essere riferite, gli sforzò finalmente a riscattarsi con 1500 ducati
d'oro.»
[484] Di ciò si chiedeva dai Consoli risarcimento alla
Serenissima Repubblica, essendo il Donati cittadino veneto. E di
questa commissione che finì subito, abbiamo solo la credenziale, la
istruzione dei Consoli al Machiavelli, e la lettera, in cui è l'esposizione
del fatto,
[485] senza che altro se ne sappia. Invece sappiamo che
allora appunto si sparse per Firenze la voce, ch'egli avesse a Venezia
tentato la sorte, vincendo al lotto da due a tre mila ducati. Così gli
scriveva Filippo de' Nerli, il quale aggiungeva la notizia, che il
Machiavelli era stato imborsato fra i cittadini abili agli ufficî politici,
avendo gli Accoppiatori chiuso un occhio sulle difficoltà che si
presentavano; e ciò era riuscito, perchè era stato raccomandato da
donne a lui benevole.
[486] Su di che il Nerli andava celiando, con un
linguaggio e con allusioni che per noi sono ora poco facili ad
intendere. Si capisce che dagli amici e dagli Accoppiatori era stato
veramente favorito, non avendo essi tenuto conto della voce diffusa
dagli avversarî, che egli non avesse tutte le condizioni richieste dalle
leggi per l'ammissione agli ufficî politici.
[487] Quanto alla pretesa
vincita al lotto, o fu cosa d'assai poco momento, o addirittura una
favola, perchè non se ne trova nessun altro riscontro, e due o tre
mila ducati erano a quel tempo tale somma da far mutare condizione
al Machiavelli, che non ebbe mai questa fortuna. Neppure il Canossa,
allora ambasciatore a Venezia, che lo vide in quei pochi giorni due
volte, dando di lui notizia al Vettori, accennò punto alla pretesa
vincita. Scriveva solamente, che avevano fra loro parlato delle cose
pubbliche, delle quali, concludeva, non v'era da dir altro, se non che
«ce ne andiamo in servitù, o per dir meglio la compriamo. Tutti lo
conoscono e nessuno vi rimedia.»
[488]
Tornato a Firenze senza, a quanto pare, aver per via potuto vedere il
Guicciardini, che era andato ad Imola, il Machiavelli trovò ammalato
il figlio Bernardo,
[489] e ricevè lettera dall'altro figlio Lodovico,
giovane impetuosissimo, che era assai spesso in dispute e risse
sanguinose, che prese più tardi parte assai viva alla cacciata dei
Medici, e morì, con la bandiera in mano, combattendo sotto le mura

di Firenze assediata dagl'Imperiali.
[490] Ora si trovava per affari
commerciali in Adrianopoli, di dove moveva aspro lamento contro un
prete, che non voleva lasciare una chiesa di patronato dei
Machiavelli, non lungi da Sant'Andrea in Percussina. E minacciava di
venire a farsi giustizia colle proprie mani, quando il padre non avesse
trovato modo di rimediarvi subito. «Non vedo,» egli concludeva, «a
che si aspetti tanto. Questo mi pare un modo di cavarci due occhi
noi, per cavarne uno al compagno.»
[491]
A tutte queste piccole noie s'aggiungevano i pensieri sempre più
gravi per le pubbliche faccende. Il Morone era prigione, il Pescara
s'avanzava verso Milano, il Papa si trovava al solito senza consiglio e
senza risoluzione. Le lettere del Guicciardini e del Machiavelli
sembravano ondeggiare fra la disperazione ed un cinico sorriso, che
spesso era invece un sorriso disperato. In una, che è senza data, il
Machiavelli mandava spiegazioni intorno al significato di qualche
motto fiorentino nella Mandragola. Prometteva di comporre le
canzonette da cantarsi fra un atto e l'altro; di far andare a Faenza la
Barbera, la ben nota cantatrice, insieme co' suoi cantori.
[492] In
un'altra, senza data del pari, e firmata: Niccolò Machiavelli, istorico,
comico e tragico, cominciava col parlare a lungo del matrimonio, che
tanto stava a cuore al Guicciardini; poi a un tratto s'interrompeva,
scrivendo: «Il Morone ne andò preso, e il ducato di Milano è
spacciato; e come costui ha aspettato il cappello, tutti gli altri
principi l'aspetteranno,
[493] nè ci è più rimedio: Sic datum desuper.
— Veggo d'Alagna tornar lo fiordaliso, e nel Vicario suo, ecc. — Nosti
versus, coetera per te ipsum lege.»
[494] E poi, mutando da capo
bruscamente: «Facciamo una volta un lieto carnesciale, e ordinate
alla Barbera un alloggiamento tra quelli frati, che se non impazzano,
io non ne voglio danaio, e raccomandatemi alla Maliscotta, e
avvisate a che porto è la commedia, e quando disegnate farla. Io
ebbi quell'augumento infino in cento ducati per l'Istoria. Comincio
ora a scrivere di nuovo, e mi sfogo accusando i principi, che hanno
fatto ogni cosa per condurci qui.»
[495]

E così continuavano. Il 19 dicembre il Machiavelli tornava sull'affare
del matrimonio, e cercando la via a farlo concludere, dava consigli
circa il modo di cavar danari dal Papa, per aumentar la dote della
fanciulla. Ma il Guicciardini, più orgoglioso e pratico, esitava a parlare
di queste cose a Clemente VII, quando erano così gravi le condizioni
in cui versavano lo Stato della Chiesa e l'Italia. Allora era morto il
Pescara, ed i potentati italiani parevano di nuovo disposti ad
addormentarsi, il che rendeva assai maggiore il pericolo in cui tutti
versavano. Il Machiavelli concludeva quella stessa lettera, dicendo:
Ognuno si crede ora rassicurato, «e parendogli aver tempo, si dà
tempo al nemico. E concludo in fine, che dalla banda di qua non si
sia per far mai cosa onorevole e gagliarda da campare o morire
giustificato, tanta paura veggo in questi cittadini, e tanto male volti a
chi fia per inghiottire.»
[496] A che il Guicciardini rispondeva il 26,
cominciando col parlar nuovamente della commedia, «perchè non mi
pare delle meno importanti cose abbiamo alle mani, e almanco è
pratica che è in potestà nostra, in modo che non si getta via il tempo
a pensarvi, e la ricreazione è più necessaria che mai in tante
turbolenze.» Quanto alle cose pubbliche, non sapeva che si dire,
vedendo come tutti biasimavano la opinione che solo a lui pareva
buona. «Si conosceranno i mali della pace, quando sarà passata
l'opportunità di fare la guerra. Noi soli vogliamo aspettare in mezzo
alla via il cattivo tempo che viene, e non potremo dire che ci sia
stata tolta la signoria, ma che turpiter elapsa sit de manibus.»
[497]
Pare che allora non solamente il Guicciardini ed il Machiavelli, non
sapendo dove posare il capo, cercassero distrarsi colle commedie;
ma che molti in Italia, pensassero, in questi anni veramente terribili,
a distrarsi colle feste. A Firenze, in fatti, durante il carnevale del
1526, la Compagnia della Cazzuola rappresentava la Mandragola in
casa di Bernardino Giordano, con uno scenario dipinto da Andrea del
Sarto e da Bastiano da San Gallo, il quale, per la sua perizia in questi
lavori, era chiamato Aristotele. Poco dopo, nell'orto di Iacopo
Fornaciai, presso la porta San Frediano, a bella posta spianato, con
lo scenario dipinto dallo stesso Aristotele, fu rappresentata la Clizia.
[498] Si fecero in questa occasione grandissime feste e conviti a

nobili, a borghesi e popolani, tanto che se ne parlò per tutta Italia. E
dobbiam credere che il Machiavelli vi si abbandonasse non meno
degli altri, perchè Filippo dei Nerli,
[499] che solo in apparenza gli era
amico, dopo essersene con lui rallegrato, scrivendone agli altri, se ne
mostrava invece assai scandalezzato. A Venezia, nel medesimo
tempo, due private Compagnie facevano recitare, una la Mandragola,
l'altra i Menecmi di Plauto, i quali ultimi riuscirono al paragone
freddissimi, tanto che i promotori della rappresentazione invitarono
gli attori della Mandragola a ripeterla in casa loro.
[500] Ed il
Machiavelli ebbe dai mercanti fiorentini colà residenti, premuroso
invito di mandar qualche altro suo lavoro, per farlo recitare nel
prossimo maggio. Ma la rappresentazione apparecchiata in Romagna
pel carnevale di quell'anno, non sembra che avesse altrimenti
effetto,
[501] perchè egli non potè andare a Faenza come aveva
promesso, trovandosi occupatissimo in Firenze, o in gite per affari
urgenti. Il Guicciardini era anch'esso in moto continuo, e nel gennaio
dovè recarsi in fretta a Roma. La notizia improvvisa d'un accordo
seguìto tra la Francia e la Spagna, per la liberazione del Re, sebbene
non se ne conoscessero ancora i termini precisi, teneva gli animi più
che mai sospesi, ed era quindi necessario apparecchiarsi agli eventi.
Di ciò le lettere dei due amici cominciavano ora a parlare con sempre
maggiore insistenza. Il Guicciardini, come già vedemmo, aveva da un
pezzo affermato che l'Imperatore avrebbe liberato il Re, e che questi
poi non avrebbe mantenuto i patti. Il Machiavelli, invece, s'era su di
ciò sempre illuso, credendo che il Re non sarebbe stato liberato, e
che in ogni caso avrebbe mantenuto i patti. Anche quando s'era
sparsa per tutto la notizia dell'accordo, egli durava una gran fatica a
non perseverare nella stessa sua erronea opinione. Tanto era di ciò
convinto che, quando giunse la nuova che il Re era stato
effettivamente liberato, e che si attribuiva questa deliberazione
all'accortezza del Papa, egli dette sfogo al suo malumore con
l'epigramma che finiva:
E quinci avvien che 'l matto
Carlo re de' Romani e 'l Vicerè

Per non vedere hanno lasciato il Re.
[502]
E poco prima, quando la nuova della liberazione non era ancor
giunta in Firenze, ma si sapeva che si trattava già degli accordi, egli
ne aveva scritto prima a Filippo Strozzi, e subito dopo, il 14 marzo, al
Guicciardini, dicendogli che aveva il capo pieno di ghiribizzi per
quest'accordo, e ripeteva ancora che o il Re non sarebbe libero, o
manterrebbe i patti. «È vero che così lascerebbe rovinar l'Italia, e
potrebbe anche perdere il regno; ma avendo esso, come voi dite, il
cervello francese, questo spauracchio non è per muoverlo come
muoverebbe un altro. Libero poi o non libero che egli sia, l'Italia avrà
guerra. E per noi non vi sono che due vie: o abbandonarsi a
discrezione del vincitore, dandogli danari, o armarsi. Il primo partito
non basta, perchè il nemico ci leverebbe i danari e poi la vita; non
resta dunque che l'armarsi.» E qui si abbandonava ad un'altra di
quelle ardite idee, tutte sue proprie. «Io dico una cosa che vi parrà
pazza, metterò un disegno innanzi, che vi parrà o temerario o
ridicolo; nondimeno questi tempi richieggono deliberazioni audaci,
inusitate e strane. E sallo ciascuno che sa ragionare di questo
mondo, come i popoli sono varî e sciocchi; nondimeno, così fatti
come sono, dicono molte volte che si fa quello che si dovrebbe fare.
Pochi dì fa si diceva per Firenze, che il signor Giovanni de' Medici
rizzava una bandiera di ventura, per far guerra dove gli venisse
meglio. Questa voce mi destò l'animo a pensare, che il popolo
dicesse quello che si dovrebbe fare. Ciascuno credo che pensi, che
fra gl'italiani non ci sia capo a chi i soldati vadano più volentieri
dietro, nè di chi gli Spagnuoli più dubitino e stimino più. Ciascuno
tiene ancora il signor Giovanni audace, impetuoso, di gran concetti,
pigliatore di gran partiti. Puossi adunque, ingrossandolo
segretamente, fargli rizzare questa bandiera, mettendogli sotto
quanti cavalli e quanti fanti si potesse più.» «Questo ben presto
potrebbe aggirare il cervello agli Spagnuoli, e far mutare i disegni
loro, coi quali hanno forse pensato a rovinar la Toscana e la Chiesa,
senza trovare ostacolo. Potrebbe anche far mutare animo al Re, che
vedrebbe d'aver da fare con genti vive. E legatevi al dito questo, che
se il Re non è mosso con cose vive e con forze, osserverà l'accordo o

vi lascerà nelle peste, perchè essendogli voi stati troppe volte contro,
o rimasti a vedere, non vorrà che gli intervenga ora lo stesso.»
[503]
Filippo Strozzi mostrò al Papa la lettera che aveva ricevuta dal
Machiavelli, e gli parlò ancora della proposta fatta in quella diretta al
Guicciardini. Ma erano pensieri troppo audaci, troppo patriottici per
farli accettare da Clemente VII, che si smarriva al solo sentirne
parlare. Disse che ben presto il Re sarebbe libero ed osserverebbe i
patti, il che lascerebbe l'Italia in balìa dell'Imperatore. La proposta
d'armare Giovanni de' Medici non gli pareva accettabile, perchè
sarebbe lo stesso che dichiarar guerra aperta all'Imperatore. In fatti
senza danari Giovanni de' Medici non poteva formare un esercito, e
se glieli dava il Papa, sarebbe stato subito responsabile dell'impresa.
[504] Così, come nulla s'era fatto dell'Ordinanza, nulla si fece ora del
nuovo disegno del Machiavelli.
Questi si volse perciò tutto a fortificare le mura di Firenze, di che
aveva in Roma tenuto lungo ragionamento col Papa, «il quale
raccomandò che si facessero opere così gagliarde da mettere nel
popolo animo di poter resistere contro ogni assalto. Voleva che si
costruisse addirittura dalla parte di San Miniato, un nuovo cerchio di
mura; ma ciò era impossibile, a cagione di quel colle. Per includerlo
dentro le nuove mura, sarebbe stato necessario allargarsi troppo e
quindi indebolirsi. Se invece si deliberava di lasciarlo fuori, bisognava
restringersi tanto da lasciar fuori anche un intero quartiere della
Città. E se questo quartiere si demoliva, era una grande rovina; se si
abbandonava, era come darlo al nemico, che subito vi si sarebbe
fortificato.
[505] Il Machiavelli perciò, dopo una visita accuratissima
fatta alle mura, insieme con l'ingegnere Pietro Navarro, scrisse una
minuta e precisa relazione, nella quale, proponendo tutti i lavori
necessarî, insisteva sempre più sul concetto di fortificare solo le
mura esistenti con nuove torri, fortilizî, fossati ed altre opere.
[506] Il
17 maggio scriveva al Guicciardini ancora in Roma, dicendogli che
aveva il capo così «pieno di baluardi» che non vi entrava altro. Gli
aggiungeva che a Firenze s'era fatta la legge con cui veniva istituito
il nuovo magistrato, per provvedere alle fortificazioni; e che se la

cosa andava innanzi, come pareva certo, egli, Machiavelli, sarebbe
stato il nuovo cancelliere. Faceva premure che il Papa cominciasse
da parte sua a dare gli ordini pel denaro necessario a cominciare i
lavori. Accennando poi alle notizie venute di Francia sulla nuova
attitudine presa dal Re, a quelle venute di Roma sui pericoli cui s'era
trovato esposto il Papa, ed a quelle finalmente venute in Lombardia
sui tumulti seguìti nell'esercito imperiale, concludeva che da esse si
vedeva chiaro «quanto facile sarebbe stato cavar d'Italia questi
ribaldi. Per amor di Dio non si perda questa occasione. Ricordatevi
che cattivi consiglieri e peggiori ministri avevano tratto non il Re, ma
il Papa come in prigione, di dove è appena fuori. L'Imperatore
adesso, vedendosi mancare sotto il Re, farà profferte che dovrebbero
trovar le orecchie vostre turate. Non si può più pensare di rimettersi
al tempo ed alla fortuna, perchè ingannano. Bisogna operare. A voi
non occorre dire altro. Liberate diuturna cura Italiam. Extirpate has
immanes belluas, quae hominis praeter faciem et vocem nihil
habent.
[507]». Il Guicciardini gli rispondeva d'essere pienamente
d'accordo con lui, e che le cose erano ormai tanto chiare, che
sperava bene si provvederebbe una volta con animo deliberato. Pure
non fu così. Il Papa, nelle piccole e grandi cose, era sempre in preda
alla stessa incertezza, la quale fece sì che anche l'opera di fortificare
le mura fiorentine non arrivasse ad alcuna conclusione, ostinandosi
egli sino all'ultimo nel suo disegno poco pratico e da tutti
condannato.
La nuova Provvisione che istituiva in Firenze i Cinque Procuratori
delle Mura, fu scritta dallo stesso Machiavelli, e venne approvata nel
Consiglio dei Cento, il 9 maggio 1526. Il 18 furono eletti i
Procuratori, che lo scelsero loro Cancelliere e Provveditore;
[508] ed
egli facendosi aiutare da un suo figlio e da Daniello Bicci, che teneva
i conti e le scritture,
[509] incominciò subito a scrivere lettere, a dare
ordini per mettere mano ai lavori. Fu ordinato ai Podestà di mandare
uomini a cavare fossati; fu scritto al Papa, perchè desse danaro, non
essendo ora possibile aggravare i cittadini con nuovi carichi. Lo
pregavano ancora che sollecitasse la venuta d'Antonio da San Gallo,
inviato già in Lombardia a studiare le fortificazioni colà, non essendo

prudente consiglio il metter mano ai lavori prima che gl'ingegneri si
fossero messi d'accordo sul disegno dei baluardi da costruire.
[510]
Ma questo appunto fu quello che riuscì impossibile, perchè il Papa
tornava sempre alla sua strana idea d'allargare la cerchia delle mura,
per modo che circondassero tutta la collina di San Miniato, e
pretendeva che l'aumento del prezzo de' nuovi terreni, i quali
verrebbero così inclusi nella cinta, dovesse far guadagnare 80,000
ducati. Il Machiavelli fu per perderne la pazienza, e tre lettere ne
scrisse il giorno 2 giugno al Guicciardini, concludendo: «tutto questo
è una favola, nè il Papa sa quello che si dice.»
[511] Caldamente
pregava che lo rimovesse da tanta ostinazione, altrimenti si sarebbe,
egli affermava, indebolita la Città, e spesa invano gran somma di
danaro. In conclusione s'andò per le lunghe, senza far lavori
d'importanza. E quando si doveva finalmente venire a qualche cosa
di più concreto, di più utile, i nemici erano già tanto innanzi, che il
Machiavelli dovette ripetutamente correre al campo, dove era il
Guicciardini, lasciando quindi e ripigliando più volte i lavori.
[512]
Ormai ogni speranza stava nel trovare il modo di deviar da Firenze la
minacciosa bufera, la quale si avanzava rapidamente, senza che si
fosse in condizioni da poter resistere con energia.
CAPITOLO XVII.
Assalto dei Colonna in Roma. — Tregua del Papa
coll'Imperatore. — Il Guicciardini e il Machiavelli al
campo. — Cremona s'arrende alla Lega. — Ordine al
Guicciardini di ritirare il campo di qua dal Po. —
Gl'imperiali s'avanzano verso Bologna. — Vani
tentativi d'accordo tra il Papa e gl'imperiali. — Il
Machiavelli torna a Firenze. — Tumulto di Firenze. —
Sacco di Roma. — Cacciata dei Medici, e
ricostituzione della repubblica fiorentina.

L'Imperatore riteneva adesso che, spingendo innanzi l'esercito,
potesse facilmente divenire arbitro dell'Italia. Ma egli mancava
assolutamente di danaro, ed il paese, quantunque debole e diviso,
gli era tutto nimico. Francesco I, uscito dalla prigione, e deliberato a
non mantenere i patti, aveva a Cognac (22 maggio 1526) stretto col
Papa, con Firenze, Venezia e Milano una lega, che fu detta santa, e
che era in sostanza diretta contro l'Impero. A Carlo V importava
quindi moltissimo separarne il Papa, o renderlo almeno
temporaneamente neutrale. E però, quando il cardinal Colonna, che
era più soldato che prelato, e nimicissimo di Clemente VII, si offerse
d'impadronirsi della persona di lui, fu mandato a Roma don Ugo di
Moncada, con incarico di tentar prima una tregua, e non
riuscendogli, dire al Colonna che facesse pure quello che voleva. In
fatti don Ugo non concluse nulla, essendo giunta la notizia delle
strettezze in cui era l'esercito imperiale, e partì quindi sdegnato, il 20
giugno, lasciando mano libera al Colonna, che non mise tempo in
mezzo. Alla testa di 800 cavalieri, 3,000 fanti ed alcune poche
artiglierie tirate da buoi, irruppe nella Città Eterna con tale impeto,
che Clemente VII ebbe appena il tempo di fuggire con la sua guardia
svizzera, e rinchiudersi in Castel Sant'Angelo. Il Vaticano, San Pietro,
le case dei cardinali andarono a sacco, ed in poche ore fu fatta una
preda di 300,000 ducati. Era già un pessimo esempio dato
agl'imperiali, che s'avanzavano dalla Lombardia; ma il Cardinale
voleva andar oltre ancora, e metter le mani sulla persona stessa del
Papa. Laonde questi si rivolse spaventato al Moncada, che seguiva il
piccolo esercito tumultuario, ed il Moncada si fece subito mediatore,
dettando le condizioni della pace, che furono: tregua di quattro mesi
coll'Imperatore, il naviglio del Papa ritirato da Genova e i soldati dalla
Lombardia, amnistiati i Colonna. Il Cardinale si ritirò allora co' suoi a
Grottaferrata, ed eran tutti pieni di sdegno, chiamandosi traditi. Il
Papa accettò i patti impostigli dalla forza, con animo però, alla prima
occasione, di non rispettarli. E don Ugo lo sapeva bene; ma per ora
gli bastava guadagnar tempo, dopo averlo spaventato. Se ne andò
quindi a Napoli, menando come ostaggio Filippo Strozzi parente dei
Medici. In questo medesimo tempo Clemente VII ebbe a sopportare
anche un'altra umiliazione. Sotto pretesto d'assicurare le spalle al

suo esercito in Lombardia, egli aveva mandato alcune sue genti, con
una moltitudine raccogliticcia di Fiorentini, a mutare il governo in
Siena. Ma furono subito messi dai Senesi in una fuga precipitosa e
vergognosa, senza avere neppur tentato di combattere.
E per colmo di sventura, tutte queste notizie, con l'ordine di ritirarsi
di qua dal Po, arrivarono al campo pontificio nel momento appunto
in cui, dopo molte traversie, s'aveva la prima volta qualche speranza
di migliore fortuna. Le cose erano dapprima cominciate colà assai
male. I Veneziani, comandati dal duca d'Urbino, non passarono
l'Adda; gli Svizzeri aspettati non venivano; ed invece i Lanzichenecchi
ingrossavano nel Tirolo, sotto il comando del Frundsberg,
protestante, che diceva di volere andare in Roma ad impiccare il
Papa, ed impegnava le proprie terre, per poter pagare i soldati
imperiali. Un tumulto seguìto a Milano contro gli Spagnuoli fu subito
represso, senza che gli alleati, i quali avrebbero facilmente potuto
mandar 20,000 uomini per sostenerlo, osassero far nulla. Venivano
finalmente in aiuto molti Svizzeri alla spicciolata, sebbene non vi
fosse un regolare contratto coi Cantoni; ma neppur questo induceva
il duca d'Urbino ad un'azione risoluta. Egli voleva il comando
generale di tutto l'esercito; si lamentava sempre d'ogni cosa, e non
decideva mai niente. Dopo aver fatto le viste d'andare a Milano, dove
tutti lo spingevano, s'era invece fermato, mandando ad assediar
Cremona, il che aveva messo l'esercito nella impossibilità d'inviare
aiuti al Doria, che bloccava Genova, e dichiarava di poterla prendere,
se gli alleati andavano subito a stringerla dalla parte di terra.
Il Guicciardini si trovava allora al campo, luogotenente del Papa, e
non cessava mai di scrivere a Roma per dargli animo; s'adoperava a
tenere in ordine l'esercito, a spronare il Duca, a spingerlo innanzi, a
farlo operare; ma tutto era vano.
[513] Quando credeva d'esser
finalmente riuscito a decidere l'inerte capitano d'andare a Milano, lo
vide invece fermarsi per l'inutile assedio di Cremona. Quando aveva
sperato che il Papa non pensasse più che alla guerra, arrivava invece
la notizia, che si trattavano accordi. «Che carico,» egli esclamava
allora, «che vergogna sarebbe smarrirsi alle prime difficoltà, ora che
l'esercito non è rotto, non sono seguiti disordini, e siamo sulle terre

del nemico!»
[514] In questo mezzo appunto giungeva al campo
Niccolò Machiavelli, mandato dai Fiorentini, che vivevano assai
perplessi per la loro città, ad esaminare e riferire come procedevano
le cose. Per via aveva ricevuto lettere del Vettori, con le quali era
stato ragguagliato del vergognoso fatto di Siena. «Credo,» così
questi gli aveva scritto, «che altra volta sia accaduto che un esercito
fugga alle grida; ma che fugga dieci miglia, non essendovi alcuno
che lo insegua, questo non credo si sia mai letto nè veduto. Ormai
tutto va a rovina. Quando vedo come vanno male le cose a Milano, a
Cremona, a Genova; come è andata male questa impresa di Siena,
io penso che con simile disdetta non riusciremo neppure a sforzare
un forno.»
[515]
Pare che in questi estremi momenti il Machiavelli fantasticasse
ancora d'una possibile resistenza del popolo in armi, e
raccomandasse di nuovo la sua Ordinanza. In fatti troviamo che
Roberto Acciaioli, oratore del Papa e dei Fiorentini in Francia,
scriveva, il 7 agosto 1526, al Guicciardini: «Ho caro che il Machiavelli
habbi dato ordine a disciplinare le fanterie. Volesse Iddio che fusse
messo in atto quello che egli ha in idea; ma dubito che non sia come
la Repubblica di Platone. E però me pareria fussi meglio che se ne
tornassi a Firenze, a fare l'offizio suo di fortificar le mura, perchè
corrono tempi da averne bisogno.»
[516] Il 10 settembre egli veniva
dal Guicciardini spedito al campo di Cremona, perchè vedesse coi
propri occhi lo stato delle cose, e facesse intendere al Pesaro,
provveditore veneto, e al duca d'Urbino, che se non credevano di
potere, in cinque o sei giorni, prendere quella città, era meglio
abbandonare addirittura l'impresa, per correre in aiuto del Doria a
Genova e, potendo, assalire anche il nemico a Milano.
[517] Ma al
Machiavelli non fu possibile concludere nulla. Il provveditore Pesaro,
in fatti, scriveva che il dì 11 settembre il Duca s'era dimostrato assai
contrario a correre in aiuto del Doria, e che il 13, presente il
Machiavelli, avendo adunato i suoi capitani, per consultarli, «s'il
doveva levarsi de l'impresa, et atender a quella di Zenova,» tutti
s'eran dichiarati contrarî. Affermavano esser necessario pigliar prima
Cremona, dopo di che sarebbe stato assai facile mandar gente a

prendere Genova.
[518] Ed il Machiavelli perciò, dopo avere di là
scritto più lettere al Guicciardini,
[519] ripartiva subito per
ritornarsene a Firenze, dove riferì come nel campo nessuno volesse
abbandonare l'impresa di Cremona, che pareva veramente vicina al
suo termine. In fatti la città poco dopo s'arrese.
Allora l'esercito fu libero. Esso componevasi di 20,000 Italiani e
13,000 Svizzeri, senza tener conto di altri 3500 che s'aspettavano
ancora dalle Alpi. Questi erano però gl'iscritti, quelli cioè che si
pagavano, non i presenti, e molti ogni giorno disertavano o si
sbandavano. Ma i nemici erano in numero minore, e privi di tutto.
Qualche cosa dunque si poteva certamente operare. Invece arrivò,
come fulmine a ciel sereno, la notizia della tregua, e l'ordine al
Guicciardini di ritirare le genti del Papa di qua dal Po. «Piuttosto,»
egli scriveva allora al Datario, «abbandonerei l'Italia, che vivere a
Roma nel modo che dovrà Nostro Signore, se va per la via che mi
dite, Tu ne cede malis, sed contra audacior ito.
[520] Deve dunque il
cardinal Colonna con mille comandati aver tanta forza da ridurci in sì
misera condizione, e quasi dar legge al mondo?»
[521] Ormai però
non c'era rimedio, e bisognava obbedire. Per conto del Papa restava
in armi solo Giovanni de' Medici, con una condotta di 4000 fanti, e
l'ordine segreto di continuare la guerra, sotto colore d'essere a soldo
della Francia. Per colmo di sventura, questo valoroso soldato era
scontentissimo del modo in cui veniva trattato, e minacciava di
passare al nemico, se non gli davano uno Stato, come tante volte
avevano promesso. «Ed è uomo capacissimo di farlo,» scriveva il
Guicciardini da Piacenza. Al duca d'Urbino non parve vero
d'abbandonar subito il campo, per andarsene a trovar la moglie.
Intanto i Lanzichenecchi, già riuniti in Bolzano, arrivavano a 10 o 12
mila, ed aumentavano ogni giorno, pronti a scendere in Italia.
[522]
Il Machiavelli, tornato a Firenze, dopo che ebbe riferito a voce,
espose anche in una sua relazione scritta lo stato vero delle cose.
S'era, secondo lui, commessa una serie d'errori, cominciando dallo
sperar troppo nella sollevazione di Milano, subito repressa
dagl'imperiali. L'impresa di Cremona era stata condotta troppo

debolmente, il che aveva fatto perdere tempo e reputazione. Il Papa
non aveva voluto ricorrere alla nomina di nuovi cardinali per far
danaro, nè aveva saputo trovarlo altrimenti. Se n'era rimasto a Roma
in modo che ne andò preso come un bimbo, «il che ha siffattamente
avviluppata la matassa, che nessuno può ravviarla, avendo egli
anche ritirato dal campo le sue genti e messer Francesco
Guicciardini, che solo correggeva gl'infiniti disordini. Ora sono più
capitani discordi fra loro, per modo che, mancando chi li guidi, fia
una zolfa di cani, dal che segue una stracurataggine di faccende
grandissima.»
[523] Egli avrebbe desiderato che si fosse venuto a
qualche partito audace e disperato, ma non aveva mai trovato
ascolto. Da una lettera di Filippo Strozzi (Roma, 26 agosto 1526)
apprendiamo in fatti che il Machiavelli aveva, in una sua, proposto
che s'andassero ad assalire gl'Imperiali nel regno di Napoli; ma che il
Papa, dopo averla letta con attenzione, concluse che la risoluzione
del detto non gli piaceva.
[524]
L'armata di Spagna muoveva intanto dal porto di Cartagena, sotto il
comando del Lannoy vicerè di Napoli, per andare a combattere il
Doria; ed il Frundsberg a novembre era già nel Bresciano, con più di
12 mila Lanzichenecchi. Tuttavia il Doria, con l'aiuto delle navi
francesi, comandate da Pietro Navarro, era sul mare in condizioni da
poter respingere il nemico. Nè sarebbe stato difficile ricacciare nei
monti i Lanzichenecchi, separati ancora dagli altri imperiali, senza
artiglierie, senza danari e senza vettovaglie. Ma nessuno andò ad
affrontarli, sebbene il duca d'Urbino con Giovanni de' Medici avesse
1600 cavalli e 19,000 fanti. I Tedeschi, dopo essersi lentamente
avanzati, si trovarono nel Mantovano, in mezzo alle paludi, circondati
dai nemici; e neppur questo potè indurre il Duca ad assalirli. Tutto
dimostrava che la servitù d'Italia non si poteva ormai evitare. Pure le
condizioni degli imperiali erano tali, che c'era da vederli sbandarsi
senza assalirli, se in quel momento non veniva ad essi un aiuto
inaspettato. Il duca di Ferrara, che possedeva le migliori artiglierie
allora conosciute, era in una posizione geograficamente così
vantaggiosa, da poter esso solo decidere l'esito della guerra. Ed il
Papa appunto allora lo aveva scioccamente offeso, respinto, irritato.

Egli mandò quindi ai Tedeschi danari con alcune delle sue artiglierie,
le quali arrivarono nel momento del maggiore bisogno. Giovanni dei
Medici, stanco dell'ozio forzato, cominciò il 25 novembre una
scaramuccia contro gl'imperiali, e secondo il suo solito, s'avanzò
arditamente, nulla sapendo delle artiglierie arrivate al nemico; sicchè
la seconda palla che esse tirarono, lo ferì in una gamba per modo
che dopo cinque giorni ne morì. E così mancava al Papa il solo
capitano che allora potesse e volesse con animo deliberato fare la
guerra.
La tregua intanto si poteva dire già finita, essendosi di fatto venuto
di nuovo alle mani. Ed il Machiavelli tornava in fretta al campo, per
esporre al Luogotenente le misere condizioni di Firenze, e dirgli che
in niun modo essa avrebbe senza aiuti potuto resistere al nemico,
quando fosse venuto ad assalirla.
[525] Ma il Guicciardini dovette
rispondergli, che i soldati della Lega si trovavano talmente sparsi,
che in caso d'urgenza egli non avrebbe potuto condurre in aiuto
della Città più di 6 o 7 mila fanti del Papa. S'apparecchiassero perciò
come meglio potevano, e se credevano di dover tentare accordi, era
meglio trattar direttamente col Vicerè, dal quale tutti gli altri
dipendevano, perchè esso rappresentava l'Imperatore. Ed il
Machiavelli, dopo aver mandato per lettera
[526] queste notizie,
tornava daccapo a Firenze.
Da Milano uscivano intanto continui drappelli di Tedeschi e di
Spagnuoli, che andavano a raggiungere i Lanzichenecchi. V'andò
anche il Borbone, dopo aver prima minacciato il Morone per cavarne
nuovo danaro, nominandolo poi suo consigliere, vedendo che si
prestava efficacemente a tutto; quando vi trovava il suo interesse.
Gl'imperiali erano arrivati al numero di 30,000, ed avendo ricevuto
una seconda volta danari e munizioni dal duca di Ferrara, lasciavano
Piacenza, avviandosi verso Bologna. Ed il Papa non si decideva
ancora nè alla pace nè alla guerra. I Fiorentini promettevano di
dargli fino a 150,000 ducati, se riusciva a fare un accordo stabile,
per salvar tutti dal pericolo imminente. Ma egli ora trattava
cogl'imperiali, ed ora faceva assalire le loro genti nel Napoletano, per
venire poi di nuovo ad accordi, che dovevano essere da capo violati.

L'Imperatore, come sin da un anno aveva preveduto e scritto il
Guicciardini, voleva addormentarlo, per averne occasione a farsi
padrone d'Italia. E però il suo esercito s'avanzava sempre dal
settentrione, sebbene assai lentamente e fra mille ostacoli, per
mancanza di danaro, per disordini continui nel campo, per la cattiva
stagione. E fra poco doveva, in tale stato, affrontare anche la
difficoltà di traversare le nevi dell'Appennino. Il Guicciardini era a
Parma, donde scriveva e riscriveva, che nulla poteva indurre il duca
d'Urbino ad assalire il nemico: o tradiva o aveva una gran paura;
forse era vera l'una cosa e l'altra.
[527] Nel febbraio lo raggiunse di
nuovo in gran fretta il Machiavelli,
[528] mandato per la terza volta da
Firenze a dirgli, che negli accordi non si poteva più sperare, che la
Città non poteva in nessun modo resistere, e chiedeva di non essere
abbandonata al nemico. Il Guicciardini lo condusse dal Duca a Casal
Maggiore, per vedere se in due riuscivano a farlo muovere una volta.
Ma ogni preghiera fu vana. Egli non voleva nè affrontare, nè
precedere il nemico: solo a distanza lo seguiva.
[529] Tutto induce a
credere che non fosse allora trattenuto unicamente dalla paura,
come molti dicevano e credevano; ma forse anche da segrete
istruzioni dei Veneziani, ai quali pare che non dispiacesse vedere il
Papa umiliato, piuttosto che divenuto per qualche vittoria potente e
pericoloso. Certo è che il Guicciardini aveva pienissima ragione di
scrivere: «Qui non si fa altro che prevedere e ritenere per certi tutti i
possibili pericoli nostri e tutti i possibili disegni del nemico, il quale
non arriverebbe a pensarne la metà, quando pure potesse leggere
nella nostra mente.»
[530] Assicurava tuttavia al Machiavelli che,
quando gl'imperiali fossero venuti in Toscana, egli li avrebbe
preceduti con le genti del Papa, per salvare Firenze, anche se il Duca
si fosse ostinato a rimaner sempre alla coda.
[531] Ed il Machiavelli
mandava queste notizie agli Otto, scrivendo ripetutamente da
Parma, che non si poteva in nessun modo prevedere quello che i
nemici erano per fare, non sembrando che lo sapessero essi stessi.
Facile sarebbe stato metterli in rotta, se però i disordini della Lega e
la inerzia del duca d'Urbino non continuassero a mandar tutto a
rovina. Nel marzo scriveva da Bologna, dove si trovava col

Guicciardini, che gl'imperiali erano colà presso alle mura; avevano
avuto la seconda volta aiuto dal duca di Ferrara, fatalmente divenuto
arbitro della guerra, e parevano decisi a venire in Toscana.
[532] Essi
intanto domandavano vettovaglie, e volevano entrare in quella città;
ma il Guicciardini fece chiudere le porte, senza altro rispondere, ed
invano minacciarono e tentarono di ricorrere alla forza.
Il Luogotenente era adesso molto impensierito, non solo del pericolo
in cui si trovava il Papa, ma di quello che pareva più vicino ancora
alla città di Firenze. E per indurre il Duca a soccorrerla in tempo,
aveva preso su di sè la grave responsabilità di cedergli la terra di San
Leo, che i Fiorentini gli avevano sempre fatta sperare, senza mai
dargliela.
[533] Per fortuna l'imminente pericolo sembrava ora
allontanarsi, giacchè gl'imperiali accennavano a pigliar direttamente
la via di Roma, e il disordine andava sempre crescendo fra di loro.
Verso la metà di marzo in fatti vi fu nel campo un vero e proprio
tumulto, che durò alcuni giorni. Il Borbone si dovette nascondere,
per salvarsi dall'ira de' soldati. Il Frundsberg volle invece affrontarla,
e si provò il 16 ad arringare i suoi Lanzichenecchi; ma gli risposero
con le punte delle alabarde sul viso, gridando ferocemente che
volevano subito le paghe. Ed a questo atto d'indisciplina, lo sdegno
del valoroso capitano fu tale che ne ebbe un colpo d'apoplessia.
Sedutosi sopra un tamburo, venne soccorso dai suoi, che poterono
condurlo a Ferrara; ma non andò molto che cessò di vivere. E
neppure in tale momento il duca d'Urbino seppe decidersi ad assalire
il nemico.
Intanto arrivava la notizia d'una nuova tregua conclusa a Roma fra il
Vicerè ed il Papa. Questi doveva reintegrare i Colonna; ritirare le
armi che aveva fatte avanzare nel Napoletano; lasciare il Reame a
Carlo V, Milano allo Sforza, e dare 60,000 ducati al Borbone, che si
sarebbe col suo esercito ritirato dallo Stato della Chiesa e dall'Italia,
se Francia e Venezia accettavano i patti. Lo sdegno del popolo
romano, allora già in armi, fu grandissimo; ma Clemente VII, che
non poteva più sostenere le enormi spese, ed era avarissimo, non
appena il 25 marzo fu firmato l'accordo dal Vicerè, licenziò buona
parte de' soldati in Roma, facendo un'economia di 30,000 ducati il

mese. Così la Città restava senza potersi difendere, ed il Borbone,
che aveva l'ordine segreto d'andare innanzi, scrisse subito al Vicerè,
che i 60,000 ducati erano pochi pel suo esercito; non poteva quindi
accettare la tregua, ed era vano presumere che egli o altri potesse
ora fermare i soldati. Il 31 marzo in fatti passò il Reno presso
Bologna, ed andò oltre.
Il Guicciardini non sapeva più che dire o che fare, ed a confonderlo
sempre più, il Morone mandava a dire, che se gli dava subito 3000
ducati, dei quali avea bisogno per liberare un suo figlio, che era in
ostaggio, avrebbe tradito gl'imperiali, lasciandoli in grandissima
confusione.
[534] Ma il Luogotenente non rispose neppure, troppo
bene conoscendo l'uomo. E sempre più rattristato, scriveva a Roma,
che il pensare, come facevano colà, alla tregua e non alla difesa, era
un funesto errore. «Non so se la necessità ci farà infine uscire
dall'incertezza. Li inimici vogliono da Nostro Signore e da noi tutto
quello che abbiamo, nè pensano solo al temporale; ma ruinano le
chiese, profanano i sacramenti, mettono eresie nella fede di Cristo.
Alle quali cose, se non pensa chi può e deve sforzarsi di portarvi
rimedio, credo sia colpevole della medesima infamia ed offesa a
Dio.»
[535] Nè molto diversamente scriveva a Firenze il Machiavelli, il
quale, annunziando che il Papa voleva far pagare dai Fiorentini i
60,000 ducati promessi agl'imperiali, aggiungeva: «Bisogna pure
trovarli e far quest'ultimo sforzo per salvare la patria. O si fa davvero
la tregua, e serviranno a pigliar tempo, a ritardare almeno la rovina,
o non si fa la tregua, e serviranno a far guerra.»
[536] Ormai però già
si sapeva che il Borbone non accettava. Egli anzi, rispondendo che i
danari promessi erano pochi, non aveva neppur detto qual somma
maggiore volesse. Un suo uomo, è vero, mandato a Firenze, dove
espressamente venne anche il Vicerè, s'accordò per 150,000 ducati,
promettendo che l'esercito avrebbe cominciato a ritirarsi appena
pagati i primi 80,000. Ma neppure a ciò il Borbone dichiarava di
consentire; e però il Machiavelli, finalmente affatto disilluso, scriveva
che adesso era meglio pensare alla guerra e non occuparsi d'altro.
[537] «Quale accordo volete voi sperare da nemici che, quando
ancora i monti li separano da voi, e le nostre genti sono in piedi, vi

domandano 100,000 ducati fra tre giorni, ed altri 50,000 fra dieci?
Arrivati che saranno costà, vi chiederanno tutto il mobile vostro. Non
vi è altro rimedio che sgannarli, e quando ciò s'abbia a fare, è meglio
sgannarli con queste alpi che con coteste mura.»
[538]
Sebbene le nevi e i monti tenessero ancora fermo l'esercito, e si
continuasse a parlare d'accordi e di somme sempre maggiori per
poterli concludere, pure il Machiavelli che, non avendo ormai altro da
sperare o da fare a Bologna, era partito per Firenze, scriveva il 16
aprile da Forlì al Vettori: «Se il Borbone va innanzi, bisogna pensare
alla guerra affatto, senza avere più un pelo che pensi alla pace. Se
non muove, bisogna concludere addirittura la pace, senza pensare
alla guerra. Dovendola però fare, non si deve più claudicare, ma
farla all'impazzata, perchè spesso la disperazione trova dei rimedî
che la elezione non ha saputo trovare. Io amo messer Francesco
Guicciardini, amo la patria mia, e vi dico, per quella esperienza che
mi hanno dato sessanta anni di vita, che io non credo mai si
travagliassero i più difficili articoli che questi, dove la pace è
necessaria e la guerra non si può abbandonare, e si ha alle mani un
principe, che a fatica può supplire alla pace sola o alla guerra sola.»
Da Brisighella scrisse il 18 allo stesso un'altra lettera, più incerta che
mai, e poi venne a Firenze, dove la sua opera poteva essere utile e
la famiglia lo aspettava con grandissima ansietà. La moglie ed i figli,
in gran paura dei Lanzichenecchi e degli Spagnuoli, già avevano in
parte sgomberato la villa; ed egli aveva promesso di raggiungerli in
tempo, quando vi fosse stato davvero vicino pericolo. «Saluta Mona
Marietta,» così il 2 aprile aveva concluso da Forlì una sua affettuosa
lettera al figlio Guido, «e dille che io sono stato quasi per partirmi di
dì in dì, e così sto, e non ebbi mai tanta voglia di essere a Firenze,
quanto ora; ma io non posso altrimenti. Solo dirai che per cosa che
la senta, stia di buona voglia, che io sarò costì prima che venga
travaglio alcuno.»
[539] Ed il figlio, ancora giovanetto, rispondeva il
17, dicendo che erano tutti lietissimi della promessa. Li avvertisse
però subito se venivano i Lanzichenecchi, perchè si fosse in tempo a
portar via ogni cosa dalla villa.
[540] Questa lettera in grossi caratteri,

quasi infantili, fu gelosamente serbata dal padre, e così arrivò sino a
noi. Egli, secondo la promessa fatta, fu subito tra i suoi.
A Firenze i cittadini s'erano dimostrati pronti ad ogni sacrifizio, per
evitare il pericolo che loro sovrastava. Avevano in fretta raccolto e
spedito i primi 80,000 ducati promessi dal Papa al Borbone;
fondevano gli ori e gli argenti delle chiese, per mandare il resto. Ma i
loro messi seppero per via che non erano neppur ora accettati i
patti, e furono a mala pena in tempo a mettere in salvo il danaro,
riportandolo a Firenze. Non v'era dunque, come il Machiavelli aveva
già detto, da pensare ad altro che a difendersi. In città si trovavano
solo alcuni pochi soldati, ed il lavoro delle fortificazioni, sebbene
fosse stato a più riprese da lui sollecitato, si poteva dire a mala pena
iniziato. Il popolo era scontentissimo del cardinal Passerini, che non
voleva consigli e non faceva nulla. «Tutto il male,» scriveva il
Guicciardini, venuto ora anch'egli a Firenze, «procede dalla
ignoranza di questo castrone, il quale si consuma in favole, e
stracura le cose importanti. Non vuole che gli altri le faccino, ed egli
non sa far nulla. Pensa solo a guardare la casa dei Medici ed il
Palazzo; abbandona lo Stato, e non vede la rovina che si tira dietro.
Oh Dio! che crudeltà è vedere tanto disordine.»
[541] Era riuscito a
condurre l'esercito della Lega presso Firenze, il che aveva contribuito
a far sì che gl'imperiali si decidessero a continuare il loro cammino
verso Roma. Ma anche quell'esercito, che doveva essere amico,
saccheggiava il contado, e quindi il malumore dei Fiorentini cresceva
sempre più. Bastò in fatti una rissa seguita il 26 aprile fra un
cittadino ed un soldato, per far nascere un tumulto generale, nel
quale il popolo si levò a chiedere le armi. Il caso volle, che allora
appunto il Passerini, salito a cavallo coi cardinali Ridolfi, Cibo e
Ippolito de' Medici, si movesse per andare incontro al duca d'Urbino,
il quale, insieme coi Provveditori veneti e col Luogotenente, aveva
preso alloggiamento in una villa a poche miglia dalla Città. Il Cardinal
Passerini volle far mostra di sprezzare il tumulto, e quindi, senza
neppur chiedere che scopo e che gravità avesse, continuò il suo
cammino. Tutto ciò fece credere alla moltitudine, che i Medici con i
loro rappresentanti se ne andassero via; ed il Palazzo fu subito

Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com