]> git.pld-linux.org Git - packages/mono-tools.git/blame - mono-tools-git-partial.diff
- merged partial update from git; obsoletes am and mono3 patches
[packages/mono-tools.git] / mono-tools-git-partial.diff
CommitLineData
d2d045d0
JB
1diff --git a/Mono.Profiler/Mono.Profiler.Widgets/Makefile.am b/Mono.Profiler/Mono.Profiler.Widgets/Makefile.am
2index 7b91e6b..f0bf1ec 100644
3--- a/Mono.Profiler/Mono.Profiler.Widgets/Makefile.am
4+++ b/Mono.Profiler/Mono.Profiler.Widgets/Makefile.am
5@@ -9,7 +9,8 @@ CSFLAGS = -noconfig -codepage:utf8 -warn:4
6 ASSEMBLY_MDB =
7 endif
8
9-pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
10+programfilesdir = $(pkglibdir)
11+programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
12
13 CLEANFILES = $(ASSEMBLY) $(ASSEMBLY_MDB)
14
15diff --git a/Mono.Profiler/heap-snapshot-explorer/Makefile.am b/Mono.Profiler/heap-snapshot-explorer/Makefile.am
16index 2bb2401..a9f34a3 100644
17--- a/Mono.Profiler/heap-snapshot-explorer/Makefile.am
18+++ b/Mono.Profiler/heap-snapshot-explorer/Makefile.am
19@@ -9,7 +9,8 @@ CSFLAGS = -noconfig -codepage:utf8 -warn:4 -optimize+
20 ASSEMBLY_MDB =
21 endif
22
23-pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
24+programfilesdir = $(pkglibdir)
25+programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
26
27 CLEANFILES = $(ASSEMBLY) $(ASSEMBLY_MDB)
28
29diff --git a/Mono.Profiler/heap-snapshot-viewer/Makefile.am b/Mono.Profiler/heap-snapshot-viewer/Makefile.am
30index 3b488be..f7b0888 100644
31--- a/Mono.Profiler/heap-snapshot-viewer/Makefile.am
32+++ b/Mono.Profiler/heap-snapshot-viewer/Makefile.am
33@@ -8,7 +8,8 @@ CSFLAGS = -noconfig -codepage:utf8 -warn:4 -optimize+
34 ASSEMBLY_MDB =
35 endif
36
37-pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
38+programfilesdir = $(pkglibdir)
39+programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
40 bin_SCRIPTS = mprof-heap-viewer
41 man_MANS=man/man1/mprof-heap-viewer.1
42
43diff --git a/Mono.Profiler/mprof-gui/Makefile.am b/Mono.Profiler/mprof-gui/Makefile.am
44index 5b00ea9..0369c2c 100644
45--- a/Mono.Profiler/mprof-gui/Makefile.am
46+++ b/Mono.Profiler/mprof-gui/Makefile.am
47@@ -8,7 +8,8 @@ CSFLAGS = -noconfig -codepage:utf8 -warn:4
48 ASSEMBLY_MDB =
49 endif
50
51-pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
52+programfilesdir = $(pkglibdir)
53+programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
54 bin_SCRIPTS = emveepee
55
56 CLEANFILES = $(ASSEMBLY) $(ASSEMBLY_MDB)
57diff --git a/Mono.Profiler/profiler-decoder-library/Makefile.am b/Mono.Profiler/profiler-decoder-library/Makefile.am
58index 115f1a7..71d49ac 100644
59--- a/Mono.Profiler/profiler-decoder-library/Makefile.am
60+++ b/Mono.Profiler/profiler-decoder-library/Makefile.am
61@@ -9,7 +9,8 @@ CSFLAGS = -noconfig -codepage:utf8 -warn:4 -optimize+
62 ASSEMBLY_MDB =
63 endif
64
65-pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
66+programfilesdir = $(pkglibdir)
67+programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
68
69 CLEANFILES = $(ASSEMBLY) $(ASSEMBLY_MDB)
70
71diff --git a/Mono.Profiler/profiler-file-decoder/Makefile.am b/Mono.Profiler/profiler-file-decoder/Makefile.am
72index 285267f..2365dc7 100644
73--- a/Mono.Profiler/profiler-file-decoder/Makefile.am
74+++ b/Mono.Profiler/profiler-file-decoder/Makefile.am
75@@ -9,7 +9,8 @@ CSFLAGS = -noconfig -codepage:utf8 -warn:4 -optimize+
76 ASSEMBLY_MDB =
77 endif
78
79-pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
80+programfilesdir = $(pkglibdir)
81+programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
82 bin_SCRIPTS = mprof-decoder
83 man_MANS = man/man1/mprof-decoder.1
84
85diff --git a/README b/README
86index 3ad3752..a01a518 100644
87--- a/README
88+++ b/README
89@@ -23,3 +23,12 @@ automatically executed):
90 make
91 make install
92
93+Building on OSX with homebrew:
94+------------------------------
95+
96+Have the following packages installed:
97+autoconf pkg-config readline automake gettext glib intltool libtool
98+
99+Run autogen like this:
100+PKG_CONFIG_PATH=/Library/Frameworks/Mono.framework/Versions/Current/lib/pkgconfig/ ./autogen.sh
101+
102diff --git a/configure.in b/configure.in
103index 2a8870f..4771a2e 100644
104--- a/configure.in
105+++ b/configure.in
106@@ -1,4 +1,4 @@
107-AC_INIT([mono-tools], [2.10])
108+AC_INIT([mono-tools], [2.11])
109 AC_CONFIG_SRCDIR([README])
110 AC_CANONICAL_SYSTEM
111 AM_INIT_AUTOMAKE([tar-ustar -Wno-portability])
112@@ -272,6 +272,7 @@ gendarme/swf-wizard-runner/Makefile
113 gendarme/tools/Makefile
114 gendarme/tools/supported/Makefile
115 gendarme/tools/supported/gd2i/Makefile
116+gendarme/tools/supported/templates/Makefile
117 gendarme/tools/unsupported/Makefile
118 gendarme/tools/unsupported/mapper/Makefile
119 gendarme/tools/unsupported/typeref/Makefile
120diff --git a/docbrowser/Makefile.am b/docbrowser/Makefile.am
121index a1a2626..065c430 100644
122--- a/docbrowser/Makefile.am
123+++ b/docbrowser/Makefile.am
124@@ -40,6 +40,7 @@ browser_sources = \
125 $(srcdir)/list.cs \
126 $(srcdir)/elabel.cs \
127 $(srcdir)/history.cs \
128+ $(srcdir)/editing.cs \
129 $(srcdir)/Contributions.cs \
130 $(srcdir)/XmlNodeWriter.cs \
131 $(srcdir)/IHtmlRender.cs \
132@@ -67,7 +68,7 @@ admin_sources = \
133 $(srcdir)/admin.cs \
134 $(srcdir)/Contributions.cs
135
136-browser_assemblies = $(GTK_SHARP_LIBS) $(MONODOC_LIBS) $(GNOME_SHARP_LIBS) -r:System.Web.Services
137+browser_assemblies = $(GTK_SHARP_LIBS) $(MONODOC_LIBS) $(GNOME_SHARP_LIBS) -r:System.Web.Services -r:System.Web
138 # we insert gtkhtml libs if we have them for printing
139 geckorender_assemblies = $(GTK_SHARP_LIBS) $(GTKHTML_SHARP_LIBS) $(GECKO_SHARP_LIBS) $(GNOME_SHARP_LIBS) $(MONODOC_LIBS) -r:browser.exe
140 gtkhtmlrender_assemblies = $(GTK_SHARP_LIBS) $(GTKHTML_SHARP_LIBS) $(GNOME_SHARP_LIBS) $(MONODOC_LIBS) -r:browser.exe
141diff --git a/docbrowser/browser.cs b/docbrowser/browser.cs
142index 5cc85e2..b9eb66f 100644
143--- a/docbrowser/browser.cs
144+++ b/docbrowser/browser.cs
145@@ -60,7 +60,7 @@ class Driver {
146 v => sources.Add (v) },
147 { "edit=",
148 "Edit mdoc(5) XML documentation found within {PATH}.",
149- v => RootTree.UncompiledHelpSources.Add (v) },
150+ v => RootTree.AddUncompiledSource (v) },
151 { "engine=",
152 "Specify which HTML rendering {ENGINE} to use:\n" +
153 " " + string.Join ("\n ", engines) + "\n" +
154@@ -119,6 +119,9 @@ class Driver {
155
156 List<string> topics = p.Parse (args);
157
158+ if (basedir == null)
159+ basedir = Directory.GetParent (System.Reflection.Assembly.GetExecutingAssembly ().Location).FullName;
160+
161 if (show_version) {
162 Console.WriteLine ("Mono Documentation Browser");
163 Version ver = Assembly.GetExecutingAssembly ().GetName ().Version;
164@@ -132,7 +135,7 @@ class Driver {
165 return r;
166 }
167
168- if (mergeConfigFile != null) {
169+ /*if (mergeConfigFile != null) {
170 ArrayList targetDirs = new ArrayList ();
171
172 for (int i = 0; i < topics.Count; i++)
173@@ -145,7 +148,7 @@ class Driver {
174
175 e.Merge ();
176 return 0;
177- }
178+ }*/
179
180 if (r != 0 || !show_gui)
181 return r;
182@@ -257,6 +260,7 @@ public class Browser {
183 TreeView search_tree;
184 TreeStore search_store;
185 SearchableIndex search_index;
186+ ArrayList searchResults = new ArrayList (20);
187 string highlight_text;
188 [Glade.Widget] VBox search_vbox;
189 ProgressPanel ppanel;
190@@ -578,6 +582,7 @@ public class Browser {
191 Result r = search_index.Search (term);
192 if (r == null)
193 return; //There was a problem with the index
194+ searchResults.Add (r);
195 //insert the results in the tree
196 TreeIter iter;
197
198@@ -622,7 +627,7 @@ public class Browser {
199 return;
200 int i_0 = p.Indices [0];
201 int i_1 = p.Indices [1];
202- Result res = (Result) search_index.Results [i_0];
203+ Result res = (Result) searchResults [i_0];
204 TreeIter parent;
205 model.IterParent (out parent, iter);
206 string term = (string) search_store.GetValue (parent, 0);
207@@ -648,21 +653,21 @@ public class Browser {
208 void TextLarger (object obj, EventArgs args)
209 {
210 SettingsHandler.Settings.preferred_font_size += 10;
211- HelpSource.CssCode = null;
212+ //HelpSource.CssCode = null;
213 Reload ();
214 SettingsHandler.Save ();
215 }
216 void TextSmaller (object obj, EventArgs args)
217 {
218 SettingsHandler.Settings.preferred_font_size -= 10;
219- HelpSource.CssCode = null;
220+ //HelpSource.CssCode = null;
221 Reload ();
222 SettingsHandler.Save ();
223 }
224 void TextNormal (object obj, EventArgs args)
225 {
226 SettingsHandler.Settings.preferred_font_size = 100;
227- HelpSource.CssCode = null;
228+ //HelpSource.CssCode = null;
229 Reload ();
230 SettingsHandler.Save ();
231 }
232@@ -733,6 +738,15 @@ public class Browser {
233
234 Node node;
235
236+ /*
237+ * The webkit library converts the url titles (N:, T:, etc.) to lower case (n:, t:, etc.)
238+ * when clicking on a link. Therefore we need to convert them to upper case, since the
239+ * monodoc backend only understands upper case titles (except for root:, afaik).
240+ */
241+ string[] urlParts = url.Split (':');
242+ if (urlParts [0].Length == 1)
243+ url = urlParts [0].ToUpper () + url.Substring (1);
244+
245 Console.Error.WriteLine ("Trying: {0}", url);
246 try {
247 string res = Browser.GetHtml (url, null, help_tree, out node);
248@@ -785,8 +799,8 @@ public class Browser {
249 //
250 string tabTitle;
251 tabTitle = matched_node.Caption; //Normal title
252- string[] parts = matched_node.URL.Split('/', '#');
253- if(matched_node.URL != null && matched_node.URL.StartsWith("ecma:")) {
254+ string[] parts = matched_node.PublicUrl.Split('/', '#');
255+ if(matched_node.PublicUrl != null && matched_node.PublicUrl.StartsWith("ecma:")) {
256 if(parts.Length == 3 && parts[2] != String.Empty) { //List of Members, properties, events, ...
257 tabTitle = parts[1] + ": " + matched_node.Caption;
258 } else if(parts.Length >= 4) { //Showing a concrete Member, property, ...
259@@ -937,6 +951,7 @@ ExtLoop:
260 void delete_event_cb (object o, DeleteEventArgs args)
261 {
262 Application.Quit ();
263+ args.RetVal = true;
264 }
265 void on_print_activate (object sender, EventArgs e)
266 {
267@@ -1691,7 +1706,7 @@ ExtLoop:
268
269 void OnOkClicked (object sender, EventArgs a)
270 {
271- CommentService service = new CommentService();
272+ //CommentService service = new CommentService();
273 // todo
274 newcomment.Hide ();
275 }
276@@ -2010,7 +2025,7 @@ public class TreeBrowser {
277 if (tree_view.Selection.GetSelected (out model, out iter)){
278 Node n = (Node) iter_to_node [iter];
279
280- string url = n.URL;
281+ string url = n.PublicUrl;
282 Node match;
283 string s;
284
285@@ -2038,7 +2053,7 @@ public class TreeBrowser {
286 return;
287 }
288
289- ((Browser)browser).Render ("<h1>Unhandled URL</h1>" + "<p>Functionality to view the resource <i>" + n.URL + "</i> is not available on your system or has not yet been implemented.</p>", null, url);
290+ ((Browser)browser).Render ("<h1>Unhandled URL</h1>" + "<p>Functionality to view the resource <i>" + n.PublicUrl + "</i> is not available on your system or has not yet been implemented.</p>", null, url);
291 }
292 }
293 }
294@@ -2702,7 +2717,7 @@ public class Tab : Notebook {
295 string [] uSplit = EditingUtils.ParseEditUrl (edit_url);
296
297 if (uSplit[0].StartsWith ("monodoc:"))
298- EditingUtils.SaveChange (edit_url, browser.help_tree, edit_node, EcmaHelpSource.GetNiceUrl (browser.CurrentTab.CurrentNode));
299+ EditingUtils.SaveChange (edit_url, browser.help_tree, edit_node, GetNiceUrl (browser.CurrentTab.CurrentNode));
300 else if (uSplit[0].StartsWith ("file:"))
301 EditingUtils.SaveChange (edit_url, browser.help_tree, edit_node, String.Empty);
302 else
303@@ -2711,6 +2726,49 @@ public class Tab : Notebook {
304 history.ActivateCurrent ();
305 }
306
307+ public static string GetNiceUrl (Node node) {
308+ if (node.Element.StartsWith("N:"))
309+ return node.Element;
310+ string name, full;
311+ int bk_pos = node.Caption.IndexOf (' ');
312+ // node from an overview
313+ if (bk_pos != -1) {
314+ name = node.Caption.Substring (0, bk_pos);
315+ full = node.Parent.Caption + "." + name.Replace ('.', '+');
316+ return "T:" + full;
317+ }
318+ // node that lists constructors, methods, fields, ...
319+ if ((node.Caption == "Constructors") || (node.Caption == "Fields") || (node.Caption == "Events")
320+ || (node.Caption == "Members") || (node.Caption == "Properties") || (node.Caption == "Methods")
321+ || (node.Caption == "Operators")) {
322+ bk_pos = node.Parent.Caption.IndexOf (' ');
323+ name = node.Parent.Caption.Substring (0, bk_pos);
324+ full = node.Parent.Parent.Caption + "." + name.Replace ('.', '+');
325+ return "T:" + full + "/" + node.Element;
326+ }
327+ int pr_pos = node.Caption.IndexOf ('(');
328+ // node from a constructor
329+ if (node.Parent.Element == "C") {
330+ name = node.Parent.Parent.Parent.Caption;
331+ int idx = node.PublicUrl.IndexOf ('/');
332+ return node.PublicUrl[idx+1] + ":" + name + "." + node.Caption.Replace ('.', '+');
333+ // node from a method with one signature, field, property, operator
334+ } else if (pr_pos == -1) {
335+ bk_pos = node.Parent.Parent.Caption.IndexOf (' ');
336+ name = node.Parent.Parent.Caption.Substring (0, bk_pos);
337+ full = node.Parent.Parent.Parent.Caption + "." + name.Replace ('.', '+');
338+ int idx = node.PublicUrl.IndexOf ('/');
339+ return node.PublicUrl[idx+1] + ":" + full + "." + node.Caption;
340+ // node from a method with several signatures
341+ } else {
342+ bk_pos = node.Parent.Parent.Parent.Caption.IndexOf (' ');
343+ name = node.Parent.Parent.Parent.Caption.Substring (0, bk_pos);
344+ full = node.Parent.Parent.Parent.Parent.Caption + "." + name.Replace ('.', '+');
345+ int idx = node.PublicUrl.IndexOf ('/');
346+ return node.PublicUrl[idx+1] + ":" + full + "." + node.Caption;
347+ }
348+ }
349+
350 void OnCancelEdits (object sender, EventArgs a)
351 {
352 SetMode (Mode.Viewer);
353@@ -2737,6 +2795,7 @@ public class Tab : Notebook {
354
355 StringWriter sw = new StringWriter ();
356 XmlWriter w = new XmlTextWriter (sw);
357+ var converter = new Monodoc.Generators.Html.Ecma2Html ();
358
359 try {
360 edit_node.InnerXml = text_editor.Buffer.Text;
361@@ -2750,7 +2809,7 @@ public class Tab : Notebook {
362 }
363 browser.statusbar.Pop (browser.context_id);
364 browser.statusbar.Push (browser.context_id, "XML OK");
365- string s = HelpSource.BuildHtml (EcmaHelpSource.css_ecma_code, sw.ToString ());
366+ string s = converter.Export (sw.ToString (), new Dictionary<string, string> ());
367 html_preview.Render(s);
368
369 return false;
370diff --git a/docbrowser/editing.cs b/docbrowser/editing.cs
371new file mode 100644
372index 0000000..d7c1e32
373--- /dev/null
374+++ b/docbrowser/editing.cs
375@@ -0,0 +1,519 @@
376+//
377+// editing.cs
378+//
379+// Author:
380+// Ben Maurer (bmaurer@users.sourceforge.net)
381+//
382+// (C) 2003 Ben Maurer
383+//
384+
385+using System;
386+using System.Collections;
387+using System.Collections.Specialized;
388+using System.IO;
389+using System.Text;
390+using System.Xml;
391+using System.Xml.Serialization;
392+using System.Xml.XPath;
393+using System.Web;
394+
395+namespace Monodoc {
396+ public class EditingUtils {
397+
398+ public static string FormatEditUri (string document_identifier, string xpath)
399+ {
400+ return String.Format ("edit:{0}@{1}", HttpUtility.UrlEncode (document_identifier),
401+ HttpUtility.UrlEncode (xpath));
402+ }
403+
404+ public static string GetXPath (XPathNavigator n)
405+ {
406+ switch (n.NodeType) {
407+ case XPathNodeType.Root: return "/";
408+ case XPathNodeType.Attribute: {
409+ string ret = "@" + n.Name;
410+ n.MoveToParent ();
411+ string s = GetXPath (n);
412+ return s + (s == "/" ? "" : "/") + ret;
413+ }
414+
415+ case XPathNodeType.Element: {
416+ string ret = n.Name;
417+ int i = 1;
418+ while (n.MoveToPrevious ()) {
419+ if (n.NodeType == XPathNodeType.Element && n.Name == ret)
420+ i++;
421+ }
422+ ret += "[" + i + "]";
423+ if (n.MoveToParent ()) {
424+ string s = GetXPath (n);
425+ return s + (s == "/" ? "" : "/") + ret;
426+ }
427+ }
428+ break;
429+ }
430+ throw new Exception ("node type not supported for editing");
431+
432+ }
433+
434+ public static XmlNode GetNodeFromUrl (string url, RootTree tree)
435+ {
436+ Console.WriteLine ("Url is: {0}", url);
437+ string [] uSplit = ParseEditUrl (url);
438+ Console.WriteLine ("Results are: {0}\n{1}\n{2}", uSplit [0], uSplit [1], uSplit [2]);
439+
440+ string xp = uSplit [2];
441+ string id = uSplit [1];
442+
443+ XmlDocument d;
444+
445+ if (uSplit[0].StartsWith("monodoc:///")) {
446+ int prov = int.Parse (uSplit [0].Substring("monodoc:///".Length));
447+ d = tree.GetHelpSourceFromId (prov).GetHelpXmlWithChanges (id);
448+ } else if (uSplit[0].StartsWith("file:")) {
449+ d = new XmlDocument();
450+ d.PreserveWhitespace = true;
451+ d.Load(uSplit[0].Substring(5));
452+ } else {
453+ throw new NotImplementedException("Don't know how to load " + url);
454+ }
455+
456+ return d.SelectSingleNode (xp);
457+
458+ }
459+
460+ public static void SaveChange (string url, RootTree tree, XmlNode node, string node_url)
461+ {
462+ /*string [] uSplit = ParseEditUrl (url);
463+
464+ string xp = uSplit [2];
465+ string id = uSplit [1];
466+
467+ if (uSplit[0].StartsWith("monodoc:///")) {
468+ int prov = int.Parse (uSplit [0].Substring("monodoc:///".Length));
469+ HelpSource hs = tree.GetHelpSourceFromId (prov);
470+
471+ changes.AddChange (hs.Name, hs.GetRealPath (id), xp, node, node_url);
472+ changes.Save ();
473+ } else if (uSplit[0].StartsWith("file:")) {
474+ uSplit[0] = uSplit[0].Substring(5);
475+
476+ XmlDocument d = new XmlDocument();
477+ d.PreserveWhitespace = true;
478+ d.Load(uSplit[0]);
479+
480+ XmlNode original = d.SelectSingleNode(xp);
481+ original.ParentNode.ReplaceChild(d.ImportNode(node, true), original);
482+
483+ d.Save(uSplit[0]);
484+ } else {
485+ throw new NotImplementedException("Don't know how to save to " + url);
486+ }*/
487+ }
488+
489+ public static void RemoveChange (string url, RootTree tree)
490+ {
491+ /*string [] uSplit = ParseEditUrl (url);
492+
493+ string xp = uSplit [2];
494+ string id = uSplit [1];
495+
496+ if (uSplit[0].StartsWith("monodoc:///")) {
497+ int prov = int.Parse (uSplit [0].Substring("monodoc:///".Length));
498+ HelpSource hs = tree.GetHelpSourceFromId (prov);
499+
500+ changes.RemoveChange (hs.Name, hs.GetRealPath (id), xp);
501+ changes.Save ();
502+ } else if (uSplit[0].StartsWith("file:")) {
503+ //TODO: Not implemented
504+ }*/
505+ }
506+
507+ public static void RenderEditPreview (string url, RootTree tree, XmlNode new_node, XmlWriter w)
508+ {
509+ string [] uSplit = ParseEditUrl (url);
510+
511+ if (uSplit[0].StartsWith("monodoc:///")) {
512+ int prov = int.Parse (uSplit [0].Substring("monodoc:///".Length));
513+ HelpSource hs = tree.GetHelpSourceFromId (prov);
514+ hs.RenderPreviewDocs (new_node, w);
515+ } else {
516+ foreach (HelpSource hs in tree.HelpSources) {
517+ if (hs is Monodoc.Providers.EcmaUncompiledHelpSource) {
518+ // It doesn't matter which EcmaHelpSource is chosen.
519+ hs.RenderPreviewDocs (new_node, w);
520+ break;
521+ }
522+ }
523+ }
524+ }
525+
526+ public static string [] ParseEditUrl (string url)
527+ {
528+ if (!url.StartsWith ("edit:"))
529+ throw new Exception ("wtf");
530+
531+ string [] parts = url.Split ('@');
532+ if (parts.Length != 2)
533+ throw new Exception (String.Format ("invalid editing url {0}", parts.Length));
534+
535+ string xp = HttpUtility.UrlDecode (parts [1]);
536+ parts = HttpUtility.UrlDecode (parts [0]).Substring ("edit:".Length).Split ('@');
537+ if (parts.Length == 1) {
538+ string p = parts[0];
539+ parts = new string[2];
540+ parts[0] = p;
541+ parts[1] = "";
542+ }
543+
544+ return new string [] {parts [0], parts [1], xp};
545+ }
546+
547+ public static void AccountForChanges (XmlDocument d, string doc_set, string real_file)
548+ {
549+ try {
550+ FileChangeset fcs = changes.GetChangeset (doc_set, real_file);
551+ if (fcs == null)
552+ return;
553+
554+ foreach (Change c in fcs.Changes) {
555+ // Filter out old changes
556+ if (c.FromVersion != RootTree.MonodocVersion)
557+ continue;
558+
559+ XmlNode old = d.SelectSingleNode (c.XPath);
560+ if (old != null)
561+ old.ParentNode.ReplaceChild (d.ImportNode (c.NewNode, true), old);
562+ }
563+ } catch {
564+ return;
565+ }
566+ }
567+
568+ public static GlobalChangeset changes = GlobalChangeset.Load ();
569+
570+ static public GlobalChangeset GetChangesFrom (int starting_serial_id)
571+ {
572+ return changes.GetFrom (starting_serial_id);
573+ }
574+ }
575+
576+#region Data Model
577+ public class GlobalChangeset {
578+
579+ public static XmlSerializer serializer = new XmlSerializer (typeof (GlobalChangeset));
580+ static string changeset_file = Path.Combine (SettingsHandler.Path, "changeset.xml");
581+ static string changeset_backup_file = Path.Combine (SettingsHandler.Path, "changeset.xml~");
582+
583+ public static GlobalChangeset Load ()
584+ {
585+ try {
586+ if (File.Exists (changeset_file))
587+ return LoadFromFile (changeset_file);
588+ } catch {}
589+
590+ return new GlobalChangeset ();
591+ }
592+
593+ public static GlobalChangeset LoadFromFile (string fileName)
594+ {
595+ using (Stream s = File.OpenRead (fileName)) {
596+ return (GlobalChangeset) serializer.Deserialize (s);
597+ }
598+ }
599+
600+ public void Save ()
601+ {
602+ SettingsHandler.EnsureSettingsDirectory ();
603+
604+ try {
605+ if (File.Exists(changeset_file)) // create backup copy
606+ File.Copy (changeset_file, changeset_backup_file, true);
607+
608+ using (FileStream fs = File.Create (changeset_file)){
609+ serializer.Serialize (fs, this);
610+ }
611+ } catch (Exception e) {
612+ Console.WriteLine ("Error while saving changes. " + e);
613+ if (File.Exists(changeset_backup_file)) // if saving fails then use backup if we have one
614+ File.Copy (changeset_backup_file, changeset_file, true);
615+ else
616+ File.Delete (changeset_file); // if no backup, delete invalid changeset
617+ }
618+ }
619+
620+ static void VerifyDirectoryExists (DirectoryInfo d) {
621+ if (d.Exists)
622+ return;
623+
624+ VerifyDirectoryExists (d.Parent);
625+ d.Create ();
626+ }
627+
628+ [XmlElement ("DocSetChangeset", typeof (DocSetChangeset))]
629+ public ArrayList DocSetChangesets = new ArrayList ();
630+
631+ public FileChangeset GetChangeset (string doc_set, string real_file)
632+ {
633+ foreach (DocSetChangeset dscs in DocSetChangesets) {
634+ if (dscs.DocSet != doc_set)
635+ continue;
636+
637+ foreach (FileChangeset fcs in dscs.FileChangesets) {
638+ if (fcs.RealFile == real_file)
639+ return fcs;
640+ }
641+ }
642+
643+ return null;
644+ }
645+
646+ public int Count {
647+ get {
648+ int count = 0;
649+
650+ foreach (DocSetChangeset dscs in DocSetChangesets){
651+ foreach (FileChangeset fcs in dscs.FileChangesets){
652+ count += fcs.Changes.Count;
653+ }
654+ }
655+
656+ return count;
657+ }
658+ }
659+
660+ Change NewChange (string xpath, XmlNode new_node, string node_url)
661+ {
662+ Change new_change = new Change ();
663+ new_change.XPath = xpath;
664+ new_change.NewNode = new_node;
665+ new_change.NodeUrl = node_url;
666+
667+ Console.WriteLine ("New serial:" + SettingsHandler.Settings.SerialNumber);
668+ new_change.Serial = SettingsHandler.Settings.SerialNumber;
669+
670+ return new_change;
671+ }
672+
673+ public void AddChange (string doc_set, string real_file, string xpath, XmlNode new_node, string node_url)
674+ {
675+ FileChangeset new_file_change_set;
676+ Change new_change = NewChange (xpath, new_node, node_url);
677+
678+ if (real_file == null)
679+ throw new Exception ("Could not find real_file. Please talk to Miguel or Ben about this");
680+
681+ foreach (DocSetChangeset dscs in DocSetChangesets) {
682+ if (dscs.DocSet != doc_set)
683+ continue;
684+
685+ foreach (FileChangeset fcs in dscs.FileChangesets) {
686+ if (fcs.RealFile != real_file)
687+ continue;
688+
689+ foreach (Change c in fcs.Changes) {
690+ if (c.XPath == xpath) {
691+ c.NewNode = new_node;
692+ c.Serial = SettingsHandler.Settings.SerialNumber;
693+ return;
694+ }
695+ }
696+
697+ fcs.Changes.Add (new_change);
698+ return;
699+
700+ }
701+
702+ new_file_change_set = new FileChangeset ();
703+ new_file_change_set.RealFile = real_file;
704+ new_file_change_set.Changes.Add (new_change);
705+ dscs.FileChangesets.Add (new_file_change_set);
706+ return;
707+
708+ }
709+
710+ DocSetChangeset new_dcs = new DocSetChangeset ();
711+ new_dcs.DocSet = doc_set;
712+
713+ new_file_change_set = new FileChangeset ();
714+ new_file_change_set.RealFile = real_file;
715+
716+ new_file_change_set.Changes.Add (new_change);
717+ new_dcs.FileChangesets.Add (new_file_change_set);
718+ DocSetChangesets.Add (new_dcs);
719+ }
720+
721+ public void RemoveChange (string doc_set, string real_file, string xpath)
722+ {
723+ if (real_file == null)
724+ throw new Exception ("Could not find real_file. Please talk to Miguel or Ben about this");
725+
726+ for (int i = 0; i < DocSetChangesets.Count; i++) {
727+ DocSetChangeset dscs = DocSetChangesets [i] as DocSetChangeset;
728+ if (dscs.DocSet != doc_set)
729+ continue;
730+
731+ for (int j = 0; j < dscs.FileChangesets.Count; j++) {
732+ FileChangeset fcs = dscs.FileChangesets [j] as FileChangeset;
733+ if (fcs.RealFile != real_file)
734+ continue;
735+
736+ for (int k = 0; k < fcs.Changes.Count; k++) {
737+ Change c = fcs.Changes [k] as Change;
738+ if (c.XPath == xpath) {
739+ fcs.Changes.Remove (c);
740+ break;
741+ }
742+ }
743+ if (fcs.Changes.Count == 0)
744+ dscs.FileChangesets.Remove (fcs);
745+ }
746+
747+ if (dscs.FileChangesets.Count == 0)
748+ DocSetChangesets.Remove (dscs);
749+ }
750+ }
751+
752+ public GlobalChangeset GetFrom (int starting_serial_id)
753+ {
754+ GlobalChangeset s = null;
755+
756+ foreach (DocSetChangeset dscs in DocSetChangesets){
757+ object o = dscs.GetFrom (starting_serial_id);
758+ if (o == null)
759+ continue;
760+ if (s == null)
761+ s = new GlobalChangeset ();
762+ s.DocSetChangesets.Add (o);
763+ }
764+ return s;
765+ }
766+ }
767+
768+ public class DocSetChangeset {
769+ [XmlAttribute] public string DocSet;
770+
771+ [XmlElement ("FileChangeset", typeof (FileChangeset))]
772+ public ArrayList FileChangesets = new ArrayList ();
773+
774+ public DocSetChangeset GetFrom (int starting_serial_id)
775+ {
776+ DocSetChangeset dsc = null;
777+
778+ foreach (FileChangeset fcs in FileChangesets){
779+ object o = fcs.GetFrom (starting_serial_id);
780+ if (o == null)
781+ continue;
782+ if (dsc == null){
783+ dsc = new DocSetChangeset ();
784+ dsc.DocSet = DocSet;
785+ }
786+ dsc.FileChangesets.Add (o);
787+ }
788+ return dsc;
789+ }
790+ }
791+
792+ public class FileChangeset {
793+ [XmlAttribute] public string RealFile;
794+
795+ [XmlElement ("Change", typeof (Change))]
796+ public ArrayList Changes = new ArrayList ();
797+
798+ public FileChangeset GetFrom (int starting_serial_id)
799+ {
800+ FileChangeset fcs = null;
801+
802+ foreach (Change c in Changes){
803+ if (c.Serial < starting_serial_id)
804+ continue;
805+ if (fcs == null){
806+ fcs = new FileChangeset ();
807+ fcs.RealFile = RealFile;
808+ }
809+ fcs.Changes.Add (c);
810+ }
811+ return fcs;
812+ }
813+ }
814+
815+ public class Change {
816+ [XmlAttribute] public string XPath;
817+ [XmlAttribute] public int FromVersion = RootTree.MonodocVersion;
818+ [XmlAttribute] public string NodeUrl;
819+
820+ public XmlNode NewNode;
821+
822+ public int Serial;
823+
824+ bool applied = false;
825+
826+ //
827+ // These are not a property, because we dont want them serialized;
828+ // Only used by the Admin Client.
829+ //
830+ public bool Applied ()
831+ {
832+ return applied;
833+ }
834+
835+ public void SetApplied (bool value)
836+ {
837+ applied = value;
838+ }
839+ }
840+#endregion
841+
842+ public class EditMerger {
843+ GlobalChangeset changeset;
844+ ArrayList targetDirs;
845+
846+ public EditMerger (GlobalChangeset changeset, ArrayList targetDirs)
847+ {
848+ this.changeset = changeset;
849+ this.targetDirs = targetDirs;
850+ }
851+
852+ public void Merge ()
853+ {
854+ foreach (DocSetChangeset dsc in changeset.DocSetChangesets) {
855+ bool merged = false;
856+ foreach (string path in targetDirs) {
857+ if (File.Exists (Path.Combine (path, dsc.DocSet + ".source"))) {
858+ Merge (dsc, path);
859+ merged = true;
860+ break;
861+ }
862+ }
863+ if (!merged) Console.WriteLine ("Could not merge docset {0}", dsc.DocSet);
864+ }
865+ }
866+
867+ void Merge (DocSetChangeset dsc, string path)
868+ {
869+ Console.WriteLine ("Merging changes in {0} ({1})", dsc.DocSet, path);
870+
871+ foreach (FileChangeset fcs in dsc.FileChangesets) {
872+ if (File.Exists (Path.Combine (path, fcs.RealFile)))
873+ Merge (fcs, path);
874+ else
875+ Console.WriteLine ("\tCould not find file {0}", Path.Combine (path, fcs.RealFile));
876+ }
877+ }
878+
879+ void Merge (FileChangeset fcs, string path)
880+ {
881+ XmlDocument d = new XmlDocument ();
882+ d.Load (Path.Combine (path, fcs.RealFile));
883+
884+ foreach (Change c in fcs.Changes) {
885+ XmlNode old = d.SelectSingleNode (c.XPath);
886+ if (old != null)
887+ old.ParentNode.ReplaceChild (d.ImportNode (c.NewNode, true), old);
888+ }
889+
890+ d.Save (Path.Combine (path, fcs.RealFile));
891+ }
892+ }
893+}
894+
895diff --git a/docbrowser/monodoc.in b/docbrowser/monodoc.in
896index a532918..806b163 100644
897--- a/docbrowser/monodoc.in
898+++ b/docbrowser/monodoc.in
899@@ -75,7 +75,7 @@ elif test x@MOZILLA_HOME@ != x; then
900 if [ -f @MOZILLA_HOME@/chrome/comm.jar ]; then
901 MOZILLA_HOME=@MOZILLA_HOME@
902 fi
903-elif grep GRE_PATH /etc/gre.d/*.conf > /dev/null ; then
904+elif grep -qs GRE_PATH /etc/gre.d/*.conf > /dev/null ; then
905 MOZILLA_HOME=$(grep -h GRE_PATH= /etc/gre.d/*.conf | cut -d '"' -f 2 -d = | head -n 1)
906 elif [ $(which xulrunner 2> /dev/null) ] > /dev/null ; then
907 MOZILLA_FIVE_HOME=`getdirectory xulrunner`
908diff --git a/gendarme/AssemblyStaticInfo.cs b/gendarme/AssemblyStaticInfo.cs
909index 2ca215e..130eb9d 100644
910--- a/gendarme/AssemblyStaticInfo.cs
911+++ b/gendarme/AssemblyStaticInfo.cs
912@@ -18,10 +18,9 @@ using System.Security.Permissions;
913 [assembly: AssemblyCopyright ("Copyright (C) 2005-2011 Novell, Inc. and contributors")]
914 [assembly: AssemblyCompany ("Novell, Inc.")]
915
916-[assembly: PermissionSet (SecurityAction.RequestMinimum, Unrestricted = true)]
917 [assembly: CLSCompliant (false)]
918 [assembly: ComVisible (false)]
919
920 #if RELEASE
921-[assembly: AssemblyVersion ("2.10.0.0")]
922+[assembly: AssemblyVersion ("2.11.0.0")]
923 #endif
924diff --git a/gendarme/MIT.X11 b/gendarme/MIT.X11
925index 8d90e9d..b3e59de 100644
926--- a/gendarme/MIT.X11
927+++ b/gendarme/MIT.X11
928@@ -1,4 +1,4 @@
929-Copyright (c) 2005-2010 Novell, Inc and the individuals listed on the
930+Copyright (c) 2005-2011 Novell, Inc and the individuals listed on the
931 ChangeLog entries.
932
933 Permission is hereby granted, free of charge, to any person obtaining
934diff --git a/gendarme/Makefile.am b/gendarme/Makefile.am
935index 890f0f2..2d96376 100644
936--- a/gendarme/Makefile.am
937+++ b/gendarme/Makefile.am
938@@ -45,7 +45,8 @@ check-test: all bin/gendarme.exe.config test
939 --ignore=unit-test.ignore --severity=all --confidence=all @unit-test.list
940
941 test-regress: all
942- mono --debug bin/gendarme.exe --config rules/rules.xml --set self-test --log regress.log testcases/*.dll testcases/*.exe
943+ mono --debug bin/gendarme.exe --config rules/rules.xml --set self-test --log regress.log \
944+ --severity=all --confidence=all testcases/*.dll testcases/*.exe
945
946 TEST1 ?= AvoidVisibleConstantFieldTest
947 test1_file = $(shell find rules -name "\.svn" -prune -o -name "*$(TEST1)*" -print)
948@@ -101,16 +102,3 @@ zip-bin: bin extra-bin
949 cd ..; \
950 rm -rf gendarme.$(GENDARME_VERSION);
951
952-instruct.xsd:
953- wget http://www.ohloh.net/instruct.xsd
954-
955-push: instruct.xsd
956- xmllint --schema instruct.xsd gendarme.xml
957-# scp gendarme-2.8preview1-bin.zip $(USER)@upload.ohloh.net:gendarme/files; \
958-# scp gendarme-2.8preview1-win32-setup.zip $(USER)@upload.ohloh.net:gendarme/files; \
959-# scp gendarme.xml $(USER)@upload.ohloh.net:gendarme/instructs
960-
961-pull-log:
962- scp $(USER)@upload.ohloh.net:gendarme/logs/upload.log .
963- cat upload.log
964-
965diff --git a/gendarme/console/ConsoleRunner.cs b/gendarme/console/ConsoleRunner.cs
966index 97afccb..bf9814c 100644
967--- a/gendarme/console/ConsoleRunner.cs
968+++ b/gendarme/console/ConsoleRunner.cs
969@@ -29,6 +29,7 @@
970 using System;
971 using System.Collections.Generic;
972 using System.Diagnostics;
973+using System.Globalization;
974 using System.IO;
975 using System.Linq;
976 using System.Reflection;
977@@ -53,21 +54,23 @@ namespace Gendarme {
978 private string log_file;
979 private string xml_file;
980 private string ignore_file;
981- private string limit;
982- private string severity_filter;
983- private string confidence_filter;
984 private bool help;
985 private bool quiet;
986 private bool version;
987+ private bool console;
988 private List<string> assembly_names;
989
990+ static string [] SplitOptions (string value)
991+ {
992+ return value.ToUpperInvariant ().Split (new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
993+ }
994+
995 // parse severity filter
996 // e.g. Audit,High+ == Audit, High and Critical
997- void ParseSeverity ()
998+ bool ParseSeverity (string filter)
999 {
1000 SeverityBitmask.ClearAll ();
1001- string [] options = severity_filter.ToUpperInvariant ().Split (',');
1002- foreach (string option in options) {
1003+ foreach (string option in SplitOptions (filter)) {
1004 Severity severity;
1005
1006 switch (option) {
1007@@ -101,28 +104,26 @@ namespace Gendarme {
1008 SeverityBitmask.SetAll ();
1009 continue;
1010 default:
1011- continue;
1012+ string msg = String.Format (CultureInfo.CurrentCulture, "Unknown severity level '{0}'", option);
1013+ throw new OptionException (msg, "severity");
1014 }
1015
1016 char end = option [option.Length - 1];
1017 if (end == '+') {
1018 SeverityBitmask.SetDown (severity);
1019- Console.WriteLine ("SetDown {0} -> {1}", severity, SeverityBitmask);
1020 } else if (end == '-') {
1021 SeverityBitmask.SetUp (severity);
1022- Console.WriteLine ("SetUp {0} -> {1}", severity, SeverityBitmask);
1023 } else {
1024 SeverityBitmask.Set (severity);
1025- Console.WriteLine ("Set {0} -> {1}", severity, SeverityBitmask);
1026 }
1027 }
1028+ return true;
1029 }
1030
1031- void ParseConfidence ()
1032+ bool ParseConfidence (string filter)
1033 {
1034 ConfidenceBitmask.ClearAll ();
1035- string [] options = confidence_filter.ToUpperInvariant ().Split (',');
1036- foreach (string option in options) {
1037+ foreach (string option in SplitOptions (filter)) {
1038 Confidence confidence;
1039
1040 switch (option) {
1041@@ -151,7 +152,8 @@ namespace Gendarme {
1042 ConfidenceBitmask.SetAll ();
1043 continue;
1044 default:
1045- continue;
1046+ string msg = String.Format (CultureInfo.CurrentCulture, "Unknown confidence level '{0}'", option);
1047+ throw new OptionException (msg, "confidence");
1048 }
1049
1050 char end = option [option.Length - 1];
1051@@ -163,48 +165,104 @@ namespace Gendarme {
1052 ConfidenceBitmask.Set (confidence);
1053 }
1054 }
1055+ return true;
1056+ }
1057+
1058+ static string ValidateInputFile (string option, string file)
1059+ {
1060+ if (!File.Exists (file)) {
1061+ string msg = String.Format (CultureInfo.CurrentCulture, "File '{0}' could not be found", file);
1062+ throw new OptionException (msg, option);
1063+ }
1064+ return file;
1065+ }
1066+
1067+ static string ValidateOutputFile (string option, string file)
1068+ {
1069+ string msg = String.Empty;
1070+ if (file.Length > 0) {
1071+ string path = Path.GetDirectoryName (file);
1072+ if (path.Length > 0) {
1073+ if (path.IndexOfAny (Path.GetInvalidPathChars ()) != -1)
1074+ msg = String.Format (CultureInfo.CurrentCulture, "Invalid path '{0}'", file);
1075+ else if (!Directory.Exists (path))
1076+ msg = String.Format (CultureInfo.CurrentCulture, "Path '{0}' does not exists", file);
1077+ }
1078+ }
1079+
1080+ string fname = Path.GetFileName (file);
1081+ if ((fname.Length == 0) || (fname.IndexOfAny (Path.GetInvalidFileNameChars ()) != -1)) {
1082+ msg = String.Format (CultureInfo.CurrentCulture, "Filename '{0}' is not valid", fname);
1083+ }
1084+
1085+ if (msg.Length > 0)
1086+ throw new OptionException (msg, option);
1087+
1088+ return file;
1089+ }
1090+
1091+ static string ValidateRuleSet (string ruleSet)
1092+ {
1093+ if (String.IsNullOrEmpty (ruleSet)) {
1094+ throw new OptionException ("Missing rule set name", "set");
1095+ }
1096+ return ruleSet;
1097+ }
1098+
1099+ static int ValidateLimit (string limit)
1100+ {
1101+ int defects_limit;
1102+ if (String.IsNullOrEmpty (limit) || !Int32.TryParse (limit, out defects_limit)) {
1103+ string msg = String.Format (CultureInfo.CurrentCulture, "Invalid value '{0}' to limit defects", limit);
1104+ throw new OptionException (msg, "limit");
1105+ }
1106+ return defects_limit;
1107 }
1108
1109 byte Parse (string [] args)
1110 {
1111+ bool severity = false;
1112+ bool confidence = false;
1113+ // if supplied, use the user limit on defects (otherwise 2^31 is used)
1114+ DefectsLimit = Int32.MaxValue;
1115+
1116 var p = new OptionSet () {
1117- { "config=", v => config_file = v },
1118- { "set=", v => rule_set = v },
1119- { "log=", v => log_file = v },
1120- { "xml=", v => xml_file = v },
1121- { "html=", v => html_file = v },
1122- { "ignore=", v => ignore_file = v },
1123- { "limit=", v => limit = v },
1124- { "severity=", v => severity_filter = v },
1125- { "confidence=",v => confidence_filter = v },
1126+ { "config=", v => config_file = ValidateInputFile ("config", v) },
1127+ { "set=", v => rule_set = ValidateRuleSet (v) },
1128+ { "log=", v => log_file = ValidateOutputFile ("log", v) },
1129+ { "xml=", v => xml_file = ValidateOutputFile ("xml", v) },
1130+ { "html=", v => html_file = ValidateOutputFile ("html", v) },
1131+ { "ignore=", v => ignore_file = ValidateInputFile ("ignore", v) },
1132+ { "limit=", v => DefectsLimit = ValidateLimit (v) },
1133+ { "severity=", v => severity = ParseSeverity (v) },
1134+ { "confidence=",v => confidence = ParseConfidence (v) },
1135 { "v|verbose", v => ++VerbosityLevel },
1136+ { "console", v => console = v != null },
1137 { "quiet", v => quiet = v != null },
1138 { "version", v => version = v != null },
1139 { "h|?|help", v => help = v != null },
1140 };
1141- assembly_names = p.Parse (args);
1142
1143- // if supplied, use the user limit on defects (otherwise 2^31 is used)
1144- int defects_limit;
1145- if (String.IsNullOrEmpty (limit) || !Int32.TryParse (limit, out defects_limit))
1146- defects_limit = Int32.MaxValue;
1147- DefectsLimit = defects_limit;
1148+ try {
1149+ assembly_names = p.Parse (args);
1150+ }
1151+ catch (OptionException e) {
1152+ Console.WriteLine ("Error parsing option '{0}' : {1}", e.OptionName, e.Message);
1153+ Console.WriteLine ();
1154+ return 1;
1155+ }
1156
1157 // by default the runner will ignore Audit and Low severity defects
1158- if (String.IsNullOrEmpty (severity_filter)) {
1159+ if (!severity) {
1160 SeverityBitmask.SetAll ();
1161 SeverityBitmask.Clear (Severity.Audit);
1162 SeverityBitmask.Clear (Severity.Low);
1163- } else {
1164- ParseSeverity ();
1165 }
1166
1167 // by default the runner will ignore Low confidence defects
1168- if (String.IsNullOrEmpty (confidence_filter)) {
1169+ if (!confidence) {
1170 ConfidenceBitmask.SetAll ();
1171 ConfidenceBitmask.Clear (Confidence.Low);
1172- } else {
1173- ParseConfidence ();
1174 }
1175
1176 return (byte) ((assembly_names.Count > 0) ? 0 : 1);
1177@@ -281,7 +339,7 @@ namespace Gendarme {
1178 }
1179
1180 // generate text report (default, to console, if xml and html aren't specified)
1181- if ((log_file != null) || ((xml_file == null) && (html_file == null))) {
1182+ if (console || (log_file != null) || ((xml_file == null) && (html_file == null))) {
1183 using (TextResultWriter writer = new TextResultWriter (this, log_file)) {
1184 writer.Report ();
1185 }
1186@@ -380,7 +438,7 @@ namespace Gendarme {
1187 private static string TimeToString (TimeSpan time)
1188 {
1189 if (time >= TimeSpan.FromMilliseconds (100))
1190- return string.Format ("{0:0.0} seconds", time.TotalSeconds);
1191+ return String.Format (CultureInfo.CurrentCulture, "{0:0.0} seconds", time.TotalSeconds);
1192 else
1193 return "<0.1 seconds";
1194 }
1195@@ -441,9 +499,10 @@ namespace Gendarme {
1196 if (null != log_file || null != xml_file || null != html_file) {
1197 List<string> files = new List<string> (new string [] { log_file, xml_file, html_file });
1198 files.RemoveAll (string.IsNullOrEmpty);
1199- hint = string.Format ("Report{0} written to: {1}.",
1200+ hint = String.Format (CultureInfo.CurrentCulture, "Report{0} written to: {1}.",
1201 (files.Count > 1) ? "s" : string.Empty,
1202- string.Join (",", files.Select (file => string.Format ("`{0}'", file)).ToArray ()));
1203+ string.Join (",", files.Select (file =>
1204+ String.Format (CultureInfo.CurrentCulture, "`{0}'", file)).ToArray ()));
1205 }
1206
1207 if (Defects.Count == 0)
1208@@ -519,6 +578,7 @@ namespace Gendarme {
1209 Console.WriteLine (" --confidence [all | [[low | normal | high | total][+|-]],...");
1210 Console.WriteLine ("\t\t\tFilter defects for the specified confidence levels.");
1211 Console.WriteLine ("\t\t\tDefault is 'normal+'");
1212+ Console.WriteLine (" --console\t\tShow defects on the console even if --log, --xml or --html are specified.");
1213 Console.WriteLine (" --quiet\t\tUsed to disable progress and other information which is normally written to stdout.");
1214 Console.WriteLine (" --v\t\t\tWhen present additional progress information is written to stdout (can be used multiple times).");
1215 Console.WriteLine (" assemblies\t\tSpecify the assemblies to verify.");
1216diff --git a/gendarme/console/Helpers.cs b/gendarme/console/Helpers.cs
1217index c399452..3ef8361 100644
1218--- a/gendarme/console/Helpers.cs
1219+++ b/gendarme/console/Helpers.cs
1220@@ -38,7 +38,7 @@ namespace Gendarme {
1221 {
1222 Assembly executing = Assembly.GetExecutingAssembly ();
1223 foreach (string resource in executing.GetManifestResourceNames ()) {
1224- if (resource.EndsWith (resourceName))
1225+ if (resource.EndsWith (resourceName, StringComparison.Ordinal))
1226 return executing.GetManifestResourceStream (resource);
1227 }
1228 return null;
1229diff --git a/gendarme/console/IgnoreFileList.cs b/gendarme/console/IgnoreFileList.cs
1230index acf0d1d..b714ded 100644
1231--- a/gendarme/console/IgnoreFileList.cs
1232+++ b/gendarme/console/IgnoreFileList.cs
1233@@ -61,13 +61,13 @@ namespace Gendarme {
1234
1235 private void Parse ()
1236 {
1237+ char [] buffer = new char [4096];
1238 while (files.Count > 0) {
1239 string fileName = files.Pop ();
1240- using (StreamReader sr = new StreamReader (fileName)) {
1241- string s = sr.ReadLine ();
1242- while (s != null) {
1243- ProcessLine (s);
1244- s = sr.ReadLine ();
1245+ using (StreamLineReader sr = new StreamLineReader (fileName)) {
1246+ while (!sr.EndOfStream) {
1247+ int length = sr.ReadLine (buffer, 0, buffer.Length);
1248+ ProcessLine (buffer, length);
1249 }
1250 }
1251 }
1252@@ -87,19 +87,33 @@ namespace Gendarme {
1253 rules.Add (rule);
1254 }
1255
1256- private void ProcessLine (string line)
1257+ static string GetString (char [] buffer, int length)
1258 {
1259- if (line.Length < 1)
1260+ // skip the 'type' + ':' characters when looking for whitespace separator(s)
1261+ int start = 2;
1262+ while (Char.IsWhiteSpace (buffer [start]) && (start < buffer.Length))
1263+ start++;
1264+
1265+ int end = length;
1266+ while (Char.IsWhiteSpace (buffer [end]) && (end >= start))
1267+ end--;
1268+
1269+ return new string (buffer, start, end - start);
1270+ }
1271+
1272+ private void ProcessLine (char [] buffer, int length)
1273+ {
1274+ if (length < 1)
1275 return;
1276
1277- switch (line [0]) {
1278+ switch (buffer [0]) {
1279 case '#': // comment
1280 break;
1281 case 'R': // rule
1282- current_rule = line.Substring (line.LastIndexOf (' ') + 1);
1283+ current_rule = GetString (buffer, length);
1284 break;
1285 case 'A': // assembly - we support Name, FullName and *
1286- string target = line.Substring (2).Trim ();
1287+ string target = GetString (buffer, length);
1288 if (target == "*") {
1289 foreach (AssemblyDefinition assembly in Runner.Assemblies) {
1290 Add (assemblies, current_rule, assembly.Name.FullName);
1291@@ -109,19 +123,19 @@ namespace Gendarme {
1292 }
1293 break;
1294 case 'T': // type (no space allowed)
1295- Add (types, current_rule, line.Substring (line.LastIndexOf (' ') + 1));
1296+ Add (types, current_rule, GetString (buffer, length));
1297 break;
1298 case 'M': // method
1299- Add (methods, current_rule, line.Substring (2).Trim ());
1300+ Add (methods, current_rule, GetString (buffer, length));
1301 break;
1302 case 'N': // namespace - special case (no need to resolve)
1303- base.Add (current_rule, NamespaceDefinition.GetDefinition (line.Substring (2).Trim ()));
1304+ base.Add (current_rule, NamespaceDefinition.GetDefinition (GetString (buffer, length)));
1305 break;
1306 case '@': // include file
1307- files.Push (line.Substring (2).Trim ());
1308+ files.Push (GetString (buffer, length));
1309 break;
1310 default:
1311- Console.Error.WriteLine ("Bad ignore entry : '{0}'", line);
1312+ Console.Error.WriteLine ("Bad ignore entry : '{0}'", new string (buffer));
1313 break;
1314 }
1315 }
1316@@ -148,14 +162,13 @@ namespace Gendarme {
1317
1318 foreach (ModuleDefinition module in assembly.Modules) {
1319 foreach (TypeDefinition type in module.GetAllTypes ()) {
1320- if (types.TryGetValue (type.FullName, out rules)) {
1321+ if (types.TryGetValue (type.GetFullName (), out rules)) {
1322 AddList (type, rules);
1323 }
1324
1325 if (type.HasMethods) {
1326 foreach (MethodDefinition method in type.Methods) {
1327- // FIXME avoid (allocations in) ToString call
1328- if (methods.TryGetValue (method.ToString (), out rules)) {
1329+ if (methods.TryGetValue (method.GetFullName (), out rules)) {
1330 AddList (method, rules);
1331 }
1332 }
1333diff --git a/gendarme/console/Makefile.am b/gendarme/console/Makefile.am
1334index f74ab23..43c0a4a 100644
1335--- a/gendarme/console/Makefile.am
1336+++ b/gendarme/console/Makefile.am
1337@@ -30,7 +30,7 @@ gendarme_prefix_resources = $(addprefix $(srcdir)/, $(gendarme_resources))
1338 gendarme_build_resources = $(foreach res,$(gendarme_prefix_resources), $(addprefix -resource:,$(res)),$(notdir $(res)))
1339
1340 ../bin/gendarme.exe: $(gendarme_build_sources) $(gendarme_prefix_resources)
1341- $(GMCS) $(GENDARME_OPTIONS) -r:$(CECIL_ASM) -r:System.Xml.Linq -r:../bin/Gendarme.Framework.dll \
1342+ $(MCS) $(GENDARME_OPTIONS) -r:$(CECIL_ASM) -r:System.Xml.Linq -r:../bin/Gendarme.Framework.dll \
1343 -out:$@ $(gendarme_build_sources) $(gendarme_build_resources)
1344
1345 self-test: ../bin/gendarme.exe
1346diff --git a/gendarme/console/Settings.cs b/gendarme/console/Settings.cs
1347index 3ecafec..23b5429 100644
1348--- a/gendarme/console/Settings.cs
1349+++ b/gendarme/console/Settings.cs
1350@@ -4,7 +4,7 @@
1351 // Authors:
1352 // Sebastien Pouliot <sebastien@ximian.com>
1353 //
1354-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
1355+// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
1356 //
1357 // Permission is hereby granted, free of charge, to any person obtaining
1358 // a copy of this software and associated documentation files (the
1359@@ -27,6 +27,7 @@
1360 //
1361
1362 using System;
1363+using System.Globalization;
1364 using System.IO;
1365 using System.Reflection;
1366 using System.Collections.Generic;
1367@@ -150,7 +151,8 @@ namespace Gendarme {
1368
1369 private void OnValidationErrors (object sender, ValidationEventArgs args)
1370 {
1371- validation_errors.Add (args.Exception.Message.Replace ("XmlSchema error", String.Format ("Error in the configuration file {0}", config_file)));
1372+ validation_errors.Add (args.Exception.Message.Replace ("XmlSchema error",
1373+ String.Format (CultureInfo.CurrentCulture, "Error in the configuration file {0}", config_file)));
1374 }
1375
1376 private void ValidateXmlDocument ()
1377@@ -228,7 +230,8 @@ namespace Gendarme {
1378
1379 static Exception GetException (string message, string ruleName, string propertyName, string value)
1380 {
1381- return new XmlException (String.Format (message + ". Review your configuration file.", ruleName, propertyName, value));
1382+ return new XmlException (String.Format (CultureInfo.CurrentCulture,
1383+ message + ". Review your configuration file.", ruleName, propertyName, value));
1384 }
1385
1386 public bool Load ()
1387diff --git a/gendarme/console/XmlResultWriter.cs b/gendarme/console/XmlResultWriter.cs
1388index 3a5e0f4..3dcdff1 100644
1389--- a/gendarme/console/XmlResultWriter.cs
1390+++ b/gendarme/console/XmlResultWriter.cs
1391@@ -31,6 +31,7 @@
1392 //
1393
1394 using System;
1395+using System.Globalization;
1396 using System.IO;
1397 using System.Linq;
1398 using System.Text;
1399@@ -70,7 +71,7 @@ namespace Gendarme {
1400 {
1401 writer.WriteStartDocument ();
1402 writer.WriteStartElement ("gendarme-output");
1403- writer.WriteAttributeString ("date", DateTime.UtcNow.ToString ());
1404+ writer.WriteAttributeString ("date", DateTime.UtcNow.ToString (CultureInfo.InvariantCulture));
1405 }
1406
1407 protected override void Write ()
1408diff --git a/gendarme/console/gendarme.csproj b/gendarme/console/gendarme.csproj
1409index 4f70bf5..eefae5e 100755
1410--- a/gendarme/console/gendarme.csproj
1411+++ b/gendarme/console/gendarme.csproj
1412@@ -1,5 +1,5 @@
1413 <?xml version="1.0" encoding="utf-8"?>\r
1414-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
1415+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
1416 <PropertyGroup>\r
1417 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
1418 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
1419@@ -12,9 +12,13 @@
1420 <AssemblyName>gendarme</AssemblyName>\r
1421 <FileUpgradeFlags>\r
1422 </FileUpgradeFlags>\r
1423- <OldToolsVersion>2.0</OldToolsVersion>\r
1424+ <OldToolsVersion>3.5</OldToolsVersion>\r
1425 <UpgradeBackupLocation>\r
1426 </UpgradeBackupLocation>\r
1427+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
1428+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
1429+ <SignAssembly>false</SignAssembly>\r
1430+ <AssemblyOriginatorKeyFile>gendarme.snk</AssemblyOriginatorKeyFile>\r
1431 <PublishUrl>http://localhost/gendarme/</PublishUrl>\r
1432 <Install>true</Install>\r
1433 <InstallFrom>Web</InstallFrom>\r
1434@@ -27,12 +31,9 @@
1435 <MapFileExtensions>true</MapFileExtensions>\r
1436 <ApplicationRevision>0</ApplicationRevision>\r
1437 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
1438- <IsWebBootstrapper>true</IsWebBootstrapper>\r
1439 <UseApplicationTrust>false</UseApplicationTrust>\r
1440 <BootstrapperEnabled>true</BootstrapperEnabled>\r
1441- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
1442- <SignAssembly>false</SignAssembly>\r
1443- <AssemblyOriginatorKeyFile>gendarme.snk</AssemblyOriginatorKeyFile>\r
1444+ <TargetFrameworkProfile />\r
1445 </PropertyGroup>\r
1446 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
1447 <DebugSymbols>true</DebugSymbols>\r
1448@@ -42,6 +43,7 @@
1449 <DefineConstants>TRACE;DEBUG</DefineConstants>\r
1450 <ErrorReport>prompt</ErrorReport>\r
1451 <WarningLevel>4</WarningLevel>\r
1452+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
1453 </PropertyGroup>\r
1454 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
1455 <DebugType>pdbonly</DebugType>\r
1456@@ -50,6 +52,7 @@
1457 <DefineConstants>TRACE;RELEASE</DefineConstants>\r
1458 <ErrorReport>prompt</ErrorReport>\r
1459 <WarningLevel>4</WarningLevel>\r
1460+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
1461 </PropertyGroup>\r
1462 <ItemGroup>\r
1463 <Reference Include="System" />\r
1464@@ -88,6 +91,10 @@
1465 <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>\r
1466 <Name>Gendarme.Framework</Name>\r
1467 </ProjectReference>\r
1468+ <ProjectReference Include="..\..\..\cecil\symbols\mdb\Mono.Cecil.Mdb.csproj">\r
1469+ <Project>{8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}</Project>\r
1470+ <Name>Mono.Cecil.Mdb</Name>\r
1471+ </ProjectReference>\r
1472 </ItemGroup>\r
1473 <ItemGroup>\r
1474 <None Include="ChangeLog" />\r
1475@@ -95,30 +102,53 @@
1476 <EmbeddedResource Include="gendarme.xsl" />\r
1477 </ItemGroup>\r
1478 <ItemGroup>\r
1479+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
1480+ <Visible>False</Visible>\r
1481+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
1482+ <Install>false</Install>\r
1483+ </BootstrapperPackage>\r
1484 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
1485 <Visible>False</Visible>\r
1486+ <ProductName>\r
1487+ </ProductName>\r
1488+ <Install>false</Install>\r
1489 </BootstrapperPackage>\r
1490 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
1491 <Visible>False</Visible>\r
1492+ <ProductName>\r
1493+ </ProductName>\r
1494+ <Install>false</Install>\r
1495 </BootstrapperPackage>\r
1496 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
1497 <Visible>False</Visible>\r
1498+ <ProductName>\r
1499+ </ProductName>\r
1500+ <Install>false</Install>\r
1501+ </BootstrapperPackage>\r
1502+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
1503+ <Visible>False</Visible>\r
1504+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
1505+ <Install>false</Install>\r
1506 </BootstrapperPackage>\r
1507 </ItemGroup>\r
1508 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
1509 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
1510 Other similar extension points exist, see Microsoft.Common.targets.
1511- <Target Name="BeforeBuild">
1512- </Target>
1513- <Target Name="AfterBuild">
1514- </Target>
1515+ <Target Name="BeforeBuild">\r
1516+ </Target>\r
1517 -->\r
1518+ <Target Name="AfterBuild">\r
1519+ <Copy\r
1520+ SourceFiles="$(TargetDir)..\..\..\rules\rules.xml"\r
1521+ DestinationFolder="$(TargetDir)"\r
1522+ SkipUnchangedFiles="True"\r
1523+ />\r
1524+ </Target>\r
1525 <PropertyGroup>\r
1526 <PreBuildEvent>\r
1527 </PreBuildEvent>\r
1528- <PostBuildEvent>copy "$(TargetDir)..\..\..\rules\rules.xml" "$(TargetDir)"\r
1529-copy "$(TargetDir)..\..\..\..\..\cecil\bin\net_3_5_Release\Mono.Cecil.Pdb.*" "$(TargetDir)"\r
1530-copy "$(TargetDir)..\..\..\..\..\cecil\bin\net_3_5_Release\Mono.Cecil.Mdb.*" "$(TargetDir)"</PostBuildEvent>\r
1531+ <PostBuildEvent>\r
1532+ </PostBuildEvent>\r
1533 </PropertyGroup>\r
1534 <ProjectExtensions>\r
1535 <MonoDevelop>\r
1536diff --git a/gendarme/framework/Gendarme.Framework.Engines/SuppressMessageEngine.cs b/gendarme/framework/Gendarme.Framework.Engines/SuppressMessageEngine.cs
1537index a98a6bc..70ef7ba 100644
1538--- a/gendarme/framework/Gendarme.Framework.Engines/SuppressMessageEngine.cs
1539+++ b/gendarme/framework/Gendarme.Framework.Engines/SuppressMessageEngine.cs
1540@@ -71,7 +71,7 @@ namespace Gendarme.Framework.Engines {
1541 {
1542 // we only need to check the custom attributes if [SuppressMessage] is referenced (note: won't work for mscorlib)
1543 AssemblyDefinition assembly = (sender as AssemblyDefinition);
1544- if (assembly.MainModule.HasTypeReference (SuppressMessage)) {
1545+ if (assembly.MainModule.AnyTypeReference ((TypeReference tr) => { return tr.IsNamed ("System.Diagnostics.CodeAnalysis", "SuppressMessageAttribute"); })) {
1546 Controller.BuildingCustomAttributes += new EventHandler<EngineEventArgs> (OnCustomAttributes);
1547 } else {
1548 Controller.BuildingCustomAttributes -= new EventHandler<EngineEventArgs> (OnCustomAttributes);
1549@@ -103,7 +103,7 @@ namespace Gendarme.Framework.Engines {
1550 foreach (CustomAttribute ca in cap.CustomAttributes) {
1551 if (!ca.HasConstructorArguments)
1552 continue;
1553- if (ca.AttributeType.FullName != SuppressMessage)
1554+ if (!ca.AttributeType.IsNamed ("System.Diagnostics.CodeAnalysis", "SuppressMessageAttribute"))
1555 continue;
1556
1557 var arguments = ca.ConstructorArguments;
1558@@ -200,7 +200,7 @@ namespace Gendarme.Framework.Engines {
1559 foreach (ModuleDefinition module in assembly.Modules) {
1560 // TODO ...
1561 foreach (TypeDefinition type in module.GetAllTypes ()) {
1562- if (targets.TryGetValue (type.FullName, out rules))
1563+ if (targets.TryGetValue (type.GetFullName (), out rules))
1564 Add (type, rules);
1565
1566 if (type.HasMethods) {
1567@@ -213,11 +213,11 @@ namespace Gendarme.Framework.Engines {
1568 targets.Clear ();
1569 }
1570
1571- private void ResolveMethod (IMetadataTokenProvider method)
1572+ private void ResolveMethod (MemberReference method)
1573 {
1574 HashSet<string> rules;
1575
1576- string m = method.ToString ();
1577+ string m = method.GetFullName ();
1578 m = m.Substring (m.IndexOf (' ') + 1);
1579
1580 if (targets.TryGetValue (m, out rules))
1581diff --git a/gendarme/framework/Gendarme.Framework.Helpers/Log.cs b/gendarme/framework/Gendarme.Framework.Helpers/Log.cs
1582index 262c7e9..759ba9f 100644
1583--- a/gendarme/framework/Gendarme.Framework.Helpers/Log.cs
1584+++ b/gendarme/framework/Gendarme.Framework.Helpers/Log.cs
1585@@ -30,6 +30,7 @@ using System.Diagnostics;
1586 using System.Collections.Generic;
1587
1588 using Mono.Cecil;
1589+using Gendarme.Framework.Rocks;
1590
1591 namespace Gendarme.Framework.Helpers {
1592
1593@@ -83,9 +84,9 @@ namespace Gendarme.Framework.Helpers {
1594 }
1595
1596 [Conditional ("DEBUG")]
1597- public static void WriteLine<T> (T category, MethodDefinition method)
1598+ public static void WriteLine<T> (T category, MemberReference member)
1599 {
1600- WriteLine (typeof (T).Name, method);
1601+ WriteLine (typeof (T).Name, member);
1602 }
1603
1604 // WriteLine (string)
1605@@ -104,10 +105,15 @@ namespace Gendarme.Framework.Helpers {
1606 }
1607
1608 [Conditional ("DEBUG")]
1609- public static void WriteLine (string category, MethodDefinition method)
1610+ public static void WriteLine (string category, MemberReference member)
1611 {
1612- if (IsEnabled (category))
1613- Debug.WriteLine (new MethodPrinter (method).ToString ());
1614+ if (IsEnabled (category)) {
1615+ MethodDefinition md = (member as MethodDefinition);
1616+ if (md != null)
1617+ Debug.WriteLine (new MethodPrinter (md).ToString ());
1618+ else
1619+ Debug.WriteLine (member.GetFullName ());
1620+ }
1621 }
1622
1623 // Misc
1624diff --git a/gendarme/framework/Gendarme.Framework.Helpers/MethodPrinter.cs b/gendarme/framework/Gendarme.Framework.Helpers/MethodPrinter.cs
1625index af3638c..ef40dcc 100644
1626--- a/gendarme/framework/Gendarme.Framework.Helpers/MethodPrinter.cs
1627+++ b/gendarme/framework/Gendarme.Framework.Helpers/MethodPrinter.cs
1628@@ -15,6 +15,7 @@ using System;
1629 using System.Collections;
1630 using System.Collections.Generic;
1631 using System.Diagnostics;
1632+using System.Globalization;
1633 using System.Text;
1634 using Mono.Cecil;
1635 using Mono.Cecil.Cil;
1636@@ -60,17 +61,28 @@ namespace Gendarme.Framework.Helpers {
1637 buffer.Append ("* ");
1638 else
1639 buffer.Append (" ");
1640- buffer.AppendFormat (" {0}: {1}", instr.Offset.ToString ("X4"),
1641- instr.OpCode.Name);
1642+
1643+ buffer.Append (" ");
1644+ buffer.Append (instr.Offset.ToString ("X4", CultureInfo.InvariantCulture));
1645+ buffer.Append (": ");
1646+ buffer.Append (instr.OpCode.Name);
1647+
1648 int[] targets = BranchTargets (instr);
1649- if (targets != null)
1650- foreach (int target in targets)
1651- buffer.AppendFormat (" {0}", target.ToString ("X4"));
1652- else if (instr.Operand is string)
1653- buffer.AppendFormat (" \"{0}\"", instr.Operand.ToString ());
1654- else if (instr.Operand != null)
1655- buffer.AppendFormat (" {0}", instr.Operand.ToString ());
1656- buffer.AppendLine (string.Empty);
1657+ if (targets != null) {
1658+ foreach (int target in targets) {
1659+ buffer.Append (' ');
1660+ buffer.Append (target.ToString ("X4", CultureInfo.InvariantCulture));
1661+ }
1662+ } else if (instr.Operand is string) {
1663+ buffer.Append (" \"");
1664+ buffer.Append (instr.Operand);
1665+ buffer.Append ('"');
1666+ } else if (instr.Operand != null) {
1667+ buffer.Append (" ");
1668+ buffer.Append (instr.Operand);
1669+ }
1670+ buffer.AppendLine ();
1671+
1672 prevInstr = instr;
1673 if (EndsTryRegion (instr) != null)
1674 buffer.AppendLine ("} (Try)");
1675diff --git a/gendarme/framework/Gendarme.Framework.Helpers/MethodSignature.cs b/gendarme/framework/Gendarme.Framework.Helpers/MethodSignature.cs
1676index e6fd265..a17ae07 100644
1677--- a/gendarme/framework/Gendarme.Framework.Helpers/MethodSignature.cs
1678+++ b/gendarme/framework/Gendarme.Framework.Helpers/MethodSignature.cs
1679@@ -34,6 +34,7 @@ using System.Collections.Generic;
1680 using System.Text;
1681
1682 using Mono.Cecil;
1683+using Gendarme.Framework.Rocks;
1684
1685 namespace Gendarme.Framework.Helpers {
1686
1687@@ -49,7 +50,7 @@ namespace Gendarme.Framework.Helpers {
1688 /// }
1689 /// </code>
1690 /// </example>
1691- // <seealso cref="Gendarme.Framework.Helpers.MethodSignatures"/>
1692+ /// <seealso cref="Gendarme.Framework.Helpers.MethodSignatures"/>
1693 public class MethodSignature {
1694
1695 /// <summary>
1696@@ -121,7 +122,7 @@ namespace Gendarme.Framework.Helpers {
1697 if (Name != null && method.Name != Name)
1698 return false;
1699
1700- if (ReturnType != null && method.ReturnType.FullName != ReturnType)
1701+ if (ReturnType != null && !method.ReturnType.IsNamed (ReturnType))
1702 return false;
1703
1704 if (Parameters != null) {
1705@@ -132,7 +133,7 @@ namespace Gendarme.Framework.Helpers {
1706 for (int i = 0; i < Parameters.Count; i++) {
1707 if (Parameters [i] == null)
1708 continue;//ignore parameter
1709- if (Parameters [i] != pdc [i].ParameterType.FullName) {
1710+ if (!pdc [i].ParameterType.IsNamed (Parameters [i])) {
1711 return false;
1712 }
1713 }
1714diff --git a/gendarme/framework/Gendarme.Framework.Helpers/MethodSignatures.cs b/gendarme/framework/Gendarme.Framework.Helpers/MethodSignatures.cs
1715index 3b8b4ad..27116fa 100644
1716--- a/gendarme/framework/Gendarme.Framework.Helpers/MethodSignatures.cs
1717+++ b/gendarme/framework/Gendarme.Framework.Helpers/MethodSignatures.cs
1718@@ -32,6 +32,7 @@ using System;
1719 using System.Collections.Generic;
1720
1721 using Mono.Cecil;
1722+using Gendarme.Framework.Rocks;
1723
1724 namespace Gendarme.Framework.Helpers {
1725
1726@@ -120,19 +121,23 @@ namespace Gendarme.Framework.Helpers {
1727 // TryParse
1728 public static readonly MethodSignature TryParse = new MethodSignature ("TryParse",
1729 delegate (MethodReference method) {
1730- if (method.ReturnType.FullName != "System.Boolean")
1731+ if (!method.ReturnType.IsNamed ("System", "Boolean"))
1732 return false;
1733
1734 IList<ParameterDefinition> pdc = method.Parameters;
1735- if (pdc [0].ParameterType.FullName != "System.String")
1736+ if (!pdc [0].ParameterType.IsNamed ("System", "String"))
1737 return false;
1738
1739 TypeReference last = pdc [pdc.Count - 1].ParameterType;
1740 if (!last.IsByReference)
1741 return false;
1742
1743- string pt_name = last.FullName;
1744- return (String.Compare (pt_name, 0, method.DeclaringType.FullName, 0, pt_name.Length - 1) == 0);
1745+ TypeReference mtype = method.DeclaringType;
1746+ if (last.Namespace != mtype.Namespace)
1747+ return false;
1748+
1749+ string pt_name = last.Name;
1750+ return (String.Compare (pt_name, 0, mtype.Name, 0, pt_name.Length - 1, StringComparison.Ordinal) == 0);
1751 }
1752 );
1753
1754@@ -141,9 +146,9 @@ namespace Gendarme.Framework.Helpers {
1755 delegate (MethodReference method) {
1756 if (!method.HasParameters)
1757 return false;
1758- if (method.ReturnType.FullName != method.DeclaringType.FullName)
1759+ if (!method.ReturnType.IsNamed (method.DeclaringType.Namespace, method.DeclaringType.Name))
1760 return false;
1761- return (method.Parameters [0].ParameterType.FullName == "System.String");
1762+ return method.Parameters [0].ParameterType.IsNamed ("System", "String");
1763 }
1764 );
1765 }
1766diff --git a/gendarme/framework/Gendarme.Framework.Helpers/OpCodeBitmask.cs b/gendarme/framework/Gendarme.Framework.Helpers/OpCodeBitmask.cs
1767index f7ceeac..6058fbe 100644
1768--- a/gendarme/framework/Gendarme.Framework.Helpers/OpCodeBitmask.cs
1769+++ b/gendarme/framework/Gendarme.Framework.Helpers/OpCodeBitmask.cs
1770@@ -26,6 +26,7 @@
1771 //
1772
1773 using System;
1774+using System.Globalization;
1775 using System.Text;
1776
1777 using Mono.Cecil.Cil;
1778@@ -144,12 +145,12 @@ namespace Gendarme.Framework.Helpers {
1779 return Equals (obj as OpCodeBitmask);
1780 }
1781
1782- public bool Equals (OpCodeBitmask set)
1783+ public bool Equals (OpCodeBitmask other)
1784 {
1785- if (set == null)
1786+ if (other == null)
1787 return false;
1788- return ((mask [0] == set.mask [0]) || (mask [1] == set.mask [1]) ||
1789- (mask [2] == set.mask [2]) || (mask [3] == set.mask [3]));
1790+ return ((mask [0] == other.mask [0]) || (mask [1] == other.mask [1]) ||
1791+ (mask [2] == other.mask [2]) || (mask [3] == other.mask [3]));
1792 }
1793
1794 public override int GetHashCode ()
1795@@ -159,7 +160,8 @@ namespace Gendarme.Framework.Helpers {
1796
1797 public override string ToString ()
1798 {
1799- return String.Format ("0x{0:X}:0x{1:X}:0x{2:X}:0x{3:X}", mask [0], mask [1], mask [2], mask [3]);
1800+ return String.Format (CultureInfo.InvariantCulture, "0x{0:X}:0x{1:X}:0x{2:X}:0x{3:X}",
1801+ mask [0], mask [1], mask [2], mask [3]);
1802 }
1803
1804
1805diff --git a/gendarme/framework/Gendarme.Framework.Helpers/StackEntryAnalysis.cs b/gendarme/framework/Gendarme.Framework.Helpers/StackEntryAnalysis.cs
1806index 61d5f9b..156aef1 100644
1807--- a/gendarme/framework/Gendarme.Framework.Helpers/StackEntryAnalysis.cs
1808+++ b/gendarme/framework/Gendarme.Framework.Helpers/StackEntryAnalysis.cs
1809@@ -97,9 +97,9 @@ namespace Gendarme.Framework.Helpers {
1810 return this == other;
1811 }
1812
1813- public bool Equals (StoreSlot storeSlot)
1814+ public bool Equals (StoreSlot other)
1815 {
1816- return this == storeSlot;
1817+ return this == other;
1818 }
1819
1820 public override int GetHashCode ()
1821@@ -182,40 +182,14 @@ namespace Gendarme.Framework.Helpers {
1822 return false;
1823 }
1824
1825- public bool Equals (InstructionWithLeave iwl)
1826+ public bool Equals (InstructionWithLeave other)
1827 {
1828- if (Instruction != iwl.Instruction)
1829- return false;
1830-
1831- if (LeaveStack == null)
1832- return (iwl.LeaveStack == null);
1833-
1834- if (iwl.LeaveStack == null)
1835- return false;
1836-
1837- if (LeaveStack.Length != iwl.LeaveStack.Length)
1838- return false;
1839-
1840- for (int i = 0; i < LeaveStack.Length; i++) {
1841- if (LeaveStack [i] != iwl.LeaveStack [i])
1842- return false;
1843- }
1844- return true;
1845+ return (Instruction == other.Instruction);
1846 }
1847
1848 public override int GetHashCode ()
1849 {
1850- int hc = 0;
1851-
1852- unchecked {
1853- hc ^= Instruction.GetHashCode ();
1854- if (LeaveStack != null) {
1855- foreach (Instruction ins in LeaveStack)
1856- hc ^= ins.GetHashCode ();
1857- }
1858- }
1859-
1860- return hc;
1861+ return Instruction.GetHashCode ();
1862 }
1863
1864 public static bool operator == (InstructionWithLeave left, InstructionWithLeave right)
1865@@ -527,7 +501,7 @@ namespace Gendarme.Framework.Helpers {
1866 return new StoreSlot (StoreType.Argument, ins.OpCode.Code - Code.Ldarg_0);
1867 case Code.Ldarg_S:
1868 case Code.Ldarg: {
1869- int sequence = ((ParameterDefinition) ins.Operand).GetSequence ();
1870+ int sequence = ((ParameterDefinition) ins.Operand).Index + 1;
1871 if (!this.Method.HasThis)
1872 sequence--;
1873 return new StoreSlot (StoreType.Argument, sequence);
1874@@ -581,7 +555,7 @@ namespace Gendarme.Framework.Helpers {
1875
1876 case Code.Starg_S: //store arg (not ref / out etc)
1877 case Code.Starg: {
1878- int sequence = ((ParameterDefinition) ins.Operand).GetSequence ();
1879+ int sequence = ((ParameterDefinition) ins.Operand).Index + 1;
1880 if (!this.Method.HasThis)
1881 sequence--;
1882 return new StoreSlot (StoreType.Argument, sequence);
1883diff --git a/gendarme/framework/Gendarme.Framework.Helpers/StackEntryUsageResult.cs b/gendarme/framework/Gendarme.Framework.Helpers/StackEntryUsageResult.cs
1884index 1fa302f..9c69872 100644
1885--- a/gendarme/framework/Gendarme.Framework.Helpers/StackEntryUsageResult.cs
1886+++ b/gendarme/framework/Gendarme.Framework.Helpers/StackEntryUsageResult.cs
1887@@ -61,9 +61,9 @@ namespace Gendarme.Framework.Helpers {
1888 return false;
1889 }
1890
1891- public bool Equals (StackEntryUsageResult usageResult)
1892+ public bool Equals (StackEntryUsageResult other)
1893 {
1894- return (Instruction == usageResult.Instruction) && (StackOffset == usageResult.StackOffset);
1895+ return (Instruction == other.Instruction) && (StackOffset == other.StackOffset);
1896 }
1897
1898 public override int GetHashCode ()
1899diff --git a/gendarme/framework/Gendarme.Framework.Helpers/StreamLineReader.cs b/gendarme/framework/Gendarme.Framework.Helpers/StreamLineReader.cs
1900new file mode 100644
1901index 0000000..3242474
1902--- /dev/null
1903+++ b/gendarme/framework/Gendarme.Framework.Helpers/StreamLineReader.cs
1904@@ -0,0 +1,122 @@
1905+//
1906+// StreamLineReader - A StringReader-like class that avoid creating string
1907+//
1908+// Authors:
1909+// Sebastien Pouliot <sebastien@ximian.com>
1910+//
1911+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
1912+//
1913+// Permission is hereby granted, free of charge, to any person obtaining
1914+// a copy of this software and associated documentation files (the
1915+// "Software"), to deal in the Software without restriction, including
1916+// without limitation the rights to use, copy, modify, merge, publish,
1917+// distribute, sublicense, and/or sell copies of the Software, and to
1918+// permit persons to whom the Software is furnished to do so, subject to
1919+// the following conditions:
1920+//
1921+// The above copyright notice and this permission notice shall be
1922+// included in all copies or substantial portions of the Software.
1923+//
1924+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1925+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1926+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1927+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
1928+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
1929+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
1930+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1931+//
1932+
1933+using System;
1934+using System.IO;
1935+
1936+namespace Gendarme.Framework.Helpers {
1937+
1938+ // note: inheriting from StreamReader was not possible since we cannot
1939+ // override EndOfStream and ensure integrity with other Read ops
1940+ public class StreamLineReader : IDisposable {
1941+
1942+ StreamReader sr;
1943+ char [] buff;
1944+ int n;
1945+ int max;
1946+
1947+ public StreamLineReader (string fileName)
1948+ {
1949+ sr = new StreamReader (fileName);
1950+ Initialize ();
1951+ }
1952+
1953+ public StreamLineReader (Stream stream)
1954+ {
1955+ sr = new StreamReader (stream);
1956+ Initialize ();
1957+ }
1958+
1959+ void Initialize ()
1960+ {
1961+ buff = new char [4096];
1962+ max = n = buff.Length;
1963+ }
1964+
1965+ public bool EndOfStream {
1966+ get { return (n == max || max == 0) && sr.EndOfStream; }
1967+ }
1968+
1969+ public int ReadLine (char [] buffer, int index, int count)
1970+ {
1971+ if (Disposed)
1972+ throw new ObjectDisposedException ("StreamLineReader");
1973+ if (buffer == null)
1974+ throw new ArgumentNullException ("buffer");
1975+ if (index < 0)
1976+ throw new ArgumentOutOfRangeException ("index", "< 0");
1977+ if (count < 0)
1978+ throw new ArgumentOutOfRangeException ("count", "< 0");
1979+ // ordered to avoid possible integer overflow
1980+ if (index > buffer.Length - count)
1981+ throw new ArgumentException ("index + count > buffer.Length");
1982+
1983+ int len = 0;
1984+ while (len < count) {
1985+ if (n == max) {
1986+ max = sr.ReadBlock (buff, 0, buff.Length);
1987+ if (max == 0) break;
1988+ n = 0;
1989+ }
1990+ char c = buff [n++];
1991+ switch (c) {
1992+ case '\r':
1993+ continue;
1994+ case '\n':
1995+ Array.Clear (buffer, len, buffer.Length - len);
1996+ return len;
1997+ default:
1998+ buffer [index++] = c;
1999+ len++;
2000+ break;
2001+ }
2002+ }
2003+ return len;
2004+ }
2005+
2006+ public void Dispose ()
2007+ {
2008+ Dispose (true);
2009+ GC.SuppressFinalize (this);
2010+ }
2011+
2012+ protected virtual void Dispose (bool disposing)
2013+ {
2014+ try {
2015+ if (!Disposed)
2016+ sr.Dispose ();
2017+ }
2018+ finally {
2019+ Disposed = true;
2020+ }
2021+ }
2022+
2023+ protected bool Disposed { get; private set; }
2024+ }
2025+}
2026+
2027diff --git a/gendarme/framework/Gendarme.Framework.Rocks/CecilRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/CecilRocks.cs
2028index a1b2cfc..12c6345 100644
2029--- a/gendarme/framework/Gendarme.Framework.Rocks/CecilRocks.cs
2030+++ b/gendarme/framework/Gendarme.Framework.Rocks/CecilRocks.cs
2031@@ -27,6 +27,7 @@
2032 //
2033
2034 using System;
2035+using System.Collections.Generic;
2036
2037 using Mono.Cecil;
2038 using Mono.Cecil.Metadata;
2039@@ -157,5 +158,30 @@ namespace Gendarme.Framework.Rocks {
2040 // compare assemblies tokens (but do not recurse)
2041 return other == null ? false : self_assembly.MetadataToken.Equals (other_assembly.MetadataToken);
2042 }
2043+
2044+ static Dictionary<MemberReference, string> full_name_cache = new Dictionary<MemberReference, string> ();
2045+
2046+ /// <summary>
2047+ /// Get the string value of the MemberReference FullName property without the cost
2048+ /// of allocating a new string for each (or most) calls.
2049+ /// </summary>
2050+ /// <param name="self">The MemberReference instance where the method is applied.</param>
2051+ /// <returns>The cached FullName property of the MemberReference</returns>
2052+ /// <remarks>Cecil needs to rebuild most of the FullName properties on each call in order to
2053+ /// be able to write assemblies. However this is a waste of memory when an application, like
2054+ /// Gendarme, use it for read-only purposes.</remarks>
2055+ public static string GetFullName (this MemberReference self)
2056+ {
2057+ if (self == null)
2058+ return String.Empty;
2059+
2060+ string full_name;
2061+ if (!full_name_cache.TryGetValue (self, out full_name)) {
2062+ full_name = self.FullName;
2063+ full_name_cache.Add (self, full_name);
2064+ }
2065+
2066+ return full_name;
2067+ }
2068 }
2069 }
2070diff --git a/gendarme/framework/Gendarme.Framework.Rocks/CustomAttributeRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/CustomAttributeRocks.cs
2071index 26b6401..ebfb1ba 100644
2072--- a/gendarme/framework/Gendarme.Framework.Rocks/CustomAttributeRocks.cs
2073+++ b/gendarme/framework/Gendarme.Framework.Rocks/CustomAttributeRocks.cs
2074@@ -44,51 +44,16 @@ namespace Gendarme.Framework.Rocks {
2075 /// </summary>
2076 public static class CustomAttributeRocks {
2077
2078- internal static string [] GeneratedCodeAttributes = {
2079- "System.CodeDom.Compiler.GeneratedCodeAttribute",
2080- "System.Runtime.CompilerServices.CompilerGeneratedAttribute"
2081- };
2082-
2083- /// <summary>
2084- /// Check if the custom attribute collection contains an attribute of a specified type.
2085- /// </summary>
2086- /// <param name="self">The CustomAttribute enumerable on which the extension method can be called.</param>
2087- /// <param name="attributeTypeName">Full type name of the attribute class.</param>
2088- /// <returns>True if the collection contains an attribute of the same name,
2089- /// False otherwise.</returns>
2090- public static bool ContainsType (this IEnumerable<CustomAttribute> self, string attributeTypeName)
2091+ internal static bool HasAnyGeneratedCodeAttribute (this ICustomAttributeProvider self)
2092 {
2093- if (attributeTypeName == null)
2094- throw new ArgumentNullException ("attributeTypeName");
2095- if (self == null)
2096+ if ((self == null) || !self.HasCustomAttributes)
2097 return false;
2098
2099- foreach (CustomAttribute ca in self) {
2100- if (ca.AttributeType.FullName == attributeTypeName)
2101+ foreach (CustomAttribute ca in self.CustomAttributes) {
2102+ TypeReference cat = ca.AttributeType;
2103+ if (cat.IsNamed ("System.CodeDom.Compiler", "GeneratedCodeAttribute") ||
2104+ cat.IsNamed ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute")) {
2105 return true;
2106- }
2107- return false;
2108- }
2109-
2110- /// <summary>
2111- /// Check if the custom attribute collection contains any of the specified type.
2112- /// </summary>
2113- /// <param name="self">The CustomAttribute enumerable on which the extension method can be called.</param>
2114- /// <param name="attributeTypeNames">A strings array of full type names of the attributes.</param>
2115- /// <returns>True if the collection contains any attribute matching one specified,
2116- /// False otherwise.</returns>
2117- public static bool ContainsAnyType (this IEnumerable<CustomAttribute> self, string[] attributeTypeNames)
2118- {
2119- if (attributeTypeNames == null)
2120- throw new ArgumentNullException ("attributeTypeNames");
2121- if (self == null)
2122- return false;
2123-
2124- foreach (CustomAttribute ca in self) {
2125- string fullname = ca.AttributeType.FullName;
2126- foreach (string attribute_full_name in attributeTypeNames) {
2127- if (fullname == attribute_full_name)
2128- return true;
2129 }
2130 }
2131 return false;
2132@@ -99,17 +64,25 @@ namespace Gendarme.Framework.Rocks {
2133 /// </summary>
2134 /// <param name="self">The ICustomAttributeProvider (e.g. AssemblyDefinition, TypeReference, MethodReference,
2135 /// FieldReference...) on which the extension method can be called.</param>
2136- /// <param name="attributeName">Full name of the attribute class</param>
2137+ /// <param name="nameSpace">The namespace of the attribute to be matched</param>
2138+ /// <param name="name">The name of the attribute to be matched</param>
2139 /// <returns>True if the provider contains an attribute of the same name,
2140 /// False otherwise.</returns>
2141- public static bool HasAttribute (this ICustomAttributeProvider self, string attributeName)
2142+ public static bool HasAttribute (this ICustomAttributeProvider self, string nameSpace, string name)
2143 {
2144- if (attributeName == null)
2145- throw new ArgumentNullException ("attributeName");
2146+ if (nameSpace == null)
2147+ throw new ArgumentNullException ("nameSpace");
2148+ if (name == null)
2149+ throw new ArgumentNullException ("name");
2150
2151 if ((self == null) || !self.HasCustomAttributes)
2152 return false;
2153- return self.CustomAttributes.ContainsType (attributeName);
2154+
2155+ foreach (CustomAttribute ca in self.CustomAttributes) {
2156+ if (ca.AttributeType.IsNamed (nameSpace, name))
2157+ return true;
2158+ }
2159+ return false;
2160 }
2161 }
2162 }
2163diff --git a/gendarme/framework/Gendarme.Framework.Rocks/FieldRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/FieldRocks.cs
2164index 39641f5..bf3b30b 100644
2165--- a/gendarme/framework/Gendarme.Framework.Rocks/FieldRocks.cs
2166+++ b/gendarme/framework/Gendarme.Framework.Rocks/FieldRocks.cs
2167@@ -49,10 +49,9 @@ namespace Gendarme.Framework.Rocks {
2168 if (field == null)
2169 return false;
2170
2171- if (field.HasCustomAttributes) {
2172- if (field.CustomAttributes.ContainsAnyType (CustomAttributeRocks.GeneratedCodeAttributes))
2173- return true;
2174- }
2175+ if (field.HasAnyGeneratedCodeAttribute ())
2176+ return true;
2177+
2178 return field.DeclaringType.IsGeneratedCode ();
2179 }
2180
2181diff --git a/gendarme/framework/Gendarme.Framework.Rocks/InstructionRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/InstructionRocks.cs
2182index 6c8aaf6..aef546a 100644
2183--- a/gendarme/framework/Gendarme.Framework.Rocks/InstructionRocks.cs
2184+++ b/gendarme/framework/Gendarme.Framework.Rocks/InstructionRocks.cs
2185@@ -27,6 +27,7 @@
2186 // THE SOFTWARE.
2187
2188 using System;
2189+using System.Globalization;
2190
2191 using Mono.Cecil;
2192 using Mono.Cecil.Cil;
2193@@ -291,7 +292,7 @@ namespace Gendarme.Framework.Rocks {
2194 case StackBehaviour.Varpop:
2195 switch (self.OpCode.FlowControl) {
2196 case FlowControl.Return:
2197- return method.ReturnType.FullName == "System.Void" ? 0 : 1;
2198+ return method.ReturnType.IsNamed ("System", "Void") ? 0 : 1;
2199
2200 case FlowControl.Call:
2201 IMethodSignature calledMethod = (IMethodSignature) self.Operand;
2202@@ -310,7 +311,8 @@ namespace Gendarme.Framework.Rocks {
2203 case StackBehaviour.PopAll:
2204 return -1;
2205 default:
2206- string unknown = String.Format ("'{0}' is not a valid value for instruction '{1}'.",
2207+ string unknown = String.Format (CultureInfo.InvariantCulture,
2208+ "'{0}' is not a valid value for instruction '{1}'.",
2209 self.OpCode.StackBehaviourPush, self.OpCode);
2210 throw new InvalidOperationException (unknown);
2211 }
2212@@ -344,11 +346,12 @@ namespace Gendarme.Framework.Rocks {
2213 case StackBehaviour.Varpush:
2214 IMethodSignature calledMethod = (IMethodSignature) self.Operand;
2215 if (calledMethod != null)
2216- return (calledMethod.ReturnType.FullName == "System.Void") ? 0 : 1;
2217+ return calledMethod.ReturnType.IsNamed ("System", "Void") ? 0 : 1;
2218
2219 throw new NotImplementedException ("Varpush not supported for this Instruction.");
2220 default:
2221- string unknown = String.Format ("'{0}' is not a valid value for instruction '{1}'.",
2222+ string unknown = String.Format (CultureInfo.InvariantCulture,
2223+ "'{0}' is not a valid value for instruction '{1}'.",
2224 self.OpCode.StackBehaviourPush, self.OpCode);
2225 throw new InvalidOperationException (unknown);
2226 }
2227diff --git a/gendarme/framework/Gendarme.Framework.Rocks/MethodRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/MethodRocks.cs
2228index f4a604c..eace40a 100644
2229--- a/gendarme/framework/Gendarme.Framework.Rocks/MethodRocks.cs
2230+++ b/gendarme/framework/Gendarme.Framework.Rocks/MethodRocks.cs
2231@@ -55,6 +55,15 @@ namespace Gendarme.Framework.Rocks {
2232 /// </summary>
2233 public static class MethodRocks {
2234
2235+ public static bool IsNamed (this MemberReference self, string nameSpace, string typeName, string methodName)
2236+ {
2237+ if (methodName == null)
2238+ throw new ArgumentNullException ("methodName");
2239+ if (self == null)
2240+ return false;
2241+ return ((self.Name == methodName) && self.DeclaringType.IsNamed (nameSpace, typeName));
2242+ }
2243+
2244 /// <summary>
2245 /// Check if the MethodReference is defined as the entry point of it's assembly.
2246 /// </summary>
2247@@ -76,7 +85,7 @@ namespace Gendarme.Framework.Rocks {
2248 return false;
2249
2250 return (self.HasThis && !self.HasParameters && (self.Name == "Finalize") &&
2251- (self.ReturnType.FullName == "System.Void"));
2252+ self.ReturnType.IsNamed ("System", "Void"));
2253 }
2254
2255 /// <summary>
2256@@ -91,10 +100,9 @@ namespace Gendarme.Framework.Rocks {
2257 return false;
2258
2259 MethodDefinition method = self.Resolve ();
2260- if ((method != null) && method.HasCustomAttributes) {
2261- if (method.CustomAttributes.ContainsAnyType (CustomAttributeRocks.GeneratedCodeAttributes))
2262- return true;
2263- }
2264+ if (method.HasAnyGeneratedCodeAttribute ())
2265+ return true;
2266+
2267 return self.DeclaringType.IsGeneratedCode ();
2268 }
2269
2270@@ -161,27 +169,10 @@ namespace Gendarme.Framework.Rocks {
2271 TypeDefinition parent = declaring.BaseType != null ? declaring.BaseType.Resolve () : null;
2272 while (parent != null) {
2273 string name = method.Name;
2274- string retval = method.ReturnType.FullName;
2275- int pcount = method.HasParameters ? method.Parameters.Count : 0;
2276 foreach (MethodDefinition md in parent.Methods) {
2277 if (name != md.Name)
2278 continue;
2279- if (retval != md.ReturnType.FullName)
2280- continue;
2281- if (md.HasParameters && (pcount == 0))
2282- continue;
2283- IList<ParameterDefinition> ppdc = md.Parameters;
2284- if (pcount != ppdc.Count)
2285- continue;
2286-
2287- bool ok = true;
2288- for (int i = 0; i < pcount; i++) {
2289- if (method.Parameters [i].ParameterType.FullName != ppdc [i].ParameterType.FullName) {
2290- ok = false;
2291- break;
2292- }
2293- }
2294- if (!ok)
2295+ if (!method.CompareSignature (md))
2296 continue;
2297
2298 return md.IsVirtual;
2299@@ -246,11 +237,11 @@ namespace Gendarme.Framework.Rocks {
2300 TypeReference type = parameters [1].ParameterType;
2301 GenericParameter gp = (type as GenericParameter);
2302 if (gp == null)
2303- return type.Inherits ("System.EventArgs");
2304+ return type.Inherits ("System", "EventArgs");
2305
2306 if (gp.HasConstraints) {
2307 IList<TypeReference> cc = gp.Constraints;
2308- return ((cc.Count == 1) && (cc [0].FullName == "System.EventArgs"));
2309+ return ((cc.Count == 1) && cc [0].IsNamed ("System", "EventArgs"));
2310 }
2311
2312 return false;
2313@@ -283,7 +274,7 @@ namespace Gendarme.Framework.Rocks {
2314
2315 private static bool AreSameElementTypes (TypeReference a, TypeReference b)
2316 {
2317- return a.GetElementType ().FullName == b.GetElementType ().FullName;
2318+ return a.IsGenericParameter || b.IsGenericParameter || b.IsNamed (a.Namespace, a.Name);
2319 }
2320
2321 /// <summary>
2322diff --git a/gendarme/framework/Gendarme.Framework.Rocks/ModuleRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/ModuleRocks.cs
2323index 06a946c..3aad117 100644
2324--- a/gendarme/framework/Gendarme.Framework.Rocks/ModuleRocks.cs
2325+++ b/gendarme/framework/Gendarme.Framework.Rocks/ModuleRocks.cs
2326@@ -4,7 +4,7 @@
2327 // Authors:
2328 // Sebastien Pouliot <sebastien@ximian.com>
2329 //
2330-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
2331+// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
2332 //
2333 // Permission is hereby granted, free of charge, to any person obtaining a copy
2334 // of this software and associated documentation files (the "Software"), to deal
2335@@ -155,19 +155,58 @@ namespace Gendarme.Framework.Rocks {
2336 yield return type;
2337 }
2338
2339- public static bool HasAnyTypeReference (this ModuleDefinition self, string [] typeNames)
2340+ static Dictionary<ModuleDefinition, IEnumerable<MemberReference>> member_ref_cache = new Dictionary<ModuleDefinition, IEnumerable<MemberReference>> ();
2341+
2342+ /// <summary>
2343+ /// Check if any MemberReference, referenced by the current ModuleDefinition, satisfies the
2344+ /// specified predicate.
2345+ /// </summary>
2346+ /// <param name="self">The ModuleDefinition on which the extension method can be called.</param>
2347+ /// <param name="predicate">The condition to execute on a provided MemberReference</param>
2348+ /// <returns>True if 'predicate' returns true for any MemberReference in the module's referenced types.</returns>
2349+ /// <remarks>Cecil's GetMemberReferences method will allocate a new array each time it is called.
2350+ /// This extension method will cache the IEnumerable, on the first use, to reduce memory consumption.</remarks>
2351+ public static bool AnyMemberReference (this ModuleDefinition self, Func<MemberReference, bool> predicate)
2352 {
2353 if (self == null)
2354 return false;
2355
2356- if (typeNames == null)
2357- throw new ArgumentNullException ("typeNames");
2358+ // since ModuleDefinition.GetMemberReferences allocates an array (always identical if the
2359+ // assembly is opened "read-only", like Gendarme does) we'll cache and retrieve the array
2360+ IEnumerable<MemberReference> refs;
2361+ if (!member_ref_cache.TryGetValue (self, out refs)) {
2362+ refs = self.GetMemberReferences ();
2363+ member_ref_cache.Add (self, refs);
2364+ }
2365+
2366+ return refs.Any (predicate);
2367+ }
2368+
2369+ static Dictionary<ModuleDefinition, IEnumerable<TypeReference>> type_ref_cache = new Dictionary<ModuleDefinition, IEnumerable<TypeReference>> ();
2370
2371- foreach (var typeName in typeNames)
2372- if (self.HasTypeReference (typeName))
2373- return true;
2374+ /// <summary>
2375+ /// Check if any TypeReference, referenced by the current ModuleDefinition, satisfies the
2376+ /// specified predicate.
2377+ /// </summary>
2378+ /// <param name="self">The ModuleDefinition on which the extension method can be called.</param>
2379+ /// <param name="predicate">The condition to execute on a provided TypeReference</param>
2380+ /// <returns>True if 'predicate' returns true for any TypeReference in the module's referenced types.</returns>
2381+ /// <remarks>Cecil's GetTypeReferences method will allocate a new array each time it is called.
2382+ /// This extension method will cache the IEnumerable, on the first use, to reduce memory consumption.</remarks>
2383+ public static bool AnyTypeReference (this ModuleDefinition self, Func<TypeReference, bool> predicate)
2384+ {
2385+ if (self == null)
2386+ return false;
2387+
2388+ // since ModuleDefinition.GetTypeReferences allocates an array (always identical if the
2389+ // assembly is opened "read-only", like Gendarme does) we'll cache and retrieve the array
2390+ IEnumerable<TypeReference> refs;
2391+ if (!type_ref_cache.TryGetValue (self, out refs)) {
2392+ refs = self.GetTypeReferences ();
2393+ type_ref_cache.Add (self, refs);
2394+ }
2395
2396- return false;
2397+ return refs.Any (predicate);
2398 }
2399 }
2400 }
2401diff --git a/gendarme/framework/Gendarme.Framework.Rocks/ParameterRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/ParameterRocks.cs
2402index cfc87ca..7a41c01 100644
2403--- a/gendarme/framework/Gendarme.Framework.Rocks/ParameterRocks.cs
2404+++ b/gendarme/framework/Gendarme.Framework.Rocks/ParameterRocks.cs
2405@@ -39,22 +39,7 @@ namespace Gendarme.Framework.Rocks {
2406 /// <returns>True if the parameter represents a list of parameters, false otherwise.</returns>
2407 public static bool IsParams (this ParameterDefinition self)
2408 {
2409- if (self == null || !self.HasCustomAttributes)
2410- return false;
2411- return self.CustomAttributes.ContainsType ("System.ParamArrayAttribute");
2412- }
2413-
2414- /// <summary>
2415- /// Returns the sequence number as found in the metadata
2416- /// </summary>
2417- /// <param name="self">The ParameterDefinition on which the extension method can be called.</param>
2418- /// <returns>The integer value of the sequence number of the parameter.</returns>
2419- public static int GetSequence (this ParameterReference self)
2420- {
2421- if (self == null)
2422- return -1;
2423-
2424- return self.Index + 1;
2425+ return self.HasAttribute ("System", "ParamArrayAttribute");
2426 }
2427 }
2428 }
2429diff --git a/gendarme/framework/Gendarme.Framework.Rocks/PropertyRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/PropertyRocks.cs
2430index 293f9db..112d323 100644
2431--- a/gendarme/framework/Gendarme.Framework.Rocks/PropertyRocks.cs
2432+++ b/gendarme/framework/Gendarme.Framework.Rocks/PropertyRocks.cs
2433@@ -59,10 +59,9 @@ namespace Gendarme.Framework.Rocks {
2434 if (self == null)
2435 return false;
2436
2437- if (self.HasCustomAttributes) {
2438- if (self.CustomAttributes.ContainsAnyType (CustomAttributeRocks.GeneratedCodeAttributes))
2439- return true;
2440- }
2441+ if (self.HasAnyGeneratedCodeAttribute ())
2442+ return true;
2443+
2444 return self.DeclaringType.IsGeneratedCode ();
2445 }
2446 }
2447diff --git a/gendarme/framework/Gendarme.Framework.Rocks/TypeRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/TypeRocks.cs
2448index d549c63..efdcc0f 100644
2449--- a/gendarme/framework/Gendarme.Framework.Rocks/TypeRocks.cs
2450+++ b/gendarme/framework/Gendarme.Framework.Rocks/TypeRocks.cs
2451@@ -84,51 +84,6 @@ namespace Gendarme.Framework.Rocks {
2452 }
2453
2454 /// <summary>
2455- /// Check if a type reference collection contains a type of a specific name.
2456- /// </summary>
2457- /// <param name="self">The TypeReferenceCollection on which the extension method can be called.</param>
2458- /// <param name="typeName">Full name of the type.</param>
2459- /// <returns>True if the collection contains an type of the same name,
2460- /// False otherwise.</returns>
2461- public static bool ContainsType (this IEnumerable<TypeReference> self, string typeName)
2462- {
2463- if (typeName == null)
2464- throw new ArgumentNullException ("typeName");
2465- if (self == null)
2466- return false;
2467-
2468- foreach (TypeReference type in self) {
2469- if (type.FullName == typeName)
2470- return true;
2471- }
2472- return false;
2473- }
2474-
2475- /// <summary>
2476- /// Check if a type reference collection contains any of the specified type names.
2477- /// </summary>
2478- /// <param name="self">The TypeReferenceCollection on which the extension method can be called.</param>
2479- /// <param name="typeNames">A string array of full type names.</param>
2480- /// <returns>True if the collection contains any types matching one specified,
2481- /// False otherwise.</returns>
2482- public static bool ContainsAnyType (this IEnumerable<TypeReference> self, string [] typeNames)
2483- {
2484- if (typeNames == null)
2485- throw new ArgumentNullException ("typeNames");
2486- if (self == null)
2487- return false;
2488-
2489- foreach (TypeReference type in self) {
2490- string fullname = type.FullName;
2491- foreach (string type_full_name in typeNames) {
2492- if (fullname == type_full_name)
2493- return true;
2494- }
2495- }
2496- return false;
2497- }
2498-
2499- /// <summary>
2500 /// Returns the first MethodDefinition that satisfies a given MethodSignature.
2501 /// </summary>
2502 /// <param name="self">The TypeReference on which the extension method can be called.</param>
2503@@ -177,7 +132,7 @@ namespace Gendarme.Framework.Rocks {
2504 continue;
2505 if ((method.Attributes & attributes) != attributes)
2506 continue;
2507- if (returnType != null && method.ReturnType.FullName != returnType)
2508+ if (returnType != null && !method.ReturnType.IsNamed (returnType))
2509 continue;
2510 if (parameters != null) {
2511 if (method.HasParameters) {
2512@@ -188,7 +143,7 @@ namespace Gendarme.Framework.Rocks {
2513 for (int i = 0; i < parameters.Length; i++) {
2514 if (parameters [i] == null)
2515 continue;//ignore parameter
2516- if (parameters [i] != pdc [i].ParameterType.GetElementType ().FullName) {
2517+ if (!pdc [i].ParameterType.GetElementType ().IsNamed (parameters [i])) {
2518 parameterError = true;
2519 break;
2520 }
2521@@ -284,13 +239,16 @@ namespace Gendarme.Framework.Rocks {
2522 /// where the information resides could be unavailable. False is returned in this case.
2523 /// </summary>
2524 /// <param name="self">The TypeDefinition on which the extension method can be called.</param>
2525- /// <param name="interfaceName">Full name of the interface</param>
2526+ /// <param name="nameSpace">The namespace of the interface to be matched</param>
2527+ /// <param name="name">The name of the interface to be matched</param>
2528 /// <returns>True if we found that the type implements the interface, False otherwise (either it
2529 /// does not implement it, or we could not find where it does).</returns>
2530- public static bool Implements (this TypeReference self, string interfaceName)
2531+ public static bool Implements (this TypeReference self, string nameSpace, string name)
2532 {
2533- if (interfaceName == null)
2534- throw new ArgumentNullException ("interfaceName");
2535+ if (nameSpace == null)
2536+ throw new ArgumentNullException ("nameSpace");
2537+ if (name == null)
2538+ throw new ArgumentNullException ("name");
2539 if (self == null)
2540 return false;
2541
2542@@ -299,23 +257,22 @@ namespace Gendarme.Framework.Rocks {
2543 return false; // not enough information available
2544
2545 // special case, check if we implement ourselves
2546- if (type.IsInterface && (type.FullName == interfaceName))
2547+ if (type.IsInterface && type.IsNamed (nameSpace, name))
2548 return true;
2549
2550- return Implements (type, interfaceName, (interfaceName.IndexOf ('`') >= 0));
2551+ return Implements (type, nameSpace, name);
2552 }
2553
2554- private static bool Implements (TypeDefinition type, string interfaceName, bool generic)
2555+ private static bool Implements (TypeDefinition type, string nameSpace, string iname)
2556 {
2557 while (type != null) {
2558 // does the type implements it itself
2559 if (type.HasInterfaces) {
2560 foreach (TypeReference iface in type.Interfaces) {
2561- string fullname = (generic) ? iface.GetElementType ().FullName : iface.FullName;
2562- if (fullname == interfaceName)
2563+ if (iface.IsNamed (nameSpace, iname))
2564 return true;
2565 //if not, then maybe one of its parent interfaces does
2566- if (Implements (iface.Resolve (), interfaceName, generic))
2567+ if (Implements (iface.Resolve (), nameSpace, iname))
2568 return true;
2569 }
2570 }
2571@@ -331,21 +288,23 @@ namespace Gendarme.Framework.Rocks {
2572 /// where the information resides could be unavailable.
2573 /// </summary>
2574 /// <param name="self">The TypeReference on which the extension method can be called.</param>
2575- /// <param name="className">Full name of the base class</param>
2576+ /// <param name="nameSpace">The namespace of the base class to be matched</param>
2577+ /// <param name="name">The name of the base class to be matched</param>
2578 /// <returns>True if the type inherits from specified class, False otherwise</returns>
2579- public static bool Inherits (this TypeReference self, string className)
2580+ public static bool Inherits (this TypeReference self, string nameSpace, string name)
2581 {
2582- if (className == null)
2583- throw new ArgumentNullException ("className");
2584+ if (nameSpace == null)
2585+ throw new ArgumentNullException ("nameSpace");
2586+ if (name == null)
2587+ throw new ArgumentNullException ("name");
2588 if (self == null)
2589 return false;
2590
2591 TypeReference current = self.Resolve ();
2592 while (current != null) {
2593- string fullname = current.FullName;
2594- if (fullname == className)
2595+ if (current.IsNamed (nameSpace, name))
2596 return true;
2597- if (fullname == "System.Object")
2598+ if (current.IsNamed ("System", "Object"))
2599 return false;
2600
2601 TypeDefinition td = current.Resolve ();
2602@@ -357,6 +316,70 @@ namespace Gendarme.Framework.Rocks {
2603 }
2604
2605 /// <summary>
2606+ /// Check if the type and its namespace are named like the provided parameters.
2607+ /// This is preferred to checking the FullName property since the later can allocate (string) memory.
2608+ /// </summary>
2609+ /// <param name="self">The TypeReference on which the extension method can be called.</param>
2610+ /// <param name="nameSpace">The namespace to be matched</param>
2611+ /// <param name="name">The type name to be matched</param>
2612+ /// <returns>True if the type is namespace and name match the arguments, False otherwise</returns>
2613+ public static bool IsNamed (this TypeReference self, string nameSpace, string name)
2614+ {
2615+ if (nameSpace == null)
2616+ throw new ArgumentNullException ("nameSpace");
2617+ if (name == null)
2618+ throw new ArgumentNullException ("name");
2619+ if (self == null)
2620+ return false;
2621+
2622+ if (self.IsNested) {
2623+ int spos = name.LastIndexOf ('/');
2624+ if (spos == -1)
2625+ return false;
2626+ // GetFullName could be optimized away but it's a fairly uncommon case
2627+ return (nameSpace + "." + name == self.GetFullName ());
2628+ }
2629+
2630+ return ((self.Namespace == nameSpace) && (self.Name == name));
2631+ }
2632+
2633+ /// <summary>
2634+ /// Check if the type full name match the provided parameter.
2635+ /// Note: prefer the overload where the namespace and type name can be supplied individually
2636+ /// </summary>
2637+ /// <param name="self">The TypeReference on which the extension method can be called.</param>
2638+ /// <param name="fullName">The full name to be matched</param>
2639+ /// <returns>True if the type is namespace and name match the arguments, False otherwise</returns>
2640+ public static bool IsNamed (this TypeReference self, string fullName)
2641+ {
2642+ if (fullName == null)
2643+ throw new ArgumentNullException ("fullName");
2644+ if (self == null)
2645+ return false;
2646+
2647+ if (self.IsNested) {
2648+ int spos = fullName.LastIndexOf ('/');
2649+ if (spos == -1)
2650+ return false;
2651+ // FIXME: GetFullName could be optimized away but it's a fairly uncommon case
2652+ return (fullName == self.GetFullName ());
2653+ }
2654+
2655+ int dpos = fullName.LastIndexOf ('.');
2656+ string nspace = self.Namespace;
2657+ if (dpos != nspace.Length)
2658+ return false;
2659+
2660+ if (String.CompareOrdinal (nspace, 0, fullName, 0, dpos) != 0)
2661+ return false;
2662+
2663+ string name = self.Name;
2664+ if (fullName.Length - dpos - 1 != name.Length)
2665+ return false;
2666+ return (String.CompareOrdinal (name, 0, fullName, dpos + 1, fullName.Length - dpos - 1) == 0);
2667+ }
2668+
2669+ /// <summary>
2670 /// Checks if type is attribute. Note that it is possible that
2671 /// we might now be able to know all inheritance since the assembly where
2672 /// the information resides could be unavailable.
2673@@ -369,7 +392,7 @@ namespace Gendarme.Framework.Rocks {
2674 if (self == null)
2675 return false;
2676
2677- return self.Inherits ("System.Attribute");
2678+ return self.Inherits ("System", "Attribute");
2679 }
2680
2681 /// <summary>
2682@@ -387,13 +410,11 @@ namespace Gendarme.Framework.Rocks {
2683 if (null == type || type.BaseType == null)
2684 return false;
2685
2686- switch (type.BaseType.FullName) {
2687- case "System.Delegate":
2688- case "System.MulticastDelegate":
2689- return true;
2690- default:
2691+ if (type.BaseType.Namespace != "System")
2692 return false;
2693- }
2694+
2695+ string name = type.BaseType.Name;
2696+ return ((name == "Delegate") || (name == "MulticastDelegate"));
2697 }
2698
2699 /// <summary>
2700@@ -410,7 +431,7 @@ namespace Gendarme.Framework.Rocks {
2701 if ((type == null) || !type.IsEnum || !type.HasCustomAttributes)
2702 return false;
2703
2704- return type.HasAttribute ("System.FlagsAttribute");
2705+ return type.HasAttribute ("System", "FlagsAttribute");
2706 }
2707
2708 /// <summary>
2709@@ -423,9 +444,11 @@ namespace Gendarme.Framework.Rocks {
2710 if (self == null)
2711 return false;
2712
2713- string full_name = self.FullName;
2714- return ((full_name == "System.Single") ||
2715- (full_name == "System.Double"));
2716+ if (self.Namespace != "System")
2717+ return false;
2718+
2719+ string name = self.Name;
2720+ return ((name == "Single") || (name == "Double"));
2721 }
2722
2723 /// <summary>
2724@@ -443,7 +466,7 @@ namespace Gendarme.Framework.Rocks {
2725 TypeDefinition type = self.Resolve ();
2726 // both helpful attributes only exists in 2.0 and more recent frameworks
2727 if (type.Module.Runtime >= TargetRuntime.Net_2_0) {
2728- if (type.CustomAttributes.ContainsAnyType (CustomAttributeRocks.GeneratedCodeAttributes))
2729+ if (type.HasAnyGeneratedCodeAttribute ())
2730 return true;
2731 }
2732 }
2733@@ -471,14 +494,11 @@ namespace Gendarme.Framework.Rocks {
2734 if (self == null)
2735 return false;
2736
2737- switch (self.FullName) {
2738- case "System.IntPtr":
2739- case "System.UIntPtr":
2740- case "System.Runtime.InteropServices.HandleRef":
2741- return true;
2742- default:
2743- return false;
2744+ if (self.Namespace == "System") {
2745+ string name = self.Name;
2746+ return ((name == "IntPtr") || (name == "UIntPtr"));
2747 }
2748+ return self.IsNamed ("System.Runtime.InteropServices", "HandleRef");
2749 }
2750
2751 /// <summary>
2752diff --git a/gendarme/framework/Gendarme.Framework.Rocks/VariableDefinitionRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/VariableDefinitionRocks.cs
2753index 6749ebd..73e03e4 100644
2754--- a/gendarme/framework/Gendarme.Framework.Rocks/VariableDefinitionRocks.cs
2755+++ b/gendarme/framework/Gendarme.Framework.Rocks/VariableDefinitionRocks.cs
2756@@ -24,8 +24,9 @@
2757 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2758 // THE SOFTWARE.
2759
2760-using Mono.Cecil.Cil;
2761 using System;
2762+using System.Globalization;
2763+using Mono.Cecil.Cil;
2764
2765 namespace Gendarme.Framework.Rocks {
2766
2767@@ -53,7 +54,7 @@ namespace Gendarme.Framework.Rocks {
2768 {
2769 if (self == null)
2770 return String.Empty;
2771- return !string.IsNullOrEmpty (self.Name) ? self.Name : "V_" + self.Index.ToString ();
2772+ return !string.IsNullOrEmpty (self.Name) ? self.Name : "V_" + self.Index.ToString (CultureInfo.InvariantCulture);
2773 }
2774 }
2775 }
2776diff --git a/gendarme/framework/Gendarme.Framework.csproj b/gendarme/framework/Gendarme.Framework.csproj
2777index f9976af..ff5851b 100755
2778--- a/gendarme/framework/Gendarme.Framework.csproj
2779+++ b/gendarme/framework/Gendarme.Framework.csproj
2780@@ -1,5 +1,5 @@
2781 <?xml version="1.0" encoding="utf-8"?>\r
2782-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
2783+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
2784 <PropertyGroup>\r
2785 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
2786 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
2787@@ -12,9 +12,11 @@
2788 <AssemblyName>Gendarme.Framework</AssemblyName>\r
2789 <FileUpgradeFlags>\r
2790 </FileUpgradeFlags>\r
2791- <OldToolsVersion>2.0</OldToolsVersion>\r
2792+ <OldToolsVersion>3.5</OldToolsVersion>\r
2793 <UpgradeBackupLocation>\r
2794 </UpgradeBackupLocation>\r
2795+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
2796+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
2797 <PublishUrl>http://localhost/Gendarme.Framework/</PublishUrl>\r
2798 <Install>true</Install>\r
2799 <InstallFrom>Web</InstallFrom>\r
2800@@ -27,10 +29,9 @@
2801 <MapFileExtensions>true</MapFileExtensions>\r
2802 <ApplicationRevision>0</ApplicationRevision>\r
2803 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
2804- <IsWebBootstrapper>true</IsWebBootstrapper>\r
2805 <UseApplicationTrust>false</UseApplicationTrust>\r
2806 <BootstrapperEnabled>true</BootstrapperEnabled>\r
2807- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
2808+ <TargetFrameworkProfile />\r
2809 </PropertyGroup>\r
2810 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
2811 <DebugSymbols>true</DebugSymbols>\r
2812@@ -41,6 +42,7 @@
2813 <ErrorReport>prompt</ErrorReport>\r
2814 <WarningLevel>3</WarningLevel>\r
2815 <StartupObject />\r
2816+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
2817 </PropertyGroup>\r
2818 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
2819 <DebugType>pdbonly</DebugType>\r
2820@@ -50,6 +52,7 @@
2821 <ErrorReport>prompt</ErrorReport>\r
2822 <WarningLevel>4</WarningLevel>\r
2823 <StartupObject />\r
2824+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
2825 </PropertyGroup>\r
2826 <ItemGroup>\r
2827 <Reference Include="System" />\r
2828@@ -58,12 +61,17 @@
2829 </Reference>\r
2830 </ItemGroup>\r
2831 <ItemGroup>\r
2832+ <ProjectReference Include="..\..\..\cecil\Mono.Cecil.csproj">\r
2833+ <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
2834+ <Name>Mono.Cecil</Name>\r
2835+ </ProjectReference>\r
2836 </ItemGroup>\r
2837 <ItemGroup>\r
2838 <Compile Include="..\AssemblyStaticInfo.cs" />\r
2839 <Compile Include="Gendarme.Framework.Engines\SuppressMessageEngine.cs" />\r
2840 <Compile Include="Gendarme.Framework.Helpers\Log.cs" />\r
2841 <Compile Include="Gendarme.Framework.Helpers\MethodPrinter.cs" />\r
2842+ <Compile Include="Gendarme.Framework.Helpers\StreamLineReader.cs" />\r
2843 <Compile Include="Gendarme.Framework.Rocks\ParameterRocks.cs" />\r
2844 <Compile Include="Gendarme.Framework.Rocks\PropertyRocks.cs" />\r
2845 <Compile Include="Gendarme.Framework.Rocks\VariableDefinitionRocks.cs" />\r
2846@@ -118,21 +126,34 @@
2847 <None Include="ChangeLog" />\r
2848 </ItemGroup>\r
2849 <ItemGroup>\r
2850+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
2851+ <Visible>False</Visible>\r
2852+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
2853+ <Install>false</Install>\r
2854+ </BootstrapperPackage>\r
2855 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
2856 <Visible>False</Visible>\r
2857+ <ProductName>\r
2858+ </ProductName>\r
2859+ <Install>false</Install>\r
2860 </BootstrapperPackage>\r
2861 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
2862 <Visible>False</Visible>\r
2863+ <ProductName>\r
2864+ </ProductName>\r
2865+ <Install>false</Install>\r
2866 </BootstrapperPackage>\r
2867 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
2868 <Visible>False</Visible>\r
2869+ <ProductName>\r
2870+ </ProductName>\r
2871+ <Install>false</Install>\r
2872+ </BootstrapperPackage>\r
2873+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
2874+ <Visible>False</Visible>\r
2875+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
2876+ <Install>false</Install>\r
2877 </BootstrapperPackage>\r
2878- </ItemGroup>\r
2879- <ItemGroup>\r
2880- <ProjectReference Include="..\..\..\cecil\Mono.Cecil.csproj">\r
2881- <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
2882- <Name>Mono.Cecil</Name>\r
2883- </ProjectReference>\r
2884 </ItemGroup>\r
2885 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
2886 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
2887diff --git a/gendarme/framework/Gendarme.Framework/Symbols.cs b/gendarme/framework/Gendarme.Framework/Symbols.cs
2888index 5e76c20..f572643 100644
2889--- a/gendarme/framework/Gendarme.Framework/Symbols.cs
2890+++ b/gendarme/framework/Gendarme.Framework/Symbols.cs
2891@@ -39,7 +39,7 @@ namespace Gendarme.Framework {
2892 // http://blogs.msdn.com/jmstall/archive/2005/06/19/FeeFee_SequencePoints.aspx
2893 private const int PdbHiddenLine = 0xFEEFEE;
2894
2895- private static string AlmostEqualTo = new string (new char [] { '\u2248' });
2896+ private const string AlmostEqualTo = "\u2248";
2897
2898 private static Instruction ExtractFirst (TypeDefinition type)
2899 {
2900@@ -55,7 +55,7 @@ namespace Gendarme.Framework {
2901
2902 private static Instruction ExtractFirst (MethodDefinition method)
2903 {
2904- if ((method == null) || !method.HasBody)
2905+ if ((method == null) || !method.HasBody || method.Body.Instructions.Count == 0)
2906 return null;
2907 Instruction ins = method.Body.Instructions [0];
2908 // note that the first instruction often does not have a sequence point
2909@@ -69,11 +69,11 @@ namespace Gendarme.Framework {
2910 {
2911 MethodDefinition method = (location as MethodDefinition);
2912 if (method != null)
2913- return (method.DeclaringType as TypeDefinition);
2914+ return method.DeclaringType;
2915
2916 FieldDefinition field = (location as FieldDefinition);
2917 if (field != null)
2918- return (field.DeclaringType as TypeDefinition);
2919+ return field.DeclaringType;
2920
2921 ParameterDefinition parameter = (location as ParameterDefinition);
2922 if (parameter != null)
2923@@ -112,7 +112,7 @@ namespace Gendarme.Framework {
2924 // include line and column.
2925 private static string FormatSequencePoint (string document, int line, int column, bool exact)
2926 {
2927- string sline = (line == PdbHiddenLine) ? "unavailable" : line.ToString ();
2928+ string sline = (line == PdbHiddenLine) ? "unavailable" : line.ToString (CultureInfo.InvariantCulture);
2929
2930 // MDB (mono symbols) does not provide any column information (so we don't show any)
2931 // there's also no point in showing a column number if we're not totally sure about the line
2932@@ -177,7 +177,7 @@ namespace Gendarme.Framework {
2933 return FormatSource (candidate);
2934
2935 // we may still be lucky to find the (a) source file for the type itself
2936- type = (method.DeclaringType as TypeDefinition);
2937+ type = method.DeclaringType;
2938 }
2939
2940 // TypeDefinition, FieldDefinition
2941diff --git a/gendarme/framework/Gendarme.Framework/ThreadModelAttribute.cs b/gendarme/framework/Gendarme.Framework/ThreadModelAttribute.cs
2942index e40e34c..4c76f63 100644
2943--- a/gendarme/framework/Gendarme.Framework/ThreadModelAttribute.cs
2944+++ b/gendarme/framework/Gendarme.Framework/ThreadModelAttribute.cs
2945@@ -27,6 +27,7 @@
2946 //
2947
2948 using System;
2949+using System.Globalization;
2950
2951 // Note that these types are extended version of what we recommend
2952 // that users use. See DecorateThreadsRule documentation for a smaller version
2953@@ -82,7 +83,7 @@ namespace Gendarme.Framework {
2954 public override string ToString ()
2955 {
2956 if (AllowsEveryCaller)
2957- return string.Format ("{0} | AllowEveryCaller", Model);
2958+ return String.Format (CultureInfo.InvariantCulture, "{0} | AllowEveryCaller", Model);
2959
2960 return Model.ToString ();
2961 }
2962@@ -96,9 +97,9 @@ namespace Gendarme.Framework {
2963 return this == rhs;
2964 }
2965
2966- public bool Equals (ThreadModelAttribute rhs)
2967+ public bool Equals (ThreadModelAttribute other)
2968 {
2969- return this == rhs;
2970+ return this == other;
2971 }
2972
2973 public static bool operator== (ThreadModelAttribute lhs, ThreadModelAttribute rhs)
2974diff --git a/gendarme/framework/Makefile.am b/gendarme/framework/Makefile.am
2975index afbf5d9..13cbf9e 100644
2976--- a/gendarme/framework/Makefile.am
2977+++ b/gendarme/framework/Makefile.am
2978@@ -40,6 +40,7 @@ framework_sources = \
2979 Gendarme.Framework.Helpers/PrimitiveReferences.cs \
2980 Gendarme.Framework.Helpers/StackEntryAnalysis.cs \
2981 Gendarme.Framework.Helpers/StackEntryUsageResult.cs \
2982+ Gendarme.Framework.Helpers/StreamLineReader.cs \
2983 Gendarme.Framework.Rocks/AssemblyRocks.cs \
2984 Gendarme.Framework.Rocks/CecilRocks.cs \
2985 Gendarme.Framework.Rocks/CommonRocks.cs \
2986@@ -86,7 +87,7 @@ framework_build_sources += $(framework_generated_sources)
2987
2988 ../bin/Gendarme.Framework.dll: $(framework_build_sources) $(CECIL_ASM)
2989 test -d ../bin || mkdir ../bin
2990- $(GMCS) $(GENDARME_OPTIONS) -target:library -doc:$(framework_SCRIPTS).doc -r:$(CECIL_ASM) \
2991+ $(MCS) $(GENDARME_OPTIONS) -target:library -doc:$(framework_SCRIPTS).doc -r:$(CECIL_ASM) \
2992 -out:$@ $(framework_build_sources)
2993
2994 framework_test_sources = \
2995@@ -108,14 +109,14 @@ framework_test_sources = \
2996 framework_test_build_sources = $(addprefix $(srcdir)/Test/, $(framework_test_sources))
2997
2998 Test.Framework.dll: $(framework_test_build_sources) $(framework_rules_SCRIPTS) ../bin/Gendarme.Framework.dll $(CECIL_ASM)
2999- $(GMCS) $(TESTS_OPTIONS) -target:library -d:CODE_ANALYSIS -pkg:mono-nunit \
3000+ $(MCS) $(TESTS_OPTIONS) -target:library -d:CODE_ANALYSIS -pkg:mono-nunit \
3001 -r:$(CECIL_ASM) -r:../bin/Gendarme.Framework.dll -r:../rules/Test.Rules/Test.Rules.dll \
3002 -out:$@ $(framework_test_build_sources)
3003
3004 test: Test.Framework.dll
3005
3006 run-test: test
3007- MONO_PATH=../bin/:../rules/Test.Rules/:$(MONO_PATH) nunit-console2 -noshadow Test.Framework.dll
3008+ MONO_PATH=../bin/:../rules/Test.Rules/:$(MONO_PATH) $(prefix)/bin/mono $(prefix)/lib/mono/4.0/nunit-console.exe Test.Framework.dll
3009
3010 self-test: $(framework_SCRIPTS)
3011 mono --debug ../bin/gendarme.exe $(framework_SCRIPTS)
3012diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/AssemblyRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/AssemblyRocksTest.cs
3013index c4bbafd..061bccd 100644
3014--- a/gendarme/framework/Test/Gendarme.Framework.Rocks/AssemblyRocksTest.cs
3015+++ b/gendarme/framework/Test/Gendarme.Framework.Rocks/AssemblyRocksTest.cs
3016@@ -49,16 +49,23 @@ namespace Test.Framework.Rocks {
3017
3018 [Test]
3019 [ExpectedException (typeof (ArgumentNullException))]
3020- public void HasAttribute_Null ()
3021+ public void HasAttribute_Namespace_Null ()
3022 {
3023- assembly.HasAttribute (null);
3024+ assembly.HasAttribute (null, "a");
3025+ }
3026+
3027+ [Test]
3028+ [ExpectedException (typeof (ArgumentNullException))]
3029+ public void HasAttribute_Name_Null ()
3030+ {
3031+ assembly.HasAttribute ("a", null);
3032 }
3033
3034 [Test]
3035 public void HasAttribute ()
3036 {
3037- Assert.IsTrue (assembly.HasAttribute ("System.Runtime.CompilerServices.RuntimeCompatibilityAttribute"), "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute");
3038- Assert.IsFalse (assembly.HasAttribute ("NUnit.Framework.TestFixtureAttribute"), "TestFixtureAttribute");
3039+ Assert.IsTrue (assembly.HasAttribute ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute"), "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute");
3040+ Assert.IsFalse (assembly.HasAttribute ("NUnit.Framework", "TestFixtureAttribute"), "TestFixtureAttribute");
3041 }
3042 }
3043 }
3044diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/CustomAttributeRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/CustomAttributeRocksTest.cs
3045index 65a868e..78c6f81 100644
3046--- a/gendarme/framework/Test/Gendarme.Framework.Rocks/CustomAttributeRocksTest.cs
3047+++ b/gendarme/framework/Test/Gendarme.Framework.Rocks/CustomAttributeRocksTest.cs
3048@@ -50,59 +50,29 @@ namespace Test.Framework.Rocks {
3049
3050 [Test]
3051 [ExpectedException (typeof (ArgumentNullException))]
3052- public void Contains_Null ()
3053- {
3054- Collection<CustomAttribute> cac = new Collection<CustomAttribute> ();
3055- cac.ContainsType ((string) null);
3056- }
3057-
3058- [Test]
3059- public void Contains ()
3060- {
3061- TypeDefinition type = assembly.MainModule.GetType ("Test.Framework.Rocks.CustomAttributeRocksTest");
3062- Collection<CustomAttribute> cac = type.CustomAttributes;
3063- Assert.IsTrue (cac.ContainsType ("NUnit.Framework.TestFixtureAttribute"), "NUnit.Framework.TestFixtureAttribute");
3064- Assert.IsFalse (cac.ContainsType ("NUnit.Framework.TestFixture"), "NUnit.Framework.TestFixture");
3065- }
3066-
3067- [Test]
3068- [ExpectedException (typeof (ArgumentNullException))]
3069- public void ContainsAny_Null ()
3070- {
3071- Collection<CustomAttribute> cac = new Collection<CustomAttribute> ();
3072- cac.ContainsAnyType (null);
3073- }
3074-
3075- [Test]
3076- public void ContainsAny ()
3077+ public void HasAttribute_Namespace_Null ()
3078 {
3079 TypeDefinition type = assembly.MainModule.GetType ("Test.Framework.Rocks.CustomAttributeRocksTest");
3080- Collection<CustomAttribute> cac = type.CustomAttributes;
3081- Assert.IsTrue (cac.ContainsAnyType (new string[] {
3082- "NUnit.Framework.TestFixtureAttribute",
3083- null,
3084- "System.ICloneable"
3085- }), "NUnit.Framework.TestFixtureAttribute");
3086- Assert.IsFalse (cac.ContainsAnyType (new string[] {}), "NUnit.Framework.TestFixture");
3087+ type.HasAttribute (null, "a");
3088 }
3089
3090 [Test]
3091 [ExpectedException (typeof (ArgumentNullException))]
3092- public void HasAttribute_Null ()
3093+ public void HasAttribute_Name_Null ()
3094 {
3095 TypeDefinition type = assembly.MainModule.GetType ("Test.Framework.Rocks.CustomAttributeRocksTest");
3096- type.HasAttribute (null);
3097+ type.HasAttribute ("a", null);
3098 }
3099
3100 [Test]
3101 public void HasAttribute ()
3102 {
3103 TypeDefinition type = null;
3104- Assert.IsFalse (type.HasAttribute ("NUnit.Framework.TestFixtureAttribute"), "null-type");
3105+ Assert.IsFalse (type.HasAttribute ("NUnit.Framework", "TestFixtureAttribute"), "null-type");
3106
3107 type = assembly.MainModule.GetType ("Test.Framework.Rocks.CustomAttributeRocksTest");
3108- Assert.IsTrue (type.HasAttribute ("NUnit.Framework.TestFixtureAttribute"), "true");
3109- Assert.IsFalse (type.HasAttribute ("NUnit.Framework.TestAttribute"), "false");
3110+ Assert.IsTrue (type.HasAttribute ("NUnit.Framework", "TestFixtureAttribute"), "true");
3111+ Assert.IsFalse (type.HasAttribute ("NUnit.Framework", "TestAttribute"), "false");
3112 }
3113 }
3114 }
3115diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/FieldRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/FieldRocksTest.cs
3116index a790ed2..69ea851 100644
3117--- a/gendarme/framework/Test/Gendarme.Framework.Rocks/FieldRocksTest.cs
3118+++ b/gendarme/framework/Test/Gendarme.Framework.Rocks/FieldRocksTest.cs
3119@@ -74,16 +74,23 @@ namespace Test.Framework.Rocks {
3120
3121 [Test]
3122 [ExpectedException (typeof (ArgumentNullException))]
3123- public void HasAttribute_Null ()
3124+ public void HasAttribute_Namespace_Null ()
3125 {
3126- GetField ("assembly").HasAttribute (null);
3127+ GetField ("assembly").HasAttribute (null, "a");
3128+ }
3129+
3130+ [Test]
3131+ [ExpectedException (typeof (ArgumentNullException))]
3132+ public void HasAttribute_Name_Null ()
3133+ {
3134+ GetField ("assembly").HasAttribute ("a", null);
3135 }
3136
3137 [Test]
3138 public void HasAttribute ()
3139 {
3140- Assert.IsTrue (GetField ("cga").HasAttribute ("System.Runtime.CompilerServices.CompilerGeneratedAttribute"), "CompilerGeneratedAttribute");
3141- Assert.IsFalse (GetField ("cga").HasAttribute ("NUnit.Framework.TestFixtureAttribute"), "TestFixtureAttribute");
3142+ Assert.IsTrue (GetField ("cga").HasAttribute ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute"), "CompilerGeneratedAttribute");
3143+ Assert.IsFalse (GetField ("cga").HasAttribute ("NUnit.Framework", "TestFixtureAttribute"), "TestFixtureAttribute");
3144 }
3145
3146 [Test]
3147diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/MethodRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/MethodRocksTest.cs
3148index c43d680..3202358 100644
3149--- a/gendarme/framework/Test/Gendarme.Framework.Rocks/MethodRocksTest.cs
3150+++ b/gendarme/framework/Test/Gendarme.Framework.Rocks/MethodRocksTest.cs
3151@@ -112,18 +112,26 @@ namespace Test.Framework.Rocks {
3152
3153 [Test]
3154 [ExpectedException (typeof (ArgumentNullException))]
3155- public void HasAttribute_Null ()
3156+ public void HasAttribute_Namespace_Null ()
3157 {
3158 MethodDefinition method = GetMethod ("FixtureSetUp");
3159- method.HasAttribute ((string) null);
3160+ method.HasAttribute (null, "a");
3161+ }
3162+
3163+ [Test]
3164+ [ExpectedException (typeof (ArgumentNullException))]
3165+ public void HasAttribute_Name_Null ()
3166+ {
3167+ MethodDefinition method = GetMethod ("FixtureSetUp");
3168+ method.HasAttribute ("a", null);
3169 }
3170
3171 [Test]
3172 public void HasAttribute ()
3173 {
3174 MethodDefinition method = GetMethod ("FixtureSetUp");
3175- Assert.IsTrue (method.HasAttribute ("NUnit.Framework.TestFixtureSetUpAttribute"), "NUnit.Framework.TestFixtureSetUpAttribute");
3176- Assert.IsFalse (method.HasAttribute ("NUnit.Framework.TestFixtureSetUp"), "NUnit.Framework.TestFixtureSetUp");
3177+ Assert.IsTrue (method.HasAttribute ("NUnit.Framework", "TestFixtureSetUpAttribute"), "NUnit.Framework.TestFixtureSetUpAttribute");
3178+ Assert.IsFalse (method.HasAttribute ("NUnit.Framework", "TestFixtureSetUp"), "NUnit.Framework.TestFixtureSetUp");
3179 }
3180
3181 [Test]
3182diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/RocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/RocksTest.cs
3183index ed62b9c..4c746fa 100644
3184--- a/gendarme/framework/Test/Gendarme.Framework.Rocks/RocksTest.cs
3185+++ b/gendarme/framework/Test/Gendarme.Framework.Rocks/RocksTest.cs
3186@@ -49,6 +49,9 @@ namespace Test.Framework.Rocks {
3187 public abstract void PublicMethod ();
3188 protected abstract void ProtectedMethod ();
3189 private void PrivateMethod () { }
3190+
3191+ public abstract class NestedNestedPublicType {
3192+ }
3193 }
3194
3195 protected abstract class NestedProtectedType {
3196diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/TypeRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/TypeRocksTest.cs
3197index 51f782f..99366be 100644
3198--- a/gendarme/framework/Test/Gendarme.Framework.Rocks/TypeRocksTest.cs
3199+++ b/gendarme/framework/Test/Gendarme.Framework.Rocks/TypeRocksTest.cs
3200@@ -179,20 +179,27 @@ namespace Test.Framework.Rocks {
3201
3202 [Test]
3203 [ExpectedException (typeof (ArgumentNullException))]
3204- public void HasAttribute_Null ()
3205+ public void HasAttribute_Namespace_Null ()
3206 {
3207- GetType (String.Empty).HasAttribute (null);
3208+ GetType (String.Empty).HasAttribute (null, "a");
3209+ }
3210+
3211+ [Test]
3212+ [ExpectedException (typeof (ArgumentNullException))]
3213+ public void HasAttribute_Name_Null ()
3214+ {
3215+ GetType (String.Empty).HasAttribute ("a", null);
3216 }
3217
3218 [Test]
3219 public void HasAttribute ()
3220 {
3221- Assert.IsTrue (GetType (String.Empty).HasAttribute ("NUnit.Framework.TestFixtureAttribute"), "TypeRocksTest");
3222- Assert.IsFalse (GetType ("/Enum").HasAttribute ("System.FlagsAttribute"), "Enum/System.FlagsAttribute");
3223- Assert.IsTrue (GetType ("/Flags").HasAttribute ("System.FlagsAttribute"), "Flags/System.FlagsAttribute");
3224+ Assert.IsTrue (GetType (String.Empty).HasAttribute ("NUnit.Framework", "TestFixtureAttribute"), "TypeRocksTest");
3225+ Assert.IsFalse (GetType ("/Enum").HasAttribute ("System", "FlagsAttribute"), "Enum/System.FlagsAttribute");
3226+ Assert.IsTrue (GetType ("/Flags").HasAttribute ("System", "FlagsAttribute"), "Flags/System.FlagsAttribute");
3227 // fullname is required
3228- Assert.IsFalse (GetType ("/Flags").HasAttribute ("System.Flags"), "Flags/System.Flags");
3229- Assert.IsFalse (GetType ("/Flags").HasAttribute ("FlagsAttribute"), "Flags/FlagsAttribute");
3230+ Assert.IsFalse (GetType ("/Flags").HasAttribute ("System", "Flags"), "Flags/System.Flags");
3231+ Assert.IsFalse (GetType ("/Flags").HasAttribute ("", "FlagsAttribute"), "Flags/FlagsAttribute");
3232 }
3233
3234 [Test]
3235@@ -204,51 +211,65 @@ namespace Test.Framework.Rocks {
3236
3237 [Test]
3238 [ExpectedException (typeof (ArgumentNullException))]
3239- public void Implements_Null ()
3240+ public void Implements_Namespace_Null ()
3241+ {
3242+ GetType (String.Empty).Implements (null, "a");
3243+ }
3244+
3245+ [Test]
3246+ [ExpectedException (typeof (ArgumentNullException))]
3247+ public void Implements_Name_Null ()
3248 {
3249- GetType (String.Empty).Implements (null);
3250+ GetType (String.Empty).Implements ("a", null);
3251 }
3252
3253 [Test]
3254 public void Implements ()
3255 {
3256- Assert.IsFalse (GetType (String.Empty).Implements ("System.ICloneable"), "ICloneable");
3257- Assert.IsTrue (GetType ("/IDeepCloneable").Implements ("Test.Framework.Rocks.TypeRocksTest/IDeepCloneable"), "itself");
3258- Assert.IsTrue (GetType ("/IDeepCloneable").Implements ("System.ICloneable"), "interface inheritance");
3259- Assert.IsTrue (GetType ("/Deep").Implements ("Test.Framework.Rocks.TypeRocksTest/IDeepCloneable"), "IDeepCloneable");
3260- Assert.IsTrue (GetType ("/Deep").Implements ("System.ICloneable"), "second-level ICloneable");
3261- Assert.IsTrue (GetType ("/Mixin").Implements ("Test.Framework.Rocks.TypeRocksTest/IDeepCloneable"), "parent interface inheritance");
3262+ Assert.IsFalse (GetType (String.Empty).Implements ("System", "ICloneable"), "ICloneable");
3263+ Assert.IsTrue (GetType ("/IDeepCloneable").Implements ("Test.Framework.Rocks", "TypeRocksTest/IDeepCloneable"), "itself");
3264+ Assert.IsTrue (GetType ("/IDeepCloneable").Implements ("System", "ICloneable"), "interface inheritance");
3265+ Assert.IsTrue (GetType ("/Deep").Implements ("Test.Framework.Rocks", "TypeRocksTest/IDeepCloneable"), "IDeepCloneable");
3266+ Assert.IsTrue (GetType ("/Deep").Implements ("System", "ICloneable"), "second-level ICloneable");
3267+ Assert.IsTrue (GetType ("/Mixin").Implements ("Test.Framework.Rocks", "TypeRocksTest/IDeepCloneable"), "parent interface inheritance");
3268 }
3269
3270 [Test]
3271 [ExpectedException (typeof (ArgumentNullException))]
3272- public void Inherits_Null ()
3273+ public void Inherits_Namespace_Null ()
3274 {
3275- GetType (String.Empty).Inherits (null);
3276+ GetType (String.Empty).Inherits (null, "a");
3277+ }
3278+
3279+ [Test]
3280+ [ExpectedException (typeof (ArgumentNullException))]
3281+ public void Inherits_Name_Null ()
3282+ {
3283+ GetType (String.Empty).Inherits ("a", null);
3284 }
3285
3286 [Test]
3287 public void Inherits ()
3288 {
3289- Assert.IsFalse (GetType ("/NotAttribute").Inherits ("System.Attribute"), "NotAttribute");
3290- Assert.IsTrue (GetType ("/AnAttribute").Inherits ("System.Attribute"), "AnAttribute");
3291- Assert.IsFalse (GetType ("/ClassInheritsNotAttribute").Inherits ("System.Attribute"), "ClassInheritsNotAttribute");
3292- Assert.IsTrue (GetType ("/AttributeInheritsAnAttribute").Inherits ("System.Attribute"), "AttributeInheritsAnAttribute");
3293+ Assert.IsFalse (GetType ("/NotAttribute").Inherits ("System", "Attribute"), "NotAttribute");
3294+ Assert.IsTrue (GetType ("/AnAttribute").Inherits ("System", "Attribute"), "AnAttribute");
3295+ Assert.IsFalse (GetType ("/ClassInheritsNotAttribute").Inherits ("System", "Attribute"), "ClassInheritsNotAttribute");
3296+ Assert.IsTrue (GetType ("/AttributeInheritsAnAttribute").Inherits ("System", "Attribute"), "AttributeInheritsAnAttribute");
3297 }
3298
3299 [Test]
3300 public void Inherits_FromAnotherAssembly ()
3301 {
3302 // we can't be sure here so to avoid false positives return false
3303- Assert.IsTrue (GetType ("/AttributeInheritsOuterAttribute").Inherits ("System.Attribute"), "AttributeInheritsOuterAttribute");
3304- Assert.IsTrue (GetType ("/AttributeInheritsOuterAttributeDerivingAttribute").Inherits ("System.Attribute"), "AttributeInheritsOuterAttributeDerivingAttribute");
3305+ Assert.IsTrue (GetType ("/AttributeInheritsOuterAttribute").Inherits ("System", "Attribute"), "AttributeInheritsOuterAttribute");
3306+ Assert.IsTrue (GetType ("/AttributeInheritsOuterAttributeDerivingAttribute").Inherits ("System", "Attribute"), "AttributeInheritsOuterAttributeDerivingAttribute");
3307 }
3308
3309 [Test]
3310 public void Inherits_Itself ()
3311 {
3312 TypeDefinition type = GetType (String.Empty);
3313- Assert.IsTrue (type.Inherits (type.FullName), "itself");
3314+ Assert.IsTrue (type.Inherits (type.Namespace, type.Name), "itself");
3315 }
3316
3317 [Test]
3318@@ -322,6 +343,50 @@ namespace Test.Framework.Rocks {
3319 }
3320
3321 [Test]
3322+ public void IsNamed ()
3323+ {
3324+ string name = "Test.Framework.Rocks.PublicType";
3325+ TypeDefinition type = assembly.MainModule.GetType (name);
3326+
3327+ Assert.IsTrue (type.IsNamed ( "Test.Framework.Rocks.PublicType"));
3328+ Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks.P"));//Missing Text
3329+ Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks.PublicTypeExtraText"));
3330+
3331+ Assert.IsTrue (type.IsNamed ("Test.Framework.Rocks", "PublicType"));
3332+ Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks", "P"));//Missing Text
3333+ Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks", "PublicTypeExtraText"));
3334+ }
3335+
3336+ [Test]
3337+ public void IsNamedNestedType ()
3338+ {
3339+ string name = "Test.Framework.Rocks.PublicType/NestedPublicType";
3340+ TypeDefinition type = assembly.MainModule.GetType (name);
3341+
3342+ Assert.IsTrue (type.IsNamed ("Test.Framework.Rocks.PublicType/NestedPublicType"));
3343+ Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks.PublicType/N"));//Missing Text
3344+ Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks.PublicType/NestedPublicTypeExtaStuff"));
3345+
3346+ Assert.IsTrue (type.IsNamed ("Test.Framework.Rocks", "PublicType/NestedPublicType"));
3347+ Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks", "PublicType/N"));//Missing Text
3348+ Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks", "PublicType/NestedPublicTypeExtraText"));
3349+
3350+ Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks", "NestedPublicType"));
3351+ Assert.IsFalse (type.IsNamed ("", "NestedPublicType"));
3352+ }
3353+
3354+ [Test]
3355+ public void IsNamedDoubleNestedType ()
3356+ {
3357+ string name = "Test.Framework.Rocks.PublicType/NestedPublicType/NestedNestedPublicType";
3358+ TypeDefinition type = assembly.MainModule.GetType (name);
3359+
3360+ Assert.IsTrue (type.IsNamed ("Test.Framework.Rocks.PublicType/NestedPublicType/NestedNestedPublicType"));
3361+
3362+ Assert.IsTrue (type.IsNamed ("Test.Framework.Rocks", "PublicType/NestedPublicType/NestedNestedPublicType"));
3363+ }
3364+
3365+ [Test]
3366 public void IsVisible ()
3367 {
3368 string name = "Test.Framework.Rocks.PublicType";
3369diff --git a/gendarme/man/gendarme.1.in b/gendarme/man/gendarme.1.in
3370index 0389780..cc1989f 100644
3371--- a/gendarme/man/gendarme.1.in
3372+++ b/gendarme/man/gendarme.1.in
3373@@ -33,8 +33,7 @@ Specify the rule sets and rule settings. Default is 'rules.xml'.
3374 Specify a rule set from configfile. Defaults to 'default'.
3375 .TP
3376 .I "--log file"
3377-Save the report to the specified file. If none of --log, --xml, or --html are used
3378-then the report is written to stdout.
3379+Save the report, as a text file, to the specified file.
3380 .TP
3381 .I "--xml file"
3382 Save the report, formatted as XML, to the specified file.
3383@@ -42,6 +41,11 @@ Save the report, formatted as XML, to the specified file.
3384 .I "--html file"
3385 Save the report, formatted as HTML, to the specified file.
3386 .TP
3387+.I "--console"
3388+Write the defects on stdout. This is the default (implicit) behavior if none of
3389+--log, --xml, or --html options are specified. If (explicitely) specified then
3390+the defects will be shown on both stdout and inside text/xml/html report(s).
3391+.TP
3392 .I "--ignore ignore-file"
3393 Do not report defects listed in the specified file.
3394 .TP
3395diff --git a/gendarme/mono-options.ignore b/gendarme/mono-options.ignore
3396index c48ca1a..aa1799a 100644
3397--- a/gendarme/mono-options.ignore
3398+++ b/gendarme/mono-options.ignore
3399@@ -67,3 +67,15 @@ T: NDesk.Options.OptionSet
3400 R: Gendarme.Rules.Smells.AvoidCodeDuplicatedInSameClassRule
3401 T: NDesk.Options.OptionSet
3402
3403+R: Gendarme.Rules.Globalization.PreferStringComparisonOverrideRule
3404+M: System.String NDesk.Options.OptionSet::GetArgumentName(System.Int32,System.Int32,System.String)
3405+
3406+R: Gendarme.Rules.Globalization.PreferIFormatProviderOverrideRule
3407+M: System.Void NDesk.Options.Option::AddSeparators(System.String,System.Int32,System.Collections.Generic.ICollection`1<System.String>)
3408+M: System.Boolean NDesk.Options.OptionSet::ParseBundledValue(System.String,System.String,NDesk.Options.OptionContext)
3409+M: System.Void NDesk.Options.OptionValueCollection::AssertValid(System.Int32)
3410+M: System.Void NDesk.Options.Option::.ctor(System.String,System.String,System.Int32)
3411+M: NDesk.Options.OptionValueType NDesk.Options.Option::ParsePrototype()
3412+M: T NDesk.Options.Option::Parse(System.String,NDesk.Options.OptionContext)
3413+M: System.Void NDesk.Options.OptionSet::ParseValue(System.String,NDesk.Options.OptionContext)
3414+
3415diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidAssemblyVersionMismatchRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidAssemblyVersionMismatchRule.cs
3416index 3b2ba33..dc43d09 100644
3417--- a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidAssemblyVersionMismatchRule.cs
3418+++ b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidAssemblyVersionMismatchRule.cs
3419@@ -25,6 +25,7 @@
3420 // THE SOFTWARE.
3421
3422 using System;
3423+using System.Globalization;
3424
3425 using Mono.Cecil;
3426 using Mono.Cecil.Cil;
3427@@ -61,26 +62,6 @@ namespace Gendarme.Rules.BadPractice {
3428 [Solution ("This situation can be confusing once deployed. Make sure both version are identical.")]
3429 public class AvoidAssemblyVersionMismatchRule : Rule, IAssemblyRule {
3430
3431- static bool VersionTryParse (string input, out Version result)
3432- {
3433- result = null;
3434- if (String.IsNullOrEmpty (input))
3435- return false;
3436-
3437- try {
3438- result = new Version (input);
3439- return true;
3440- }
3441- catch (ArgumentException) {
3442- // also cover ArgumentOutOfRangeException
3443- }
3444- catch (FormatException) {
3445- }
3446- catch (OverflowException) {
3447- }
3448- return false;
3449- }
3450-
3451 public RuleResult CheckAssembly (AssemblyDefinition assembly)
3452 {
3453 if (!assembly.HasCustomAttributes)
3454@@ -100,11 +81,10 @@ namespace Gendarme.Rules.BadPractice {
3455 // any attribute without arguments can be skipped
3456 if (!ca.HasConstructorArguments)
3457 continue;
3458- if (ca.AttributeType.FullName != "System.Reflection.AssemblyFileVersionAttribute")
3459+ if (!ca.AttributeType.IsNamed ("System.Reflection", "AssemblyFileVersionAttribute"))
3460 continue;
3461
3462- // FIXME: replace with Version.TryParse once we upgrade to FX4.0
3463- VersionTryParse (ca.ConstructorArguments [0].Value as string, out file_version);
3464+ Version.TryParse (ca.ConstructorArguments [0].Value as string, out file_version);
3465 break;
3466 }
3467
3468@@ -127,9 +107,11 @@ namespace Gendarme.Rules.BadPractice {
3469 else if (assembly_version.Revision == file_version.Revision)
3470 return RuleResult.Success;
3471
3472- string msg = String.Format ("Assembly version is '{0}' while file version is '{1}'.", assembly_version, file_version);
3473+ string msg = String.Format (CultureInfo.InvariantCulture,
3474+ "Assembly version is '{0}' while file version is '{1}'.", assembly_version, file_version);
3475 Runner.Report (assembly, s, Confidence.High, msg);
3476 return RuleResult.Failure;
3477 }
3478 }
3479 }
3480+
3481diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidCallingProblematicMethodsRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidCallingProblematicMethodsRule.cs
3482index 777cc02..87d00c2 100644
3483--- a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidCallingProblematicMethodsRule.cs
3484+++ b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidCallingProblematicMethodsRule.cs
3485@@ -27,8 +27,9 @@
3486 //
3487
3488 using System;
3489-using System.Reflection;
3490+using System.Globalization;
3491 using System.Collections.Generic;
3492+using System.Reflection;
3493
3494 using Mono.Cecil;
3495 using Mono.Cecil.Cil;
3496@@ -100,22 +101,22 @@ namespace Gendarme.Rules.BadPractice {
3497 public AvoidCallingProblematicMethodsRule ()
3498 {
3499 problematicMethods.Add ("Collect", (m, i) =>
3500- (m.DeclaringType.FullName == "System.GC") ? Severity.Critical : (Severity?) null);
3501+ m.DeclaringType.IsNamed ("System", "GC") ? Severity.Critical : (Severity?) null);
3502 problematicMethods.Add ("Suspend", (m, i) =>
3503- (m.DeclaringType.FullName == "System.Threading.Thread") ? Severity.Medium : (Severity?) null);
3504+ m.DeclaringType.IsNamed ("System.Threading", "Thread") ? Severity.Medium : (Severity?) null);
3505 problematicMethods.Add ("Resume", (m, i) =>
3506- (m.DeclaringType.FullName == "System.Threading.Thread") ? Severity.Medium : (Severity?) null);
3507+ m.DeclaringType.IsNamed ("System.Threading", "Thread") ? Severity.Medium : (Severity?) null);
3508 problematicMethods.Add ("DangerousGetHandle", (m, i) =>
3509- (m.DeclaringType.FullName == "System.Runtime.InteropServices.SafeHandle") ? Severity.Critical : (Severity?) null);
3510+ m.DeclaringType.IsNamed ("System.Runtime.InteropServices", "SafeHandle") ? Severity.Critical : (Severity?) null);
3511 problematicMethods.Add ("LoadFrom", (m, i) =>
3512- (m.DeclaringType.FullName == "System.Reflection.Assembly") ? Severity.High : (Severity?) null);
3513+ m.DeclaringType.IsNamed ("System.Reflection", "Assembly") ? Severity.High : (Severity?) null);
3514 problematicMethods.Add ("LoadFile", (m, i) =>
3515- (m.DeclaringType.FullName == "System.Reflection.Assembly") ? Severity.High : (Severity?) null);
3516+ m.DeclaringType.IsNamed ("System.Reflection", "Assembly") ? Severity.High : (Severity?) null);
3517 problematicMethods.Add ("LoadWithPartialName", (m, i) =>
3518- (m.DeclaringType.FullName == "System.Reflection.Assembly") ? Severity.High : (Severity?) null);
3519+ m.DeclaringType.IsNamed ("System.Reflection", "Assembly") ? Severity.High : (Severity?) null);
3520 problematicMethods.Add ("InvokeMember", (m, i) =>
3521- (m.DeclaringType.FullName != "System.Type") ? (Severity?) null :
3522- IsAccessingWithNonPublicModifiers (i) ? Severity.Critical : (Severity?) null);
3523+ !m.DeclaringType.IsNamed ("System", "Type") ? (Severity?) null :
3524+ IsAccessingWithNonPublicModifiers (i) ? Severity.Critical : (Severity?) null);
3525 }
3526
3527 private static bool OperandIsNonPublic (BindingFlags operand)
3528@@ -166,7 +167,8 @@ namespace Gendarme.Rules.BadPractice {
3529
3530 Severity? severity = IsProblematicCall (instruction);
3531 if (severity.HasValue) {
3532- string msg = String.Format ("You are calling to {0}, which is a potentially problematic method",
3533+ string msg = String.Format (CultureInfo.InvariantCulture,
3534+ "You are calling to {0}, which is a potentially problematic method",
3535 instruction.Operand);
3536 Runner.Report (method, instruction, severity.Value, Confidence.High, msg);
3537 }
3538diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidNullCheckWithAsOperatorRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidNullCheckWithAsOperatorRule.cs
3539new file mode 100644
3540index 0000000..26394d9
3541--- /dev/null
3542+++ b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidNullCheckWithAsOperatorRule.cs
3543@@ -0,0 +1,141 @@
3544+//
3545+// Gendarme.Rules.BadPractice.AvoidNullCheckWithAsOperatorRule
3546+//
3547+// Authors:
3548+// Sebastien Pouliot <sebastien@ximian.com>
3549+//
3550+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
3551+//
3552+// Permission is hereby granted, free of charge, to any person obtaining
3553+// a copy of this software and associated documentation files (the
3554+// "Software"), to deal in the Software without restriction, including
3555+// without limitation the rights to use, copy, modify, merge, publish,
3556+// distribute, sublicense, and/or sell copies of the Software, and to
3557+// permit persons to whom the Software is furnished to do so, subject to
3558+// the following conditions:
3559+//
3560+// The above copyright notice and this permission notice shall be
3561+// included in all copies or substantial portions of the Software.
3562+//
3563+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
3564+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3565+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
3566+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
3567+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
3568+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
3569+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3570+//
3571+
3572+using System;
3573+
3574+using Mono.Cecil;
3575+using Mono.Cecil.Cil;
3576+
3577+using Gendarme.Framework;
3578+using Gendarme.Framework.Engines;
3579+using Gendarme.Framework.Helpers;
3580+using Gendarme.Framework.Rocks;
3581+
3582+namespace Gendarme.Rules.BadPractice {
3583+
3584+ /// <summary>
3585+ /// The rule will detect if a null check is done before using the <c>as</c> operator.
3586+ /// This null check is not needed, a <c>null</c> instance will return <c>null</c>,
3587+ /// and the code will need to deal with <c>as</c> returning a null value anyway.
3588+ /// </summary>
3589+ /// <example>
3590+ /// Bad example:
3591+ /// <code>
3592+ /// public string AsString (object obj)
3593+ /// {
3594+ /// return (o == null) ? null : o as string;
3595+ /// }
3596+ /// </code>
3597+ /// </example>
3598+ /// <example>
3599+ /// Good example:
3600+ /// <code>
3601+ /// public string AsString (object obj)
3602+ /// {
3603+ /// return (o as string);
3604+ /// }
3605+ /// </code>
3606+ /// </example>
3607+ // as suggested in https://bugzilla.novell.com/show_bug.cgi?id=651305
3608+ [Problem ("An unneeded null check is done before using the 'as' operator.")]
3609+ [Solution ("Remove the extraneous null check")]
3610+ [EngineDependency (typeof (OpCodeEngine))]
3611+ public class AvoidNullCheckWithAsOperatorRule : Rule, IMethodRule {
3612+
3613+ OpCodeBitmask mask = new OpCodeBitmask (0x100000, 0x10000000000000, 0x0, 0x0);
3614+
3615+ static bool CheckFalseBranch (Instruction ins)
3616+ {
3617+ Instruction next = ins.Next;
3618+ if (!next.Is (ins.Previous.OpCode.Code))
3619+ return false;
3620+
3621+ if (!(ins.Operand as Instruction).Is (Code.Ldnull))
3622+ return false;
3623+
3624+ return CheckIsinst (next.Next);
3625+ }
3626+
3627+ static bool CheckTrueBranch (Instruction ins)
3628+ {
3629+ if (!ins.Next.Is (Code.Ldnull))
3630+ return false;
3631+
3632+ Instruction br = (ins.Operand as Instruction);
3633+ if (ins.Previous.OpCode.Code != br.OpCode.Code)
3634+ return false;
3635+
3636+ return CheckIsinst (br.Next);
3637+ }
3638+
3639+ static bool CheckIsinst (Instruction ins)
3640+ {
3641+ if (!ins.Is (Code.Isinst))
3642+ return false;
3643+ return (ins.Next.OpCode.FlowControl != FlowControl.Cond_Branch);
3644+ }
3645+
3646+ public RuleResult CheckMethod (MethodDefinition method)
3647+ {
3648+ // rule only applies to methods with IL...
3649+ if (!method.HasBody)
3650+ return RuleResult.DoesNotApply;
3651+
3652+ // and when the IL contains both a isinst and ldnull
3653+ if (!mask.IsSubsetOf (OpCodeEngine.GetBitmask (method)))
3654+ return RuleResult.DoesNotApply;
3655+
3656+ foreach (Instruction ins in method.Body.Instructions) {
3657+ bool detected = false;
3658+ switch (ins.OpCode.Code) {
3659+ case Code.Brfalse_S:
3660+ case Code.Brfalse:
3661+ detected = CheckFalseBranch (ins);
3662+ break;
3663+ case Code.Brtrue_S:
3664+ case Code.Brtrue:
3665+ detected = CheckTrueBranch (ins);
3666+ break;
3667+ }
3668+ if (detected)
3669+ Runner.Report (method, ins, Severity.Medium, Confidence.Normal);
3670+ }
3671+
3672+ return Runner.CurrentRuleResult;
3673+ }
3674+#if false
3675+ public void Bitmask ()
3676+ {
3677+ OpCodeBitmask mask = new OpCodeBitmask ();
3678+ mask.Set (Code.Isinst);
3679+ mask.Set (Code.Ldnull);
3680+ Console.WriteLine (mask);
3681+ }
3682+#endif
3683+ }
3684+}
3685diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidVisibleConstantFieldRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidVisibleConstantFieldRule.cs
3686index 0831682..c18be47 100644
3687--- a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidVisibleConstantFieldRule.cs
3688+++ b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidVisibleConstantFieldRule.cs
3689@@ -24,6 +24,8 @@
3690 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3691 // THE SOFTWARE.
3692
3693+using System.Globalization;
3694+
3695 using Mono.Cecil;
3696 using Mono.Cecil.Cil;
3697
3698@@ -80,11 +82,12 @@ namespace Gendarme.Rules.BadPractice {
3699
3700 // we let null constant for all reference types (since they can't be changed to anything else)
3701 // except for strings (which can be modified later)
3702- string type_name = field.FieldType.FullName;
3703- if (!field.FieldType.IsValueType && (type_name != "System.String"))
3704+ TypeReference ftype = field.FieldType;
3705+ if (!ftype.IsValueType && !ftype.IsNamed ("System", "String"))
3706 continue;
3707
3708- string msg = string.Format ("'{0}' of type {1}.", field.Name, type_name);
3709+ string msg = string.Format (CultureInfo.InvariantCulture, "'{0}' of type {1}.",
3710+ field.Name, ftype.GetFullName ());
3711 Runner.Report (field, Severity.High, Confidence.High, msg);
3712
3713 }
3714diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewExceptionWithoutThrowingRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewExceptionWithoutThrowingRule.cs
3715index e40aed6..183a18c 100644
3716--- a/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewExceptionWithoutThrowingRule.cs
3717+++ b/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewExceptionWithoutThrowingRule.cs
3718@@ -96,7 +96,7 @@ namespace Gendarme.Rules.BadPractice {
3719
3720 MethodReference constructor = (MethodReference) ins.Operand;
3721
3722- if (!constructor.DeclaringType.Inherits ("System.Exception"))
3723+ if (!constructor.DeclaringType.Inherits ("System", "Exception"))
3724 continue;
3725
3726 // quick check to save resources
3727diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewThreadWithoutStartRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewThreadWithoutStartRule.cs
3728index 3f01bb1..ac0c146 100644
3729--- a/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewThreadWithoutStartRule.cs
3730+++ b/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewThreadWithoutStartRule.cs
3731@@ -110,8 +110,6 @@ namespace Gendarme.Rules.BadPractice {
3732 return false;
3733 }
3734
3735- private const string Thread = "System.Threading.Thread";
3736-
3737 public override void Initialize (IRunner runner)
3738 {
3739 base.Initialize (runner);
3740@@ -119,8 +117,10 @@ namespace Gendarme.Rules.BadPractice {
3741 // if the module does not reference (sealed) System.Threading.Thread
3742 // then no code inside the module will instanciate it
3743 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
3744- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
3745- e.CurrentModule.HasTypeReference (Thread);
3746+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
3747+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
3748+ return tr.IsNamed ("System.Threading", "Thread");
3749+ }));
3750 };
3751 }
3752
3753@@ -141,11 +141,11 @@ namespace Gendarme.Rules.BadPractice {
3754
3755 MethodReference constructor = (MethodReference) ins.Operand;
3756
3757- if (constructor.DeclaringType.FullName != Thread)
3758+ if (!constructor.DeclaringType.IsNamed ("System.Threading", "Thread"))
3759 continue;
3760 if (ins.Next != null && (ins.Next.OpCode.Code == Code.Call || ins.Next.OpCode.Code == Code.Callvirt)) { //quick check to safe resources
3761 MethodReference calledMethod = (MethodReference) ins.Next.Operand;
3762- if ((calledMethod.DeclaringType.FullName == Thread) && (calledMethod.Name == "Start"))
3763+ if (calledMethod.IsNamed ("System.Threading", "Thread", "Start"))
3764 continue;
3765 }
3766
3767diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/CloneMethodShouldNotReturnNullRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/CloneMethodShouldNotReturnNullRule.cs
3768index eff7ae0..e740a02 100644
3769--- a/gendarme/rules/Gendarme.Rules.BadPractice/CloneMethodShouldNotReturnNullRule.cs
3770+++ b/gendarme/rules/Gendarme.Rules.BadPractice/CloneMethodShouldNotReturnNullRule.cs
3771@@ -69,8 +69,6 @@ namespace Gendarme.Rules.BadPractice {
3772 [Solution ("Return an appropriate object instead of returning null.")]
3773 public class CloneMethodShouldNotReturnNullRule : ReturnNullRule, IMethodRule {
3774
3775- private const string ICloneable = "System.ICloneable";
3776-
3777 public override void Initialize (IRunner runner)
3778 {
3779 base.Initialize (runner);
3780@@ -78,8 +76,10 @@ namespace Gendarme.Rules.BadPractice {
3781 // if the module does not reference System.ICloneable then
3782 // no type inside will be implementing it
3783 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
3784- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
3785- e.CurrentModule.HasTypeReference (ICloneable);
3786+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
3787+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
3788+ return tr.IsNamed ("System", "ICloneable");
3789+ }));
3790 };
3791 }
3792
3793@@ -90,7 +90,7 @@ namespace Gendarme.Rules.BadPractice {
3794 return RuleResult.DoesNotApply;
3795
3796 // where the type implements ICloneable
3797- if (!method.DeclaringType.Implements (ICloneable))
3798+ if (!method.DeclaringType.Implements ("System", "ICloneable"))
3799 return RuleResult.DoesNotApply;
3800
3801 // call base class to detect if the method can return null
3802diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/ConstructorShouldNotCallVirtualMethodsRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/ConstructorShouldNotCallVirtualMethodsRule.cs
3803index d3758bb..7f47cf5 100644
3804--- a/gendarme/rules/Gendarme.Rules.BadPractice/ConstructorShouldNotCallVirtualMethodsRule.cs
3805+++ b/gendarme/rules/Gendarme.Rules.BadPractice/ConstructorShouldNotCallVirtualMethodsRule.cs
3806@@ -28,6 +28,7 @@
3807
3808 using System;
3809 using System.Collections.Generic;
3810+using System.Globalization;
3811 using System.Linq;
3812
3813 using Mono.Cecil;
3814@@ -177,7 +178,7 @@ namespace Gendarme.Rules.BadPractice {
3815 if (mr.HasThis)
3816 parameters++;
3817 parameters += mr.Parameters.Count;
3818- if (mr.ReturnType.FullName != "System.Void")
3819+ if (!mr.ReturnType.IsNamed ("System", "Void"))
3820 parameters--;
3821 }
3822 break;
3823@@ -196,7 +197,7 @@ namespace Gendarme.Rules.BadPractice {
3824 if (!OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)))
3825 return;
3826
3827- string method_name = method.ToString ();
3828+ string method_name = method.GetFullName ();
3829 // check to avoid constructors calling recursive methods
3830 if (stack.Contains (method_name))
3831 return;
3832@@ -216,12 +217,14 @@ namespace Gendarme.Rules.BadPractice {
3833 continue;
3834
3835 // check that we're not calling the method on another object
3836- if (!IsCallFromInstance (current.Previous, md.Parameters.Count))
3837+ int n = md.HasParameters ? md.Parameters.Count : 0;
3838+ if (!IsCallFromInstance (current.Previous, n))
3839 continue;
3840
3841 if (md.IsVirtual && !md.IsFinal) {
3842 string s = stack.Count == 0 ? method_name : stack.Aggregate ((a1, a2) => a1 + ", " + Environment.NewLine + a2);
3843- s = String.Format ("Calling a virtual method, '{0}' from {1}.", md, s);
3844+ s = String.Format (CultureInfo.InvariantCulture,
3845+ "Calling a virtual method, '{0}' from {1}.", md, s);
3846 Runner.Report (method, current, Severity.High, Confidence.High, s);
3847 } else {
3848 stack.Push (method_name);
3849diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DisableDebuggingCodeRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DisableDebuggingCodeRule.cs
3850index f1c6049..9534ca5 100644
3851--- a/gendarme/rules/Gendarme.Rules.BadPractice/DisableDebuggingCodeRule.cs
3852+++ b/gendarme/rules/Gendarme.Rules.BadPractice/DisableDebuggingCodeRule.cs
3853@@ -89,9 +89,6 @@ namespace Gendarme.Rules.BadPractice {
3854 [EngineDependency (typeof (OpCodeEngine))]
3855 public class DisableDebuggingCodeRule : Rule, IMethodRule {
3856
3857- private const string ConditionalAttribute = "System.Diagnostics.ConditionalAttribute";
3858- private const string Console = "System.Console";
3859-
3860 // note: there can be multiple [Conditional] attribute on a method
3861 private static bool HasConditionalAttributeForDebugging (IList<CustomAttribute> cac)
3862 {
3863@@ -101,7 +98,7 @@ namespace Gendarme.Rules.BadPractice {
3864 // any attribute without arguments can be skipped
3865 if (!ca.HasConstructorArguments)
3866 continue;
3867- if (ca.AttributeType.FullName == ConditionalAttribute) {
3868+ if (ca.AttributeType.IsNamed ("System.Diagnostics", "ConditionalAttribute")) {
3869 switch (ca.ConstructorArguments [0].Value as string) {
3870 case "DEBUG":
3871 case "TRACE":
3872@@ -126,7 +123,9 @@ namespace Gendarme.Rules.BadPractice {
3873 // if the module does not reference System.Console then no
3874 // method inside it will be calling any Console.write* methods
3875 (e.CurrentAssembly.Name.Name == "mscorlib" ||
3876- e.CurrentModule.HasTypeReference (Console));
3877+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
3878+ return tr.IsNamed ("System", "Console");
3879+ }));
3880 };
3881 }
3882
3883@@ -152,8 +151,12 @@ namespace Gendarme.Rules.BadPractice {
3884 continue;
3885
3886 // ... to System.Console ...
3887- MethodReference mr = (ins.Operand as MethodReference);
3888- if (mr.DeclaringType.FullName != Console)
3889+ MethodReference mr = ins.Operand as MethodReference;
3890+
3891+ if (mr == null)
3892+ continue;
3893+
3894+ if (!mr.DeclaringType.IsNamed ("System", "Console"))
3895 continue;
3896
3897 // ... Write* methods
3898diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotDecreaseVisibilityRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotDecreaseVisibilityRule.cs
3899new file mode 100644
3900index 0000000..4b387df
3901--- /dev/null
3902+++ b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotDecreaseVisibilityRule.cs
3903@@ -0,0 +1,124 @@
3904+//
3905+// Gendarme.Rules.BadPractice.DoNotDecreaseVisibilityRule
3906+//
3907+// Authors:
3908+// Sebastien Pouliot <sebastien@ximian.com>
3909+//
3910+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
3911+//
3912+// Permission is hereby granted, free of charge, to any person obtaining a copy
3913+// of this software and associated documentation files (the "Software"), to deal
3914+// in the Software without restriction, including without limitation the rights
3915+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3916+// copies of the Software, and to permit persons to whom the Software is
3917+// furnished to do so, subject to the following conditions:
3918+//
3919+// The above copyright notice and this permission notice shall be included in
3920+// all copies or substantial portions of the Software.
3921+//
3922+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3923+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3924+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3925+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3926+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3927+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3928+// THE SOFTWARE.
3929+
3930+using Mono.Cecil;
3931+
3932+using Gendarme.Framework;
3933+using Gendarme.Framework.Rocks;
3934+
3935+namespace Gendarme.Rules.BadPractice {
3936+
3937+ /// <summary>
3938+ /// The rule detect when a method visibility is decreased in an inherited type.
3939+ /// Decreasing visibility does not prevent calling the base class method unless
3940+ /// the type is <c>sealed</c>. Note that some language (but not C#) will allow
3941+ /// you to seal, e.g. <c>final</c>, the method without an <c>override</c>.
3942+ /// </summary>
3943+ /// <example>
3944+ /// Bad example:
3945+ /// <code>
3946+ /// public class Base {
3947+ /// public void Public ()
3948+ /// {
3949+ /// }
3950+ /// }
3951+ ///
3952+ /// public class BadInheritor : Base {
3953+ /// private new void Public ()
3954+ /// {
3955+ /// }
3956+ /// }
3957+ /// </code>
3958+ /// </example>
3959+ /// <example>
3960+ /// Good example (do not hide):
3961+ /// <code>
3962+ /// public class Inheritor : Base {
3963+ /// }
3964+ /// </code>
3965+ /// </example>
3966+ /// <example>
3967+ /// Good example (sealed type):
3968+ /// <code>
3969+ /// public sealed class Inheritor : Base {
3970+ /// private new void Public ()
3971+ /// {
3972+ /// }
3973+ /// }
3974+ /// </code>
3975+ /// </example>
3976+ [Problem ("A private method is hiding a visible method from a base type")]
3977+ [Solution ("Either seal the inherited type or rename/remove the private method.")]
3978+ [FxCopCompatibility ("Microsoft.Usage", "CA2222:DoNotDecreaseInheritedMemberVisibility")]
3979+ public class DoNotDecreaseVisibilityRule : Rule, IMethodRule {
3980+
3981+ static bool IsHiding (MethodDefinition method, TypeReference type)
3982+ {
3983+ if (type == null)
3984+ return false;
3985+
3986+ TypeDefinition td = type.Resolve ();
3987+ if ((td != null) && td.HasMethods) {
3988+ string name = method.Name;
3989+ foreach (MethodDefinition md in td.Methods) {
3990+ if (!md.IsPublic && !md.IsFamily)
3991+ continue;
3992+ if (name != md.Name)
3993+ continue;
3994+ if (method.CompareSignature (md))
3995+ return true;
3996+ }
3997+ }
3998+
3999+ return IsHiding (method, type.DeclaringType);
4000+ }
4001+
4002+ public RuleResult CheckMethod (MethodDefinition method)
4003+ {
4004+ if (!method.IsPrivate || method.IsFinal)
4005+ return RuleResult.DoesNotApply;
4006+
4007+ TypeDefinition type = method.DeclaringType;
4008+ if (type.IsSealed)
4009+ return RuleResult.DoesNotApply;
4010+
4011+ // we got a private, non-final, method in an unsealed type
4012+
4013+ // note: unlike CSC, MCS does not mark .cctor with hidebysig
4014+ // this also covers a private default ctor inheriting from System.Object
4015+ if (method.IsConstructor && !method.HasParameters)
4016+ return RuleResult.Success;
4017+
4018+ // are we're hiding something ?
4019+ if (method.IsHideBySig && !IsHiding (method, type.BaseType))
4020+ return RuleResult.Success;
4021+
4022+ Runner.Report (method, Severity.High, Confidence.Normal);
4023+ return RuleResult.Failure;
4024+ }
4025+ }
4026+}
4027+
4028diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotForgetNotImplementedMethodsRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotForgetNotImplementedMethodsRule.cs
4029index d90a8b3..c4ce839 100644
4030--- a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotForgetNotImplementedMethodsRule.cs
4031+++ b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotForgetNotImplementedMethodsRule.cs
4032@@ -93,7 +93,7 @@ namespace Gendarme.Rules.BadPractice {
4033 if (inst.OpCode.Code != Code.Newobj)
4034 continue;
4035 MethodReference ctor = (MethodReference) inst.Operand;
4036- if ("System.NotImplementedException" != ctor.DeclaringType.FullName)
4037+ if (!ctor.DeclaringType.IsNamed ("System", "NotImplementedException"))
4038 continue;
4039 if (inst.Next.OpCode.Code != Code.Throw)
4040 continue;
4041diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseEnumIsAssignableFromRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseEnumIsAssignableFromRule.cs
4042index dd6280e..5fd5d90 100644
4043--- a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseEnumIsAssignableFromRule.cs
4044+++ b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseEnumIsAssignableFromRule.cs
4045@@ -99,7 +99,7 @@ namespace Gendarme.Rules.BadPractice {
4046 if (type == null)
4047 return false;
4048
4049- return type.FullName == "System.Enum";
4050+ return type.IsNamed ("System", "Enum");
4051 }
4052
4053 static bool IsCallToTypeIsAssignableFrom (Instruction instruction)
4054@@ -124,10 +124,7 @@ namespace Gendarme.Rules.BadPractice {
4055 if (operand.Name != name)
4056 return false;
4057
4058- if (operand.DeclaringType.FullName != "System.Type")
4059- return false;
4060-
4061- return true;
4062+ return operand.DeclaringType.IsNamed ("System", "Type");
4063 }
4064
4065 static bool IsCall (OpCode opcode)
4066diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseGetInterfaceToCheckAssignabilityRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseGetInterfaceToCheckAssignabilityRule.cs
4067index 05edf49..a94bf42 100644
4068--- a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseGetInterfaceToCheckAssignabilityRule.cs
4069+++ b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseGetInterfaceToCheckAssignabilityRule.cs
4070@@ -86,7 +86,7 @@ namespace Gendarme.Rules.BadPractice {
4071 MethodReference call = (ins.Operand as MethodReference);
4072 if (call.Name != "GetInterface")
4073 continue;
4074- if (!call.DeclaringType.Inherits ("System.Type")) // not a sealed type
4075+ if (!call.DeclaringType.Inherits ("System", "Type")) // not a sealed type
4076 continue;
4077
4078 // check for a null compare
4079diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Gendarme.Rules.BadPractice.csproj b/gendarme/rules/Gendarme.Rules.BadPractice/Gendarme.Rules.BadPractice.csproj
4080index 0b595dc..2841537 100755
4081--- a/gendarme/rules/Gendarme.Rules.BadPractice/Gendarme.Rules.BadPractice.csproj
4082+++ b/gendarme/rules/Gendarme.Rules.BadPractice/Gendarme.Rules.BadPractice.csproj
4083@@ -1,5 +1,5 @@
4084 <?xml version="1.0" encoding="utf-8"?>\r
4085-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
4086+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
4087 <PropertyGroup>\r
4088 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
4089 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
4090@@ -10,8 +10,28 @@
4091 <AppDesignerFolder>Properties</AppDesignerFolder>\r
4092 <RootNamespace>Gendarme.Rules.BadPractice</RootNamespace>\r
4093 <AssemblyName>Gendarme.Rules.BadPractice</AssemblyName>\r
4094- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
4095+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
4096 <FileAlignment>512</FileAlignment>\r
4097+ <FileUpgradeFlags>\r
4098+ </FileUpgradeFlags>\r
4099+ <OldToolsVersion>3.5</OldToolsVersion>\r
4100+ <UpgradeBackupLocation />\r
4101+ <PublishUrl>publish\</PublishUrl>\r
4102+ <Install>true</Install>\r
4103+ <InstallFrom>Disk</InstallFrom>\r
4104+ <UpdateEnabled>false</UpdateEnabled>\r
4105+ <UpdateMode>Foreground</UpdateMode>\r
4106+ <UpdateInterval>7</UpdateInterval>\r
4107+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
4108+ <UpdatePeriodically>false</UpdatePeriodically>\r
4109+ <UpdateRequired>false</UpdateRequired>\r
4110+ <MapFileExtensions>true</MapFileExtensions>\r
4111+ <ApplicationRevision>0</ApplicationRevision>\r
4112+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
4113+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
4114+ <UseApplicationTrust>false</UseApplicationTrust>\r
4115+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
4116+ <TargetFrameworkProfile />\r
4117 </PropertyGroup>\r
4118 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
4119 <DebugSymbols>true</DebugSymbols>\r
4120@@ -24,6 +44,7 @@
4121 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.BadPractice.xml</DocumentationFile>\r
4122 <NoWarn>1591</NoWarn>\r
4123 <WarningsAsErrors>1570</WarningsAsErrors>\r
4124+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
4125 </PropertyGroup>\r
4126 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
4127 <DebugType>pdbonly</DebugType>\r
4128@@ -35,6 +56,7 @@
4129 <NoWarn>1591</NoWarn>\r
4130 <WarningsAsErrors>1570</WarningsAsErrors>\r
4131 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.BadPractice.xml</DocumentationFile>\r
4132+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
4133 </PropertyGroup>\r
4134 <ItemGroup>\r
4135 <Reference Include="System" />\r
4136@@ -80,6 +102,23 @@
4137 <Name>Gendarme.Framework</Name>\r
4138 </ProjectReference>\r
4139 </ItemGroup>\r
4140+ <ItemGroup>\r
4141+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
4142+ <Visible>False</Visible>\r
4143+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
4144+ <Install>false</Install>\r
4145+ </BootstrapperPackage>\r
4146+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
4147+ <Visible>False</Visible>\r
4148+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
4149+ <Install>true</Install>\r
4150+ </BootstrapperPackage>\r
4151+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
4152+ <Visible>False</Visible>\r
4153+ <ProductName>Windows Installer 3.1</ProductName>\r
4154+ <Install>true</Install>\r
4155+ </BootstrapperPackage>\r
4156+ </ItemGroup>\r
4157 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
4158 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
4159 Other similar extension points exist, see Microsoft.Common.targets.
4160diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/GetEntryAssemblyMayReturnNullRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/GetEntryAssemblyMayReturnNullRule.cs
4161index 3719234..5dc1626 100644
4162--- a/gendarme/rules/Gendarme.Rules.BadPractice/GetEntryAssemblyMayReturnNullRule.cs
4163+++ b/gendarme/rules/Gendarme.Rules.BadPractice/GetEntryAssemblyMayReturnNullRule.cs
4164@@ -70,8 +70,6 @@ namespace Gendarme.Rules.BadPractice {
4165 [EngineDependency (typeof (OpCodeEngine))]
4166 public class GetEntryAssemblyMayReturnNullRule : Rule, IMethodRule {
4167
4168- private const string Assembly = "System.Reflection.Assembly";
4169-
4170 public override void Initialize (IRunner runner)
4171 {
4172 base.Initialize (runner);
4173@@ -81,13 +79,20 @@ namespace Gendarme.Rules.BadPractice {
4174 // GetEntryAssembly will work inside executables
4175 e.CurrentAssembly.EntryPoint == null &&
4176
4177- // if the module does not reference System.Reflection.Assembly
4178- // then no method inside it will be calling GetEntryAssembly
4179+ // if the module does not reference System.Reflection.Assembly.GetEntryAssembly
4180+ // then there's no point in enabling the rule
4181 (e.CurrentAssembly.Name.Name == "mscorlib" ||
4182- e.CurrentModule.HasTypeReference (Assembly));
4183+ e.CurrentModule.AnyMemberReference ((MemberReference mr) => {
4184+ return IsGetEntryAssembly (mr);
4185+ }));
4186 };
4187 }
4188
4189+ static bool IsGetEntryAssembly (MemberReference method)
4190+ {
4191+ return method.IsNamed ("System.Reflection", "Assembly", "GetEntryAssembly");
4192+ }
4193+
4194 public RuleResult CheckMethod (MethodDefinition method)
4195 {
4196 // rule doesn't not apply to methods without code (e.g. p/invokes)
4197@@ -108,11 +113,8 @@ namespace Gendarme.Rules.BadPractice {
4198 switch (current.OpCode.Code) {
4199 case Code.Call:
4200 case Code.Callvirt:
4201- MethodReference mr = (current.Operand as MethodReference);
4202- if ((mr != null) && (mr.Name == "GetEntryAssembly")
4203- && (mr.DeclaringType.FullName == Assembly)) {
4204- Runner.Report (method, current, Severity.Medium, Confidence.Total, String.Empty);
4205- }
4206+ if (IsGetEntryAssembly (current.Operand as MethodReference))
4207+ Runner.Report (method, current, Severity.Medium, Confidence.Total);
4208 break;
4209 }
4210 }
4211diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Makefile.am b/gendarme/rules/Gendarme.Rules.BadPractice/Makefile.am
4212index 5dc3f47..5237708 100644
4213--- a/gendarme/rules/Gendarme.Rules.BadPractice/Makefile.am
4214+++ b/gendarme/rules/Gendarme.Rules.BadPractice/Makefile.am
4215@@ -3,12 +3,14 @@ include ../common.make
4216 rules_sources = \
4217 AvoidAssemblyVersionMismatchRule.cs \
4218 AvoidCallingProblematicMethodsRule.cs \
4219+ AvoidNullCheckWithAsOperatorRule.cs \
4220 AvoidVisibleConstantFieldRule.cs \
4221 CheckNewExceptionWithoutThrowingRule.cs \
4222 CheckNewThreadWithoutStartRule.cs \
4223 CloneMethodShouldNotReturnNullRule.cs \
4224 ConstructorShouldNotCallVirtualMethodsRule.cs \
4225 DisableDebuggingCodeRule.cs \
4226+ DoNotDecreaseVisibilityRule.cs \
4227 DoNotForgetNotImplementedMethodsRule.cs \
4228 DoNotUseEnumIsAssignableFromRule.cs \
4229 DoNotUseGetInterfaceToCheckAssignabilityRule.cs \
4230@@ -27,12 +29,14 @@ rules_sources = \
4231
4232 tests_sources = \
4233 AvoidAssemblyVersionMismatchTest.cs \
4234- AvoidVisibleConstantFieldTest.cs \
4235 AvoidCallingProblematicMethodsTest.cs \
4236+ AvoidNullCheckWithAsOperatorTest.cs \
4237+ AvoidVisibleConstantFieldTest.cs \
4238 CheckNewExceptionWithoutThrowingTest.cs \
4239 CheckNewThreadWithoutStartTest.cs \
4240 CloneMethodShouldNotReturnNullTest.cs \
4241 ConstructorShouldNotCallVirtualMethodsTest.cs \
4242+ DoNotDecreaseVisibilityTest.cs \
4243 DoNotForgetNotImplementedMethodsTest.cs \
4244 DoNotUseEnumIsAssignableFromTest.cs \
4245 DoNotUseGetInterfaceToCheckAssignabilityTest.cs \
4246diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/ObsoleteMessagesShouldNotBeEmptyRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/ObsoleteMessagesShouldNotBeEmptyRule.cs
4247index da0fdd5..33e5802 100644
4248--- a/gendarme/rules/Gendarme.Rules.BadPractice/ObsoleteMessagesShouldNotBeEmptyRule.cs
4249+++ b/gendarme/rules/Gendarme.Rules.BadPractice/ObsoleteMessagesShouldNotBeEmptyRule.cs
4250@@ -70,8 +70,6 @@ namespace Gendarme.Rules.BadPractice {
4251 [FxCopCompatibility ("Microsoft.Design", "CA1041:ProvideObsoleteAttributeMessage")]
4252 public class ObsoleteMessagesShouldNotBeEmptyRule : Rule, ITypeRule {
4253
4254- private const string ObsoleteAttribute = "System.ObsoleteAttribute";
4255-
4256 public override void Initialize (IRunner runner)
4257 {
4258 base.Initialize (runner);
4259@@ -79,8 +77,10 @@ namespace Gendarme.Rules.BadPractice {
4260 // if the module does not have a reference to System.ObsoleteAttribute
4261 // then nothing will be marked as obsolete inside it
4262 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
4263- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
4264- e.CurrentModule.HasTypeReference (ObsoleteAttribute);
4265+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
4266+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
4267+ return tr.IsNamed ("System", "ObsoleteAttribute");
4268+ }));
4269 };
4270 }
4271
4272@@ -92,7 +92,7 @@ namespace Gendarme.Rules.BadPractice {
4273 foreach (CustomAttribute ca in cap.CustomAttributes) {
4274 // ObsoleteAttribute has a three (3) ctors, including a default (parameter-less) ctor
4275 // http://msdn.microsoft.com/en-us/library/68k270ch.aspx
4276- if (ca.AttributeType.FullName != ObsoleteAttribute)
4277+ if (!ca.AttributeType.IsNamed ("System", "ObsoleteAttribute"))
4278 continue;
4279
4280 // note: we don't have to check fields since they cannot be used
4281diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/OnlyUseDisposeForIDisposableTypesRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/OnlyUseDisposeForIDisposableTypesRule.cs
4282index 0425323..9647199 100644
4283--- a/gendarme/rules/Gendarme.Rules.BadPractice/OnlyUseDisposeForIDisposableTypesRule.cs
4284+++ b/gendarme/rules/Gendarme.Rules.BadPractice/OnlyUseDisposeForIDisposableTypesRule.cs
4285@@ -94,9 +94,9 @@ namespace Gendarme.Rules.BadPractice {
4286
4287 Log.WriteLine (this);
4288 Log.WriteLine (this, "----------------------------------");
4289- Log.WriteLine (this, type.FullName);
4290+ Log.WriteLine (this, type);
4291
4292- if (!type.Implements ("System.IDisposable")) {
4293+ if (!type.Implements ("System", "IDisposable")) {
4294 Log.WriteLine (this, "type does not implement IDisposable");
4295
4296 foreach (MethodDefinition method in type.Methods.Where (m => m.Name == "Dispose"))
4297diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/PreferEmptyInstanceOverNullRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/PreferEmptyInstanceOverNullRule.cs
4298index 5c16da9..c6cbebc 100644
4299--- a/gendarme/rules/Gendarme.Rules.BadPractice/PreferEmptyInstanceOverNullRule.cs
4300+++ b/gendarme/rules/Gendarme.Rules.BadPractice/PreferEmptyInstanceOverNullRule.cs
4301@@ -25,6 +25,7 @@
4302 // THE SOFTWARE.
4303
4304 using System;
4305+using System.Globalization;
4306
4307 using Mono.Cecil;
4308 using Mono.Cecil.Cil;
4309@@ -146,9 +147,9 @@ namespace Gendarme.Rules.BadPractice {
4310
4311 //only apply to methods returning string, array, or IEnumerable-impl
4312 return_type = method.ReturnType;
4313- string_return_type = (return_type.FullName == "System.String");
4314+ string_return_type = return_type.IsNamed ("System", "String");
4315 array_return_type = return_type.IsArray;
4316- ienumerable_return_type = return_type.Implements ("System.Collections.IEnumerable");
4317+ ienumerable_return_type = return_type.Implements ("System.Collections", "IEnumerable");
4318
4319 if (!string_return_type && !array_return_type && !ienumerable_return_type)
4320 return RuleResult.DoesNotApply;
4321@@ -158,7 +159,7 @@ namespace Gendarme.Rules.BadPractice {
4322
4323 protected override void Report (MethodDefinition method, Instruction ins)
4324 {
4325- string msg = string.Format ("Replace null with {0}.", SuggestReturnType ());
4326+ string msg = String.Format (CultureInfo.InvariantCulture, "Replace null with {0}.", SuggestReturnType ());
4327 Runner.Report (method, ins, method.IsVisible () ? Severity.Medium : Severity.Low, Confidence.Normal, msg);
4328 }
4329
4330@@ -167,7 +168,7 @@ namespace Gendarme.Rules.BadPractice {
4331 if (string_return_type)
4332 return "string.Empty";
4333 else if (array_return_type)
4334- return string.Format ("an empty {0} array", return_type.Name);
4335+ return String.Format (CultureInfo.InvariantCulture, "an empty {0} array", return_type.Name);
4336 else if (ienumerable_return_type)
4337 return "yield break (or equivalent)";
4338 return "an empty collection";
4339diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/PreferParamsArrayForVariableArgumentsRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/PreferParamsArrayForVariableArgumentsRule.cs
4340index 10751fd..c048420 100644
4341--- a/gendarme/rules/Gendarme.Rules.BadPractice/PreferParamsArrayForVariableArgumentsRule.cs
4342+++ b/gendarme/rules/Gendarme.Rules.BadPractice/PreferParamsArrayForVariableArgumentsRule.cs
4343@@ -83,7 +83,9 @@ namespace Gendarme.Rules.BadPractice {
4344
4345 Runner.AnalyzeModule += (object o, RunnerEventArgs e) => {
4346 Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
4347- e.CurrentModule.HasTypeReference ("System.ArgIterator"));
4348+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
4349+ return tr.IsNamed ("System", "ArgIterator");
4350+ }));
4351 };
4352 }
4353
4354diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/PreferSafeHandleRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/PreferSafeHandleRule.cs
4355index f87ac97..6d93dcc 100644
4356--- a/gendarme/rules/Gendarme.Rules.BadPractice/PreferSafeHandleRule.cs
4357+++ b/gendarme/rules/Gendarme.Rules.BadPractice/PreferSafeHandleRule.cs
4358@@ -186,9 +186,12 @@ namespace Gendarme.Rules.BadPractice {
4359 static FieldDefinition FindIntPtr (TypeDefinition type)
4360 {
4361 foreach (FieldDefinition field in type.Fields) {
4362- string name = field.FieldType.FullName;
4363- if (name == "System.IntPtr" || name == "System.UIntPtr")
4364- return field;
4365+ TypeReference ftype = field.FieldType;
4366+ if (ftype.Namespace == "System") {
4367+ string name = ftype.Name;
4368+ if ((name == "IntPtr") || (name == "UIntPtr"))
4369+ return field;
4370+ }
4371 }
4372
4373 return null;
4374@@ -212,7 +215,7 @@ namespace Gendarme.Rules.BadPractice {
4375
4376 Log.WriteLine (this);
4377 Log.WriteLine (this, "----------------------------------");
4378- Log.WriteLine (this, type.FullName);
4379+ Log.WriteLine (this, type);
4380
4381 FieldDefinition field = FindIntPtr (type);
4382 if (field != null) {
4383@@ -222,7 +225,7 @@ namespace Gendarme.Rules.BadPractice {
4384 if (finalizer != null)
4385 confidence = (Confidence) ((int) confidence - 1); // lower numbers have higher confidence
4386
4387- if (type.Implements ("System.IDisposable"))
4388+ if (type.Implements ("System", "IDisposable"))
4389 confidence = (Confidence) ((int) confidence - 1);
4390
4391 Log.WriteLine (this, "'{0}' is an IntPtr.", field.Name);
4392diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/PreferTryParseRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/PreferTryParseRule.cs
4393index 432c9ba..7856cdb 100644
4394--- a/gendarme/rules/Gendarme.Rules.BadPractice/PreferTryParseRule.cs
4395+++ b/gendarme/rules/Gendarme.Rules.BadPractice/PreferTryParseRule.cs
4396@@ -118,6 +118,7 @@ namespace Gendarme.Rules.BadPractice {
4397 static bool HasTryParseMethod (TypeDefinition type)
4398 {
4399 bool present = false;
4400+
4401 if (!has_try_parse.TryGetValue (type, out present)) {
4402 foreach (MethodReference method in type.Methods) {
4403 if (MethodSignatures.TryParse.Matches (method)) {
4404@@ -162,7 +163,8 @@ namespace Gendarme.Rules.BadPractice {
4405 if (!MethodSignatures.Parse.Matches (mr))
4406 continue;
4407
4408- if (!HasTryParseMethod (mr.DeclaringType.Resolve ()))
4409+ TypeDefinition declaringType = mr.DeclaringType.Resolve();
4410+ if (declaringType != null && !HasTryParseMethod(declaringType))
4411 continue;
4412
4413 // if inside a try (catch/finally) block then...
4414diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/README.md b/gendarme/rules/Gendarme.Rules.BadPractice/README.md
4415new file mode 100644
4416index 0000000..dc0fb44
4417--- /dev/null
4418+++ b/gendarme/rules/Gendarme.Rules.BadPractice/README.md
4419@@ -0,0 +1,9 @@
4420+# Gendarme.Rules.BadPractice Rules
4421+
4422+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.BadPractice(git)]] pages.
4423+
4424+
4425+## Feedback
4426+
4427+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
4428+
4429diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Test/AvoidNullCheckWithAsOperatorTest.cs b/gendarme/rules/Gendarme.Rules.BadPractice/Test/AvoidNullCheckWithAsOperatorTest.cs
4430new file mode 100644
4431index 0000000..65f9d50
4432--- /dev/null
4433+++ b/gendarme/rules/Gendarme.Rules.BadPractice/Test/AvoidNullCheckWithAsOperatorTest.cs
4434@@ -0,0 +1,142 @@
4435+//
4436+// Unit Tests for AvoidNullCheckWithAsOperatorRule
4437+//
4438+// Authors:
4439+// Sebastien Pouliot <sebastien@ximian.com>
4440+//
4441+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
4442+//
4443+// Permission is hereby granted, free of charge, to any person obtaining
4444+// a copy of this software and associated documentation files (the
4445+// "Software"), to deal in the Software without restriction, including
4446+// without limitation the rights to use, copy, modify, merge, publish,
4447+// distribute, sublicense, and/or sell copies of the Software, and to
4448+// permit persons to whom the Software is furnished to do so, subject to
4449+// the following conditions:
4450+//
4451+// The above copyright notice and this permission notice shall be
4452+// included in all copies or substantial portions of the Software.
4453+//
4454+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
4455+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4456+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
4457+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
4458+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
4459+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
4460+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
4461+//
4462+
4463+using System;
4464+using Gendarme.Rules.BadPractice;
4465+
4466+using NUnit.Framework;
4467+using Test.Rules.Definitions;
4468+using Test.Rules.Fixtures;
4469+
4470+namespace Test.Rules.BadPractice {
4471+
4472+ [TestFixture]
4473+ public class AvoidNullCheckWithAsOperatorTest : MethodRuleTestFixture<AvoidNullCheckWithAsOperatorRule> {
4474+
4475+ string AsString_Bad1a (object obj)
4476+ {
4477+ return obj == null ? null : obj as string;
4478+ }
4479+
4480+ string AsString_Bad1b (object obj)
4481+ {
4482+ if (obj != null)
4483+ return obj as string;
4484+ return null;
4485+ }
4486+
4487+ string AsString_Bad2a (object obj)
4488+ {
4489+ return obj != null ? obj as string : null;
4490+ }
4491+
4492+ string AsString_Bad2b (object obj)
4493+ {
4494+ if (obj == null)
4495+ return null;
4496+ return obj as string;
4497+ }
4498+
4499+ string AsString_Good (object obj)
4500+ {
4501+ return obj as string;
4502+ }
4503+
4504+ string AsString_Good2 (string message, object obj)
4505+ {
4506+ if (message == null)
4507+ throw new ArgumentNullException ("message");
4508+ Console.WriteLine (message);
4509+ return obj as string;
4510+ }
4511+
4512+ string AsString_Good3 (string message, object obj)
4513+ {
4514+ if (message == null)
4515+ return null;
4516+ Console.WriteLine (message);
4517+ return obj as string;
4518+ }
4519+
4520+ void LocalsBad1a ()
4521+ {
4522+ object o = null;
4523+ string a = o == null ? null : o as string;
4524+ Console.WriteLine (a);
4525+ }
4526+
4527+ void LocalsBad2a ()
4528+ {
4529+ object o = null;
4530+ string a = o != null ? o as string : null;
4531+ Console.WriteLine (a);
4532+ }
4533+
4534+ // extracted from: moon/class/System.Windows/Mono.Xaml/XamlPropertySetter.cs
4535+ // no 'as' has been harmed by this test
4536+ object ConvertValue (object value)
4537+ {
4538+ if (value == null)
4539+ return null;
4540+
4541+ if (value is Type || value is SimpleMethods)
4542+ return value;
4543+
4544+ return value.ToString ();
4545+ }
4546+
4547+ [Test]
4548+ public void DoesNotApply ()
4549+ {
4550+ AssertRuleDoesNotApply (SimpleMethods.ExternalMethod);
4551+ AssertRuleDoesNotApply (SimpleMethods.EmptyMethod);
4552+ // no ldnull instruction
4553+ AssertRuleDoesNotApply<AvoidNullCheckWithAsOperatorTest> ("AsString_Good");
4554+ AssertRuleDoesNotApply<AvoidNullCheckWithAsOperatorTest> ("AsString_Good2");
4555+ }
4556+
4557+ [Test]
4558+ public void Success ()
4559+ {
4560+ AssertRuleSuccess<AvoidNullCheckWithAsOperatorTest> ("AsString_Good3");
4561+ AssertRuleSuccess<AvoidNullCheckWithAsOperatorTest> ("ConvertValue");
4562+ }
4563+
4564+ [Test]
4565+ public void Failure ()
4566+ {
4567+ AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("AsString_Bad1a");
4568+ AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("AsString_Bad1b");
4569+ AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("AsString_Bad2a");
4570+ AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("AsString_Bad2b");
4571+
4572+ AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("LocalsBad1a");
4573+ AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("LocalsBad2a");
4574+ }
4575+ }
4576+}
4577diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Test/DoNotDecreaseVisibilityTest.cs b/gendarme/rules/Gendarme.Rules.BadPractice/Test/DoNotDecreaseVisibilityTest.cs
4578new file mode 100644
4579index 0000000..9bafda7
4580--- /dev/null
4581+++ b/gendarme/rules/Gendarme.Rules.BadPractice/Test/DoNotDecreaseVisibilityTest.cs
4582@@ -0,0 +1,210 @@
4583+//
4584+// Tests.Rules.BadPractice.DoNotDecreaseVisibilityTest
4585+//
4586+// Authors:
4587+// Sebastien Pouliot <sebastien@ximian.com>
4588+//
4589+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
4590+//
4591+// Permission is hereby granted, free of charge, to any person obtaining a copy
4592+// of this software and associated documentation files (the "Software"), to deal
4593+// in the Software without restriction, including without limitation the rights
4594+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4595+// copies of the Software, and to permit persons to whom the Software is
4596+// furnished to do so, subject to the following conditions:
4597+//
4598+// The above copyright notice and this permission notice shall be included in
4599+// all copies or substantial portions of the Software.
4600+//
4601+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4602+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4603+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4604+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4605+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4606+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4607+// THE SOFTWARE.
4608+
4609+using System;
4610+
4611+using Mono.Cecil;
4612+using Gendarme.Rules.BadPractice ;
4613+
4614+using NUnit.Framework;
4615+using Test.Rules.Fixtures;
4616+using Test.Rules.Helpers;
4617+using Test.Rules.Definitions;
4618+
4619+namespace Test.Rules.BadPractice {
4620+
4621+ [TestFixture]
4622+ public class DoNotDecreaseVisibilityTest : MethodRuleTestFixture<DoNotDecreaseVisibilityRule> {
4623+
4624+ public class TestCase {
4625+
4626+ public class Base {
4627+ public void Public ()
4628+ {
4629+ }
4630+
4631+ protected bool Protected (int x)
4632+ {
4633+ return x == 0;
4634+ }
4635+
4636+ internal int Internal ()
4637+ {
4638+ return -1;
4639+ }
4640+
4641+ private float Private (float f)
4642+ {
4643+ return f;
4644+ }
4645+ }
4646+
4647+ public class BadInheritor : Base {
4648+ private new void Public ()
4649+ {
4650+ }
4651+
4652+ private new bool Protected (int x)
4653+ {
4654+ return x == 1;
4655+ }
4656+
4657+ private new int Internal ()
4658+ {
4659+ return -1;
4660+ }
4661+
4662+ private new float Private (float f)
4663+ {
4664+ return -f;
4665+ }
4666+ }
4667+
4668+ public class NoInheritance {
4669+ private new void Public ()
4670+ {
4671+ }
4672+
4673+ private new bool Protected (int x)
4674+ {
4675+ return x == 1;
4676+ }
4677+
4678+ private new int Internal ()
4679+ {
4680+ return -1;
4681+ }
4682+
4683+ private new float Private (float f)
4684+ {
4685+ return -f;
4686+ }
4687+ }
4688+
4689+ // c# cannot seal the method without making it an override
4690+ // and an override cannot change visibility
4691+#if false
4692+ public class FinalInheritor : Base {
4693+ private new sealed void Public ()
4694+ {
4695+ }
4696+
4697+ private new sealed bool Protected (int x)
4698+ {
4699+ return x == 1;
4700+ }
4701+
4702+ private new sealed int Internal ()
4703+ {
4704+ return -1;
4705+ }
4706+
4707+ private new float Private (float f)
4708+ {
4709+ return -f;
4710+ }
4711+ }
4712+#endif
4713+ public sealed class Sealed : Base {
4714+ private new void Public ()
4715+ {
4716+ }
4717+
4718+ private new bool Protected (int x)
4719+ {
4720+ return x == 1;
4721+ }
4722+
4723+ private new int Internal ()
4724+ {
4725+ return -1;
4726+ }
4727+
4728+ private new float Private (float f)
4729+ {
4730+ return -f;
4731+ }
4732+ }
4733+
4734+ public class StaticCtor {
4735+ static StaticCtor ()
4736+ {
4737+ }
4738+ }
4739+
4740+ public class StaticCtorInheritor : StaticCtor {
4741+ static StaticCtorInheritor ()
4742+ {
4743+ }
4744+ }
4745+ }
4746+
4747+ [Test]
4748+ public void DoesNotApply ()
4749+ {
4750+ // not private
4751+ AssertRuleDoesNotApply<TestCase.Base> ("Public");
4752+ AssertRuleDoesNotApply<TestCase.Base> ("Protected");
4753+ AssertRuleDoesNotApply<TestCase.Base> ("Internal");
4754+#if false
4755+ // method is sealed (final)
4756+ AssertRuleDoesNotApply<TestCase.FinalInheritor> ("Public");
4757+ AssertRuleDoesNotApply<TestCase.FinalInheritor> ("Protected");
4758+ AssertRuleDoesNotApply<TestCase.FinalInheritor> ("Internal");
4759+ AssertRuleDoesNotApply<TestCase.FinalInheritor> ("Private");
4760+#endif
4761+ // type is sealed
4762+ AssertRuleDoesNotApply<TestCase.Sealed> ("Public");
4763+ AssertRuleDoesNotApply<TestCase.Sealed> ("Protected");
4764+ AssertRuleDoesNotApply<TestCase.Sealed> ("Internal");
4765+ AssertRuleDoesNotApply<TestCase.Sealed> ("Private");
4766+ }
4767+
4768+ [Test]
4769+ public void Good ()
4770+ {
4771+ AssertRuleSuccess<TestCase.Base> ("Private");
4772+
4773+ AssertRuleSuccess<TestCase.NoInheritance> ("Public");
4774+ AssertRuleSuccess<TestCase.NoInheritance> ("Protected");
4775+ AssertRuleSuccess<TestCase.NoInheritance> ("Internal");
4776+ AssertRuleSuccess<TestCase.NoInheritance> ("Private");
4777+
4778+ AssertRuleSuccess<TestCase.BadInheritor> ("Internal");
4779+ AssertRuleSuccess<TestCase.BadInheritor> ("Private");
4780+
4781+ AssertRuleSuccess<TestCase.StaticCtor> (".cctor");
4782+ AssertRuleSuccess<TestCase.StaticCtorInheritor> (".cctor");
4783+ }
4784+
4785+ [Test]
4786+ public void Bad ()
4787+ {
4788+ AssertRuleFailure<TestCase.BadInheritor> ("Public");
4789+ AssertRuleFailure<TestCase.BadInheritor> ("Protected");
4790+ }
4791+ }
4792+}
4793diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Test/Tests.Rules.BadPractice.csproj b/gendarme/rules/Gendarme.Rules.BadPractice/Test/Tests.Rules.BadPractice.csproj
4794index 0693fa8..ec4cf33 100755
4795--- a/gendarme/rules/Gendarme.Rules.BadPractice/Test/Tests.Rules.BadPractice.csproj
4796+++ b/gendarme/rules/Gendarme.Rules.BadPractice/Test/Tests.Rules.BadPractice.csproj
4797@@ -1,5 +1,5 @@
4798 <?xml version="1.0" encoding="utf-8"?>\r
4799-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
4800+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
4801 <PropertyGroup>\r
4802 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
4803 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
4804@@ -10,8 +10,28 @@
4805 <AppDesignerFolder>Properties</AppDesignerFolder>\r
4806 <RootNamespace>Tests.Rules.BadPractice</RootNamespace>\r
4807 <AssemblyName>Tests.Rules.BadPractice</AssemblyName>\r
4808- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
4809+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
4810 <FileAlignment>512</FileAlignment>\r
4811+ <FileUpgradeFlags>\r
4812+ </FileUpgradeFlags>\r
4813+ <OldToolsVersion>3.5</OldToolsVersion>\r
4814+ <UpgradeBackupLocation />\r
4815+ <PublishUrl>publish\</PublishUrl>\r
4816+ <Install>true</Install>\r
4817+ <InstallFrom>Disk</InstallFrom>\r
4818+ <UpdateEnabled>false</UpdateEnabled>\r
4819+ <UpdateMode>Foreground</UpdateMode>\r
4820+ <UpdateInterval>7</UpdateInterval>\r
4821+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
4822+ <UpdatePeriodically>false</UpdatePeriodically>\r
4823+ <UpdateRequired>false</UpdateRequired>\r
4824+ <MapFileExtensions>true</MapFileExtensions>\r
4825+ <ApplicationRevision>0</ApplicationRevision>\r
4826+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
4827+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
4828+ <UseApplicationTrust>false</UseApplicationTrust>\r
4829+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
4830+ <TargetFrameworkProfile />\r
4831 </PropertyGroup>\r
4832 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
4833 <DebugSymbols>true</DebugSymbols>\r
4834@@ -21,6 +41,7 @@
4835 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
4836 <ErrorReport>prompt</ErrorReport>\r
4837 <WarningLevel>4</WarningLevel>\r
4838+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
4839 </PropertyGroup>\r
4840 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
4841 <DebugType>pdbonly</DebugType>\r
4842@@ -29,6 +50,7 @@
4843 <DefineConstants>TRACE</DefineConstants>\r
4844 <ErrorReport>prompt</ErrorReport>\r
4845 <WarningLevel>4</WarningLevel>\r
4846+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
4847 </PropertyGroup>\r
4848 <ItemGroup>\r
4849 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
4850@@ -85,6 +107,23 @@
4851 <ItemGroup>\r
4852 <Folder Include="Properties\" />\r
4853 </ItemGroup>\r
4854+ <ItemGroup>\r
4855+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
4856+ <Visible>False</Visible>\r
4857+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
4858+ <Install>false</Install>\r
4859+ </BootstrapperPackage>\r
4860+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
4861+ <Visible>False</Visible>\r
4862+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
4863+ <Install>true</Install>\r
4864+ </BootstrapperPackage>\r
4865+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
4866+ <Visible>False</Visible>\r
4867+ <ProductName>Windows Installer 3.1</ProductName>\r
4868+ <Install>true</Install>\r
4869+ </BootstrapperPackage>\r
4870+ </ItemGroup>\r
4871 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
4872 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
4873 Other similar extension points exist, see Microsoft.Common.targets.
4874diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/UseFileOpenOnlyWithFileAccessRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/UseFileOpenOnlyWithFileAccessRule.cs
4875index 655298f..2c8be6f 100644
4876--- a/gendarme/rules/Gendarme.Rules.BadPractice/UseFileOpenOnlyWithFileAccessRule.cs
4877+++ b/gendarme/rules/Gendarme.Rules.BadPractice/UseFileOpenOnlyWithFileAccessRule.cs
4878@@ -26,6 +26,7 @@
4879
4880 using System;
4881 using System.Collections.Generic;
4882+using System.Globalization;
4883
4884 using Mono.Cecil;
4885 using Mono.Cecil.Cil;
4886@@ -68,9 +69,19 @@ namespace Gendarme.Rules.BadPractice {
4887 [EngineDependency (typeof (OpCodeEngine))]
4888 public class UseFileOpenOnlyWithFileAccessRule : Rule, IMethodRule {
4889
4890- const string fileMode = "System.IO.FileMode";
4891- const string fileAccess = "System.IO.FileAccess";
4892- const string fileSystemRights = "System.Security.AccessControl.FileSystemRights";
4893+ public override void Initialize (IRunner runner)
4894+ {
4895+ base.Initialize (runner);
4896+
4897+ // if the module does not reference System.IO.FileMode
4898+ // then no code inside the module will be using it
4899+ Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
4900+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
4901+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
4902+ return tr.IsNamed ("System.IO", "FileMode");
4903+ }));
4904+ };
4905+ }
4906
4907 // System.IO.File::Open
4908 // System.IO.FileInfo::Open
4909@@ -115,16 +126,17 @@ namespace Gendarme.Rules.BadPractice {
4910 bool foundFileMode = false;
4911 bool foundFileAccess = false;
4912 foreach (ParameterDefinition parameter in m.Parameters) {
4913- string ptname = parameter.ParameterType.FullName;
4914- if (!foundFileMode && ptname == fileMode)
4915+ TypeReference ptype = parameter.ParameterType;
4916+ if (!foundFileMode && ptype.IsNamed ("System.IO", "FileMode"))
4917 foundFileMode = true;
4918- if (!foundFileAccess && (ptname == fileAccess || ptname == fileSystemRights))
4919+ if (!foundFileAccess && (ptype.IsNamed ("System.IO", "FileAccess") || ptype.IsNamed ("System.Security.AccessControl", "FileSystemRights")))
4920 foundFileAccess = true;
4921 }
4922 if (foundFileMode && !foundFileAccess) {
4923- Runner.Report (method, instruction, Severity.Medium, Confidence.Normal,
4924- String.Format("{0}::{1} being called with FileMode parameter but without FileAccess.",
4925- m.DeclaringType.FullName, m.Name));
4926+ string msg = String.Format (CultureInfo.InvariantCulture,
4927+ "{0}::{1} being called with FileMode parameter but without FileAccess.",
4928+ m.DeclaringType.GetFullName (), m.Name);
4929+ Runner.Report (method, instruction, Severity.Medium, Confidence.Normal, msg);
4930 }
4931 }
4932 return Runner.CurrentRuleResult;
4933diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DecorateThreadsRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DecorateThreadsRule.cs
4934index feead4a..c7b243a 100644
4935--- a/gendarme/rules/Gendarme.Rules.Concurrency/DecorateThreadsRule.cs
4936+++ b/gendarme/rules/Gendarme.Rules.Concurrency/DecorateThreadsRule.cs
4937@@ -37,6 +37,7 @@ using System.Collections;
4938 using System.Collections.Generic;
4939 using System.Collections.ObjectModel;
4940 using System.Diagnostics;
4941+using System.Globalization;
4942 using System.Linq;
4943
4944 namespace Gendarme.Rules.Concurrency {
4945@@ -268,7 +269,8 @@ namespace Gendarme.Rules.Concurrency {
4946 if (delegateType != null && !ThreadRocks.ThreadedNamespace (delegateType.Namespace)) {
4947 ThreadModel delegateModel = delegateType.ThreadingModel ();
4948 if (model != delegateModel && !delegateModel.AllowsEveryCaller ()) {
4949- string mesg = string.Format ("{0} event must match {1} delegate.", model, delegateModel);
4950+ string mesg = String.Format (CultureInfo.InvariantCulture,
4951+ "{0} event must match {1} delegate.", model, delegateModel);
4952 ReportDefect (method, Severity.High, Confidence.High, mesg);
4953 }
4954 }
4955@@ -281,15 +283,17 @@ namespace Gendarme.Rules.Concurrency {
4956 bool new_slot = method.IsNewSlot;
4957 superTypes = from s in superTypes where (s.IsInterface == new_slot) select s;
4958 string [] parameters = pdc != null
4959- ? (from p in pdc.Cast<ParameterDefinition> () select p.ParameterType.FullName).ToArray ()
4960+ ? (from p in pdc.Cast<ParameterDefinition> () select p.ParameterType.GetFullName ()).ToArray ()
4961 : null;
4962
4963+ string return_type_name = method.ReturnType.GetFullName ();
4964 foreach (TypeDefinition type in superTypes) {
4965- MethodDefinition superMethod = type.GetMethod (name, method.ReturnType.FullName, parameters);
4966+ MethodDefinition superMethod = type.GetMethod (name, return_type_name, parameters);
4967 if (superMethod != null && !ThreadRocks.ThreadedNamespace (superMethod.DeclaringType.Namespace)) {
4968 ThreadModel superModel = superMethod.ThreadingModel ();
4969 if (model != superModel) {
4970- string mesg = string.Format ("{0} {1} must match {2} {3} method.", model, name, superModel,
4971+ string mesg = String.Format (CultureInfo.InvariantCulture,
4972+ "{0} {1} must match {2} {3} method.", model, name, superModel,
4973 new_slot ? "interface" : "base");
4974 ReportDefect (method, Severity.High, Confidence.High, mesg);
4975 }
4976@@ -299,7 +303,7 @@ namespace Gendarme.Rules.Concurrency {
4977
4978 // Serializable cannot be applied to static methods, but can be applied to
4979 // operators because they're just sugar for normal calls.
4980- if (method.IsStatic && model.Is (ThreadModel.Serializable) && !name.StartsWith ("op_")) {
4981+ if (method.IsStatic && model.Is (ThreadModel.Serializable) && !name.StartsWith ("op_", StringComparison.Ordinal)) {
4982 string mesg = "Static members cannot be decorated with Serializable.";
4983 ReportDefect (method, Severity.High, Confidence.High, mesg);
4984 }
4985@@ -315,21 +319,23 @@ namespace Gendarme.Rules.Concurrency {
4986 foreach (MethodDefinition caller in anonymous_entry_points) {
4987 foreach (Instruction ins in caller.Body.Instructions) {
4988 switch (ins.OpCode.Code) {
4989- case Code.Call:
4990- case Code.Callvirt:
4991- MethodDefinition target = ((MethodReference) ins.Operand).Resolve ();
4992- if (target != null) {
4993- ThreadModel targetModel = target.ThreadingModel ();
4994- if (targetModel == ThreadModel.MainThread) {
4995- string mesg = string.Format ("An anonymous thread entry point cannot call MainThread {0}.", target.Name);
4996-
4997- ++DefectCount;
4998- Log.WriteLine (this, "Defect: {0}", mesg);
4999- Defect defect = new Defect (this, caller, caller, ins, Severity.High, Confidence.High, mesg);
5000- Runner.Report (defect);
5001- }
5002+ case Code.Call:
5003+ case Code.Callvirt:
5004+ MethodDefinition target = ((MethodReference) ins.Operand).Resolve ();
5005+ if (target != null) {
5006+ ThreadModel targetModel = target.ThreadingModel ();
5007+ if (targetModel == ThreadModel.MainThread) {
5008+ string mesg = String.Format (CultureInfo.InvariantCulture,
5009+ "An anonymous thread entry point cannot call MainThread {0}.",
5010+ target.Name);
5011+
5012+ ++DefectCount;
5013+ Log.WriteLine (this, "Defect: {0}", mesg);
5014+ Defect defect = new Defect (this, caller, caller, ins, Severity.High, Confidence.High, mesg);
5015+ Runner.Report (defect);
5016 }
5017- break;
5018+ }
5019+ break;
5020 }
5021 }
5022 }
5023@@ -385,8 +391,9 @@ namespace Gendarme.Rules.Concurrency {
5024 if (!target.IsGeneratedCode () || target.IsProperty ()) {
5025 ThreadModel targetModel = target.ThreadingModel ();
5026 if (!IsValidCall (callerModel, targetModel)) {
5027- string mesg = string.Format ("{0} delegate cannot be bound to {1} {2} method.", callerModel, targetModel, target.Name);
5028-
5029+ string mesg = String.Format (CultureInfo.InvariantCulture,
5030+ "{0} delegate cannot be bound to {1} {2} method.",
5031+ callerModel, targetModel, target.Name);
5032 ++DefectCount;
5033 Log.WriteLine (this, "Defect: {0}", mesg);
5034 Defect defect = new Defect (this, method, method, ins, Severity.High, Confidence.High, mesg);
5035@@ -431,7 +438,7 @@ namespace Gendarme.Rules.Concurrency {
5036 methods.AddIfNew ((MethodReference) ins.Previous.Previous.Operand);
5037
5038 // Misc threaded events.
5039- } else if (call_type.FullName == "System.ComponentModel.BackgroundWorker") {
5040+ } else if (call_type.IsNamed ("System.ComponentModel", "BackgroundWorker")) {
5041 if (call.Name == "add_DoWork") {
5042 candidate = (MethodReference) ins.Previous.Previous.Operand;
5043 }
5044@@ -465,7 +472,9 @@ namespace Gendarme.Rules.Concurrency {
5045 if (target != null) {
5046 ThreadModel targetModel = target.ThreadingModel ();
5047 if (!IsValidCall (method_model.Value, targetModel)) {
5048- string mesg = string.Format ("{0} {1} cannot be bound to {2} {3} method.", method_model, entry.Key, targetModel, target.Name);
5049+ string mesg = String.Format (CultureInfo.InvariantCulture,
5050+ "{0} {1} cannot be bound to {2} {3} method.",
5051+ method_model, entry.Key, targetModel, target.Name);
5052 ReportDefect (method, Severity.High, Confidence.High, mesg);
5053 }
5054 }
5055@@ -490,9 +499,8 @@ namespace Gendarme.Rules.Concurrency {
5056 // but mono doesn't.
5057 case "add_ErrorDataReceived":
5058 case "add_OutputDataReceived":
5059- TypeReference type = method.DeclaringType;
5060- if (type.Name == "Process")
5061- return (type.Namespace == "System.Diagnostics");
5062+ if (method.DeclaringType.IsNamed ("System.Diagnostics", "Process"))
5063+ return true;
5064 break;
5065 }
5066 return false;
5067@@ -523,7 +531,8 @@ namespace Gendarme.Rules.Concurrency {
5068 anonymous_entry_points.Add (method);
5069
5070 } else if (model == ThreadModel.MainThread) {
5071- string mesg = string.Format ("{0} is a thread entry point and so cannot be MainThread.", method.Name);
5072+ string mesg = String.Format (CultureInfo.InvariantCulture,
5073+ "{0} is a thread entry point and so cannot be MainThread.", method.Name);
5074 ReportDefect (method, Severity.High, Confidence.High, mesg);
5075 }
5076 }
5077@@ -537,7 +546,8 @@ namespace Gendarme.Rules.Concurrency {
5078 ThreadModel callerModel = caller.ThreadingModel ();
5079 ThreadModel targetModel = target.ThreadingModel ();
5080 if (!IsValidCall (callerModel, targetModel)) {
5081- string mesg = string.Format ("{0} {1} cannot call {2} {3}.", callerModel, caller.Name, targetModel, target.Name);
5082+ string mesg = String.Format (CultureInfo.InvariantCulture, "{0} {1} cannot call {2} {3}.",
5083+ callerModel, caller.Name, targetModel, target.Name);
5084
5085 ++DefectCount;
5086 Log.WriteLine (this, "Defect: {0}", mesg);
5087diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnThisOrTypesRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnThisOrTypesRule.cs
5088index 2ddb7ac..7c91ad5 100644
5089--- a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnThisOrTypesRule.cs
5090+++ b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnThisOrTypesRule.cs
5091@@ -27,6 +27,7 @@
5092 //
5093
5094 using System;
5095+using System.Globalization;
5096
5097 using Mono.Cecil;
5098 using Mono.Cecil.Cil;
5099@@ -108,23 +109,26 @@ namespace Gendarme.Rules.Concurrency {
5100
5101 switch (ins.OpCode.Code) {
5102 case Code.Ldarg_0:
5103- msg = LockThis;
5104+ if (!method.IsStatic)
5105+ msg = LockThis;
5106 break;
5107 case Code.Ldarg:
5108 case Code.Ldarg_S:
5109- ParameterDefinition pd = (ins.Operand as ParameterDefinition);
5110- if ((pd == null) || (pd.GetSequence () != 0))
5111- msg = LockThis;
5112+ if (!method.IsStatic) {
5113+ ParameterDefinition pd = (ins.Operand as ParameterDefinition);
5114+ if ((pd == null) || (pd.Index == 0))
5115+ msg = LockThis;
5116+ }
5117 break;
5118 case Code.Call:
5119 case Code.Callvirt:
5120 MethodReference mr = (ins.Operand as MethodReference);
5121- if (mr.ReturnType.FullName != "System.Type")
5122+ if (!mr.ReturnType.IsNamed ("System", "Type"))
5123 return String.Empty;
5124
5125 if ((mr.Name == "GetTypeFromHandle") && (mr.DeclaringType.Name == "Type")) {
5126 // ldtoken
5127- msg = String.Format (LockType, (ins.Previous.Operand as TypeReference).Name);
5128+ msg = String.Format (CultureInfo.InvariantCulture, LockType, (ins.Previous.Operand as TypeReference).Name);
5129 } else {
5130 msg = mr.ToString ();
5131 }
5132diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnWeakIdentityObjectsRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnWeakIdentityObjectsRule.cs
5133index fe730aa..57c3b84 100644
5134--- a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnWeakIdentityObjectsRule.cs
5135+++ b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnWeakIdentityObjectsRule.cs
5136@@ -27,6 +27,7 @@
5137 //
5138
5139 using System;
5140+using System.Globalization;
5141
5142 using Mono.Cecil;
5143 using Mono.Cecil.Cil;
5144@@ -99,12 +100,26 @@ namespace Gendarme.Rules.Concurrency {
5145 [FxCopCompatibility ("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity")]
5146 public class DoNotLockOnWeakIdentityObjectsRule : LockAnalyzerRule {
5147
5148- private static string [] unsealed_types = new string[] {
5149- "System.MarshalByRefObject",
5150- "System.OutOfMemoryException",
5151- "System.Reflection.MemberInfo",
5152- "System.Reflection.ParameterInfo"
5153- };
5154+ static bool IsWeakSealedType (TypeReference type)
5155+ {
5156+ switch (type.Namespace) {
5157+ case "System":
5158+ string name = type.Name;
5159+ return ((name == "String") || (name == "ExecutionEngineException") || (name == "StackOverflowException"));
5160+ case "System.Threading":
5161+ return (type.Name == "Thread");
5162+ default:
5163+ return false;
5164+ }
5165+ }
5166+
5167+ static string InheritFromWeakType (TypeReference type, string nameSpace, string name)
5168+ {
5169+ if (!type.Inherits (nameSpace, name))
5170+ return String.Empty;
5171+ return String.Format (CultureInfo.InvariantCulture, "'{0}' inherits from '{1}.{2}'.",
5172+ type.GetFullName (), nameSpace, name);
5173+ }
5174
5175 public override void Analyze (MethodDefinition method, MethodReference enter, Instruction ins)
5176 {
5177@@ -119,7 +134,7 @@ namespace Gendarme.Rules.Concurrency {
5178 if (first.OpCode.Code == Code.Dup)
5179 first = first.Previous;
5180 type = first.GetOperandType (method);
5181- if (type.FullName == "System.Object") {
5182+ if (type.IsNamed ("System", "Object")) {
5183 // newer GMCS use a temporary local that hides the real type
5184 Instruction prev = first.Previous;
5185 if (first.IsLoadLocal () && prev.IsStoreLocal ()) {
5186@@ -131,24 +146,28 @@ namespace Gendarme.Rules.Concurrency {
5187 if (type == null)
5188 return;
5189
5190- // fast check for sealed types
5191- string full_name = type.FullName;
5192- switch (full_name) {
5193- case "System.ExecutionEngineException":
5194- case "System.StackOverflowException":
5195- case "System.String":
5196- case "System.Threading.Thread":
5197- Runner.Report (method, call, Severity.High, Confidence.Normal, full_name);
5198- break;
5199- default:
5200- foreach (string unsealed in unsealed_types) {
5201- if (!type.Inherits (unsealed))
5202- continue;
5203-
5204- string msg = String.Format ("'{0}' inherits from '{1}'.", full_name, unsealed);
5205+ if (IsWeakSealedType (type)) {
5206+ Runner.Report (method, call, Severity.High, Confidence.Normal, type.GetFullName ());
5207+ } else {
5208+ string msg = InheritFromWeakType (type, "System", "MarshalByRefObject");
5209+ if (msg.Length > 0) {
5210+ Runner.Report (method, call, Severity.High, Confidence.Normal, msg);
5211+ return;
5212+ }
5213+ msg = InheritFromWeakType (type, "System", "OutOfMemoryException");
5214+ if (msg.Length > 0) {
5215+ Runner.Report (method, call, Severity.High, Confidence.Normal, msg);
5216+ return;
5217+ }
5218+ msg = InheritFromWeakType (type, "System.Reflection", "MemberInfo");
5219+ if (msg.Length > 0) {
5220+ Runner.Report (method, call, Severity.High, Confidence.Normal, msg);
5221+ return;
5222+ }
5223+ msg = InheritFromWeakType (type, "System.Reflection", "ParameterInfo");
5224+ if (msg.Length > 0) {
5225 Runner.Report (method, call, Severity.High, Confidence.Normal, msg);
5226 }
5227- break;
5228 }
5229 }
5230 }
5231diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotUseThreadStaticWithInstanceFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotUseThreadStaticWithInstanceFieldsRule.cs
5232index af1beeb..c949329 100644
5233--- a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotUseThreadStaticWithInstanceFieldsRule.cs
5234+++ b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotUseThreadStaticWithInstanceFieldsRule.cs
5235@@ -84,15 +84,13 @@ namespace Gendarme.Rules.Concurrency {
5236 [Solution ("ThreadStaticAttribute will only make static fields thread safe. To make an instance field thread safe you need to use techniques like locking or System.Threading.Thread.Thread::AllocateNamedDataSlot.")]
5237 public sealed class DoNotUseThreadStaticWithInstanceFieldsRule : Rule, ITypeRule {
5238
5239- private const string ThreadStaticAttribute = "System.ThreadStaticAttribute";
5240-
5241 public RuleResult CheckType (TypeDefinition type)
5242 {
5243 if (!type.HasFields || type.IsEnum)
5244 return RuleResult.DoesNotApply;
5245
5246 foreach (FieldDefinition field in type.Fields) {
5247- if (!field.IsStatic && field.CustomAttributes.ContainsType (ThreadStaticAttribute)) {
5248+ if (!field.IsStatic && field.HasAttribute ("System", "ThreadStaticAttribute")) {
5249 Runner.Report (field, Severity.Critical, Confidence.Total);
5250 }
5251 }
5252diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DontUseLockedRegionOutsideMethodRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DontUseLockedRegionOutsideMethodRule.cs
5253index 9b2a53b..4cc40d6 100644
5254--- a/gendarme/rules/Gendarme.Rules.Concurrency/DontUseLockedRegionOutsideMethodRule.cs
5255+++ b/gendarme/rules/Gendarme.Rules.Concurrency/DontUseLockedRegionOutsideMethodRule.cs
5256@@ -100,7 +100,8 @@ namespace Gendarme.Rules.Concurrency {
5257 /// Monitor.Enter (mutex);
5258 /// try {
5259 /// producer++;
5260- /// } finally {
5261+ /// }
5262+ /// finally {
5263 /// Monitor.Exit (mutex);
5264 /// }
5265 /// }
5266@@ -131,8 +132,10 @@ namespace Gendarme.Rules.Concurrency {
5267 // if not then this rule does not need to be executed for the module
5268 // note: mscorlib.dll is an exception since it defines, not refer, System.Threading.Monitor
5269 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
5270- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
5271- e.CurrentModule.HasTypeReference ("System.Threading.Monitor");
5272+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
5273+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
5274+ return tr.IsNamed ("System.Threading", "Monitor");
5275+ }));
5276 };
5277 }
5278
5279@@ -157,9 +160,9 @@ namespace Gendarme.Rules.Concurrency {
5280 if (m == null)
5281 continue;
5282
5283- if (IsMonitorMethod (m, "Enter")) {
5284+ if (m.IsNamed ("System.Threading", "Monitor", "Enter")) {
5285 enter++;
5286- } else if (IsMonitorMethod (m, "Exit")) {
5287+ } else if (m.IsNamed ("System.Threading", "Monitor", "Exit")) {
5288 exit++;
5289 }
5290 }
5291@@ -170,13 +173,5 @@ namespace Gendarme.Rules.Concurrency {
5292 Runner.Report (method, Severity.High, Confidence.Normal);
5293 return RuleResult.Failure;
5294 }
5295-
5296- //FIXME: copied from DoubleCheckLockingRule, we need to share this
5297- private static bool IsMonitorMethod (MemberReference method, string methodName)
5298- {
5299- if (method.Name != methodName)
5300- return false;
5301- return (method.DeclaringType.FullName == "System.Threading.Monitor");
5302- }
5303 }
5304 }
5305diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DoubleCheckLockingRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DoubleCheckLockingRule.cs
5306index 8595046..d1227a2 100644
5307--- a/gendarme/rules/Gendarme.Rules.Concurrency/DoubleCheckLockingRule.cs
5308+++ b/gendarme/rules/Gendarme.Rules.Concurrency/DoubleCheckLockingRule.cs
5309@@ -154,7 +154,9 @@ namespace Gendarme.Rules.Concurrency {
5310 // if not then this rule does not need to be executed for the module
5311 // note: mscorlib.dll is an exception since it defines, not refer, System.Threading.Monitor
5312 (e.CurrentAssembly.Name.Name == "mscorlib" ||
5313- e.CurrentModule.HasTypeReference ("System.Threading.Monitor"));
5314+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
5315+ return tr.IsNamed ("System.Threading", "Monitor");
5316+ }));
5317 };
5318 }
5319
5320@@ -213,7 +215,7 @@ namespace Gendarme.Rules.Concurrency {
5321 {
5322 if (method.Name != methodName)
5323 return false;
5324- if (method.DeclaringType.FullName != "System.Threading.Monitor")
5325+ if (!method.DeclaringType.IsNamed ("System.Threading", "Monitor"))
5326 return false;
5327 // exclude Monitor.Enter(object, ref bool) since the comparison would be made
5328 // againt the 'lockTaken' parameter and would report failures for every cases.
5329diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/Gendarme.Rules.Concurrency.csproj b/gendarme/rules/Gendarme.Rules.Concurrency/Gendarme.Rules.Concurrency.csproj
5330index 8224fee..e9f89be 100644
5331--- a/gendarme/rules/Gendarme.Rules.Concurrency/Gendarme.Rules.Concurrency.csproj
5332+++ b/gendarme/rules/Gendarme.Rules.Concurrency/Gendarme.Rules.Concurrency.csproj
5333@@ -1,5 +1,5 @@
5334 <?xml version="1.0" encoding="utf-8"?>\r
5335-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
5336+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
5337 <PropertyGroup>\r
5338 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
5339 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
5340@@ -12,9 +12,11 @@
5341 <AssemblyName>Gendarme.Rules.Concurrency</AssemblyName>\r
5342 <FileUpgradeFlags>\r
5343 </FileUpgradeFlags>\r
5344- <OldToolsVersion>2.0</OldToolsVersion>\r
5345+ <OldToolsVersion>3.5</OldToolsVersion>\r
5346 <UpgradeBackupLocation>\r
5347 </UpgradeBackupLocation>\r
5348+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
5349+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
5350 <PublishUrl>http://localhost/Gendarme.Rules.Concurrency/</PublishUrl>\r
5351 <Install>true</Install>\r
5352 <InstallFrom>Web</InstallFrom>\r
5353@@ -27,10 +29,9 @@
5354 <MapFileExtensions>true</MapFileExtensions>\r
5355 <ApplicationRevision>0</ApplicationRevision>\r
5356 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
5357- <IsWebBootstrapper>true</IsWebBootstrapper>\r
5358 <UseApplicationTrust>false</UseApplicationTrust>\r
5359 <BootstrapperEnabled>true</BootstrapperEnabled>\r
5360- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
5361+ <TargetFrameworkProfile />\r
5362 </PropertyGroup>\r
5363 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
5364 <DebugSymbols>true</DebugSymbols>\r
5365@@ -43,6 +44,7 @@
5366 <NoWarn>1591</NoWarn>\r
5367 <WarningsAsErrors>1570</WarningsAsErrors>\r
5368 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Concurrency.xml</DocumentationFile>\r
5369+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
5370 </PropertyGroup>\r
5371 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
5372 <DebugType>pdbonly</DebugType>\r
5373@@ -54,6 +56,7 @@
5374 <NoWarn>1591</NoWarn>\r
5375 <WarningsAsErrors>1570</WarningsAsErrors>\r
5376 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Concurrency.xml</DocumentationFile>\r
5377+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
5378 </PropertyGroup>\r
5379 <ItemGroup>\r
5380 <Reference Include="System" />\r
5381@@ -93,14 +96,33 @@
5382 <None Include="ChangeLog" />\r
5383 </ItemGroup>\r
5384 <ItemGroup>\r
5385+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
5386+ <Visible>False</Visible>\r
5387+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
5388+ <Install>false</Install>\r
5389+ </BootstrapperPackage>\r
5390 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
5391 <Visible>False</Visible>\r
5392+ <ProductName>\r
5393+ </ProductName>\r
5394+ <Install>false</Install>\r
5395 </BootstrapperPackage>\r
5396 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
5397 <Visible>False</Visible>\r
5398+ <ProductName>\r
5399+ </ProductName>\r
5400+ <Install>false</Install>\r
5401 </BootstrapperPackage>\r
5402 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
5403 <Visible>False</Visible>\r
5404+ <ProductName>\r
5405+ </ProductName>\r
5406+ <Install>false</Install>\r
5407+ </BootstrapperPackage>\r
5408+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
5409+ <Visible>False</Visible>\r
5410+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
5411+ <Install>false</Install>\r
5412 </BootstrapperPackage>\r
5413 </ItemGroup>\r
5414 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
5415diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/LockAnalyzerRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/LockAnalyzerRule.cs
5416index 04424af..fd7bc61 100644
5417--- a/gendarme/rules/Gendarme.Rules.Concurrency/LockAnalyzerRule.cs
5418+++ b/gendarme/rules/Gendarme.Rules.Concurrency/LockAnalyzerRule.cs
5419@@ -49,8 +49,10 @@ namespace Gendarme.Rules.Concurrency {
5420 // if not then this rule does not need to be executed for the module
5421 // note: mscorlib.dll is an exception since it defines, not refer, System.Threading.Monitor
5422 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
5423- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
5424- e.CurrentModule.HasTypeReference ("System.Threading.Monitor");
5425+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
5426+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
5427+ return tr.IsNamed ("System.Threading", "Monitor");
5428+ }));
5429 };
5430 }
5431
5432@@ -68,14 +70,8 @@ namespace Gendarme.Rules.Concurrency {
5433
5434 foreach (Instruction ins in method.Body.Instructions) {
5435 MethodReference mr = ins.GetMethod ();
5436- if (mr == null)
5437- continue;
5438- if (mr.DeclaringType.FullName != "System.Threading.Monitor")
5439- continue;
5440- if (mr.Name != "Enter")
5441- continue;
5442-
5443- Analyze (method, mr, ins);
5444+ if (mr.IsNamed ("System.Threading", "Monitor", "Enter"))
5445+ Analyze (method, mr, ins);
5446 }
5447 return Runner.CurrentRuleResult;
5448 }
5449diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/ProtectCallToEventDelegatesRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/ProtectCallToEventDelegatesRule.cs
5450index e614973..843c9b8 100644
5451--- a/gendarme/rules/Gendarme.Rules.Concurrency/ProtectCallToEventDelegatesRule.cs
5452+++ b/gendarme/rules/Gendarme.Rules.Concurrency/ProtectCallToEventDelegatesRule.cs
5453@@ -27,6 +27,7 @@
5454 //
5455
5456 using System;
5457+using System.Globalization;
5458
5459 using Mono.Cecil;
5460 using Mono.Cecil.Cil;
5461@@ -164,13 +165,13 @@ namespace Gendarme.Rules.Concurrency {
5462 Instruction caller = ins.TraceBack (method);
5463 FieldDefinition field = caller.GetField ();
5464 if (field != null) {
5465- string msg = String.Format ("Possible race condition since field '{0}' is accessed directly.", field.Name);
5466+ string msg = String.Format (CultureInfo.InvariantCulture, "Possible race condition since field '{0}' is accessed directly.", field.Name);
5467 Runner.Report (method, ins, Severity.High, Confidence.High, msg);
5468 } else {
5469 // look for the variable, if it's not then stop analysis
5470 VariableDefinition load = caller.GetVariable (method);
5471 if ((load != null) && !CheckVariable (method, caller, load)) {
5472- string msg = String.Format ("Variable '{0}' does not seems to be checked against null.", load.Name);
5473+ string msg = String.Format (CultureInfo.InvariantCulture, "Variable '{0}' does not seems to be checked against null.", load.Name);
5474 Runner.Report (method, ins, Severity.High, Confidence.Normal, msg);
5475 }
5476 }
5477diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/README.md b/gendarme/rules/Gendarme.Rules.Concurrency/README.md
5478new file mode 100644
5479index 0000000..3da4dc8
5480--- /dev/null
5481+++ b/gendarme/rules/Gendarme.Rules.Concurrency/README.md
5482@@ -0,0 +1,9 @@
5483+# Gendarme.Rules.Concurrency Rules
5484+
5485+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Concurrency(git)]] pages.
5486+
5487+
5488+## Feedback
5489+
5490+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
5491+
5492diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/ReviewLockUsedOnlyForOperationsOnVariablesRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/ReviewLockUsedOnlyForOperationsOnVariablesRule.cs
5493index af249bd..621e362 100644
5494--- a/gendarme/rules/Gendarme.Rules.Concurrency/ReviewLockUsedOnlyForOperationsOnVariablesRule.cs
5495+++ b/gendarme/rules/Gendarme.Rules.Concurrency/ReviewLockUsedOnlyForOperationsOnVariablesRule.cs
5496@@ -93,8 +93,10 @@ namespace Gendarme.Rules.Concurrency {
5497 // if not then this rule does not need to be executed for the module
5498 // note: mscorlib.dll is an exception since it defines, not refer, System.Threading.Monitor
5499 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
5500- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
5501- e.CurrentModule.HasTypeReference ("System.Threading.Monitor");
5502+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
5503+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
5504+ return tr.IsNamed ("System.Threading", "Monitor");
5505+ }));
5506 };
5507 }
5508
5509@@ -154,9 +156,7 @@ namespace Gendarme.Rules.Concurrency {
5510 return false;
5511
5512 MethodReference method = (ins.Operand as MethodReference);
5513- if (method == null)
5514- return false;
5515- if ((method.Name != "Enter") || (method.DeclaringType.FullName != "System.Threading.Monitor"))
5516+ if (!method.IsNamed ("System.Threading", "Monitor", "Enter"))
5517 return false;
5518 return (parametersCount == method.Parameters.Count);
5519 }
5520diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/Test/DoNotLockOnThisOrTypesTest.cs b/gendarme/rules/Gendarme.Rules.Concurrency/Test/DoNotLockOnThisOrTypesTest.cs
5521index 707a537..4db0096 100644
5522--- a/gendarme/rules/Gendarme.Rules.Concurrency/Test/DoNotLockOnThisOrTypesTest.cs
5523+++ b/gendarme/rules/Gendarme.Rules.Concurrency/Test/DoNotLockOnThisOrTypesTest.cs
5524@@ -103,11 +103,20 @@ namespace Test.Rules.Concurrency {
5525 }
5526 }
5527
5528+ static bool TryEnter (object obj)
5529+ {
5530+ lock (obj) {
5531+ Console.WriteLine ();
5532+ }
5533+ return true;
5534+ }
5535+
5536 [Test]
5537 public void StaticType ()
5538 {
5539 AssertRuleFailure<DoNotLockOnThisOrTypesTest> ("StaticLockType", 1);
5540 AssertRuleFailure<DoNotLockOnThisOrTypesTest> ("StaticLockTypes", 2);
5541+ AssertRuleSuccess<DoNotLockOnThisOrTypesTest> ("TryEnter");
5542 }
5543
5544 object instance_locker = new object ();
5545diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/Test/Tests.Rules.Concurrency.csproj b/gendarme/rules/Gendarme.Rules.Concurrency/Test/Tests.Rules.Concurrency.csproj
5546index e272dcc..292cdd3 100755
5547--- a/gendarme/rules/Gendarme.Rules.Concurrency/Test/Tests.Rules.Concurrency.csproj
5548+++ b/gendarme/rules/Gendarme.Rules.Concurrency/Test/Tests.Rules.Concurrency.csproj
5549@@ -1,5 +1,5 @@
5550 <?xml version="1.0" encoding="utf-8"?>\r
5551-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
5552+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
5553 <PropertyGroup>\r
5554 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
5555 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
5556@@ -12,9 +12,11 @@
5557 <AssemblyName>Tests.Rules.Concurrency</AssemblyName>\r
5558 <FileUpgradeFlags>\r
5559 </FileUpgradeFlags>\r
5560- <OldToolsVersion>2.0</OldToolsVersion>\r
5561+ <OldToolsVersion>3.5</OldToolsVersion>\r
5562 <UpgradeBackupLocation>\r
5563 </UpgradeBackupLocation>\r
5564+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
5565+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
5566 <PublishUrl>http://localhost/Tests.Rules.Concurrency/</PublishUrl>\r
5567 <Install>true</Install>\r
5568 <InstallFrom>Web</InstallFrom>\r
5569@@ -27,10 +29,9 @@
5570 <MapFileExtensions>true</MapFileExtensions>\r
5571 <ApplicationRevision>0</ApplicationRevision>\r
5572 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
5573- <IsWebBootstrapper>true</IsWebBootstrapper>\r
5574 <UseApplicationTrust>false</UseApplicationTrust>\r
5575 <BootstrapperEnabled>true</BootstrapperEnabled>\r
5576- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
5577+ <TargetFrameworkProfile />\r
5578 </PropertyGroup>\r
5579 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
5580 <DebugSymbols>true</DebugSymbols>\r
5581@@ -40,6 +41,7 @@
5582 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
5583 <ErrorReport>prompt</ErrorReport>\r
5584 <WarningLevel>4</WarningLevel>\r
5585+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
5586 </PropertyGroup>\r
5587 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
5588 <DebugType>pdbonly</DebugType>\r
5589@@ -48,6 +50,7 @@
5590 <DefineConstants>TRACE</DefineConstants>\r
5591 <ErrorReport>prompt</ErrorReport>\r
5592 <WarningLevel>4</WarningLevel>\r
5593+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
5594 </PropertyGroup>\r
5595 <ItemGroup>\r
5596 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
5597@@ -93,14 +96,33 @@
5598 </ProjectReference>\r
5599 </ItemGroup>\r
5600 <ItemGroup>\r
5601+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
5602+ <Visible>False</Visible>\r
5603+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
5604+ <Install>false</Install>\r
5605+ </BootstrapperPackage>\r
5606 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
5607 <Visible>False</Visible>\r
5608+ <ProductName>\r
5609+ </ProductName>\r
5610+ <Install>false</Install>\r
5611 </BootstrapperPackage>\r
5612 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
5613 <Visible>False</Visible>\r
5614+ <ProductName>\r
5615+ </ProductName>\r
5616+ <Install>false</Install>\r
5617 </BootstrapperPackage>\r
5618 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
5619 <Visible>False</Visible>\r
5620+ <ProductName>\r
5621+ </ProductName>\r
5622+ <Install>false</Install>\r
5623+ </BootstrapperPackage>\r
5624+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
5625+ <Visible>False</Visible>\r
5626+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
5627+ <Install>false</Install>\r
5628 </BootstrapperPackage>\r
5629 </ItemGroup>\r
5630 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
5631diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/ThreadRocks.cs b/gendarme/rules/Gendarme.Rules.Concurrency/ThreadRocks.cs
5632index e89969b..95fb166 100644
5633--- a/gendarme/rules/Gendarme.Rules.Concurrency/ThreadRocks.cs
5634+++ b/gendarme/rules/Gendarme.Rules.Concurrency/ThreadRocks.cs
5635@@ -119,7 +119,7 @@ namespace Gendarme.Rules.Concurrency {
5636 }
5637
5638 } else if (method.IsStatic) {
5639- if (model == ThreadModel.Serializable && !method.Name.StartsWith ("op_")) {
5640+ if (model == ThreadModel.Serializable && !method.Name.StartsWith ("op_", StringComparison.Ordinal)) {
5641 return ThreadModel.MainThread;
5642 }
5643 }
5644diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/WriteStaticFieldFromInstanceMethodRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/WriteStaticFieldFromInstanceMethodRule.cs
5645index 686855d..9fa400f 100644
5646--- a/gendarme/rules/Gendarme.Rules.Concurrency/WriteStaticFieldFromInstanceMethodRule.cs
5647+++ b/gendarme/rules/Gendarme.Rules.Concurrency/WriteStaticFieldFromInstanceMethodRule.cs
5648@@ -27,6 +27,7 @@
5649 //
5650
5651 using System;
5652+using System.Globalization;
5653
5654 using Mono.Cecil;
5655 using Mono.Cecil.Cil;
5656@@ -76,8 +77,6 @@ namespace Gendarme.Rules.Concurrency {
5657 [EngineDependency (typeof (OpCodeEngine))]
5658 public class WriteStaticFieldFromInstanceMethodRule : Rule, IMethodRule {
5659
5660- private const string ThreadStaticAttribute = "System.ThreadStaticAttribute";
5661-
5662 static bool CheckField (FieldReference field)
5663 {
5664 // skip instance fields and generated static field (likely by the compiler)
5665@@ -92,7 +91,7 @@ namespace Gendarme.Rules.Concurrency {
5666 // skip fields decorated with [ThreadStatic] (the runtime will use
5667 // thread local storage for these so they are thread safe)
5668 if (fd.HasCustomAttributes) {
5669- if (fd.CustomAttributes.ContainsType (ThreadStaticAttribute))
5670+ if (fd.HasAttribute ("System", "ThreadStaticAttribute"))
5671 return false;
5672 }
5673 return true;
5674@@ -118,7 +117,9 @@ namespace Gendarme.Rules.Concurrency {
5675 if (ins.OpCode.Code == Code.Stsfld) {
5676 FieldReference fr = (ins.Operand as FieldReference);
5677 if (CheckField (fr)) {
5678- string text = String.Format ("The static field '{0}', of type '{1}'. is being set in an instance method.", fr.Name, fr.FieldType);
5679+ string text = String.Format (CultureInfo.InvariantCulture,
5680+ "The static field '{0}', of type '{1}'. is being set in an instance method.",
5681+ fr.Name, fr.FieldType);
5682 Runner.Report (method, ins, Severity.Medium, Confidence.High, text);
5683 }
5684 }
5685diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AttributeStringLiteralsShouldParseCorrectlyRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AttributeStringLiteralsShouldParseCorrectlyRule.cs
5686index d13758b..d75246e 100644
5687--- a/gendarme/rules/Gendarme.Rules.Correctness/AttributeStringLiteralsShouldParseCorrectlyRule.cs
5688+++ b/gendarme/rules/Gendarme.Rules.Correctness/AttributeStringLiteralsShouldParseCorrectlyRule.cs
5689@@ -29,6 +29,7 @@
5690 using System;
5691 using System.Collections;
5692 using System.Collections.Generic;
5693+using System.Globalization;
5694
5695 using Gendarme.Framework;
5696 using Gendarme.Framework.Rocks;
5697@@ -80,42 +81,16 @@ namespace Gendarme.Rules.Correctness {
5698 return original.IndexOf (value, 0, StringComparison.OrdinalIgnoreCase) != -1;
5699 }
5700
5701- // FIXME : FX4 Version.TryParse @ http://msdn.microsoft.com/en-us/library/system.version.tryparse.aspx
5702- static bool TryParseVersion (string version)
5703- {
5704- try {
5705- new Version (version);
5706- return true;
5707- }
5708- catch (FormatException) {
5709- return false;
5710- }
5711- catch (ArgumentException) {
5712- return false;
5713- }
5714- }
5715-
5716- // FIXME : FX4 Guid.TryParse @ http://msdn.microsoft.com/en-us/library/system.guid.tryparse.aspx
5717- static bool TryParseGuid (string guid)
5718- {
5719- try {
5720- new Guid (guid);
5721- return true;
5722- }
5723- catch (FormatException) {
5724- return false;
5725- }
5726- }
5727-
5728 void CheckParametersAndValues (IMetadataTokenProvider provider, IMethodSignature constructor, IList<CustomAttributeArgument> arguments)
5729 {
5730 for (int index = 0; index < arguments.Count; index++) {
5731 ParameterDefinition parameter = constructor.Parameters[index];
5732- if (String.Compare (parameter.ParameterType.FullName, "System.String") == 0) {
5733+ if (parameter.ParameterType.IsNamed ("System", "String")) {
5734 string value = (string) arguments [index].Value;
5735- if (Contains (parameter.Name, "version")) {
5736- if (!TryParseVersion (value)) {
5737- string msg = String.Format ("The value passed: {0} can't be parsed to a valid Version.", value);
5738+ if (Contains (parameter.Name, "version")) {
5739+ Version v = null;
5740+ if (!Version.TryParse (value, out v)) {
5741+ string msg = String.Format (CultureInfo.InvariantCulture, "The value passed: {0} can't be parsed to a valid Version.", value);
5742 Runner.Report (provider, Severity.High, Confidence.High, msg);
5743 }
5744 continue;
5745@@ -125,14 +100,15 @@ namespace Gendarme.Rules.Correctness {
5746 Contains (parameter.Name, "urn")) {
5747 Uri parsed = null;
5748 if (!Uri.TryCreate (value, UriKind.Absolute, out parsed)) {
5749- string msg = String.Format ("The valued passed {0} can't be parsed to a valid Uri.", value);
5750+ string msg = String.Format (CultureInfo.InvariantCulture, "The valued passed {0} can't be parsed to a valid Uri.", value);
5751 Runner.Report (provider, Severity.High, Confidence.High, msg);
5752 }
5753 continue;
5754 }
5755 if (Contains (parameter.Name, "guid")) {
5756- if (!TryParseGuid (value)) {
5757- string msg = String.Format ("The valued passed {0} can't be parsed to a valid Guid.", value);
5758+ Guid g;
5759+ if (!Guid.TryParse (value, out g)) {
5760+ string msg = String.Format (CultureInfo.InvariantCulture, "The valued passed {0} can't be parsed to a valid Guid.", value);
5761 Runner.Report (provider, Severity.High, Confidence.High, msg);
5762 }
5763 continue;
5764@@ -203,3 +179,4 @@ namespace Gendarme.Rules.Correctness {
5765 }
5766 }
5767 }
5768+
5769diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AvoidCodeWithSideEffectsInConditionalCodeRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AvoidCodeWithSideEffectsInConditionalCodeRule.cs
5770index 7a4a569..8d96766 100644
5771--- a/gendarme/rules/Gendarme.Rules.Correctness/AvoidCodeWithSideEffectsInConditionalCodeRule.cs
5772+++ b/gendarme/rules/Gendarme.Rules.Correctness/AvoidCodeWithSideEffectsInConditionalCodeRule.cs
5773@@ -34,6 +34,7 @@ using Mono.Cecil;
5774 using Mono.Cecil.Cil;
5775 using System;
5776 using System.Collections.Generic;
5777+using System.Globalization;
5778
5779 namespace Gendarme.Rules.Correctness {
5780
5781@@ -114,7 +115,8 @@ namespace Gendarme.Rules.Correctness {
5782
5783 string name = Mutates (method, ins);
5784 if (name != null) {
5785- string mesg = string.Format ("{0}::{1} is conditionally compiled on {2} but mutates {3}",
5786+ string mesg = String.Format (CultureInfo.InvariantCulture,
5787+ "{0}::{1} is conditionally compiled on {2} but mutates {3}",
5788 target.DeclaringType.Name, target.Name, define, name);
5789 Log.WriteLine (this, mesg);
5790
5791diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AvoidConstructorsInStaticTypesRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AvoidConstructorsInStaticTypesRule.cs
5792index a4eac8b..fe51ad6 100644
5793--- a/gendarme/rules/Gendarme.Rules.Correctness/AvoidConstructorsInStaticTypesRule.cs
5794+++ b/gendarme/rules/Gendarme.Rules.Correctness/AvoidConstructorsInStaticTypesRule.cs
5795@@ -106,7 +106,7 @@ namespace Gendarme.Rules.Correctness {
5796 }
5797 }
5798
5799- if (type.BaseType.FullName == "System.Object")
5800+ if (type.BaseType.IsNamed ("System", "Object"))
5801 return true;
5802
5803 return IsAllStatic (type.BaseType.Resolve ());
5804diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AvoidFloatingPointEqualityRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AvoidFloatingPointEqualityRule.cs
5805index 4c41820..7877367 100644
5806--- a/gendarme/rules/Gendarme.Rules.Correctness/AvoidFloatingPointEqualityRule.cs
5807+++ b/gendarme/rules/Gendarme.Rules.Correctness/AvoidFloatingPointEqualityRule.cs
5808@@ -179,7 +179,7 @@ namespace Gendarme.Rules.Correctness {
5809 case Code.Call:
5810 case Code.Callvirt:
5811 MemberReference member = instruction.Operand as MemberReference;
5812- if ((member != null) && member.Name.Equals ("Equals") && member.DeclaringType.IsFloatingPoint ()) {
5813+ if ((member != null) && (member.Name == "Equals") && member.DeclaringType.IsFloatingPoint ()) {
5814 Runner.Report (method, instruction, Severity.High, Confidence.Total, EqualsMessage);
5815 }
5816 break;
5817diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AvoidMethodsWithSideEffectsInConditionalCodeRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AvoidMethodsWithSideEffectsInConditionalCodeRule.cs
5818index 264d8ff..8e84621 100644
5819--- a/gendarme/rules/Gendarme.Rules.Correctness/AvoidMethodsWithSideEffectsInConditionalCodeRule.cs
5820+++ b/gendarme/rules/Gendarme.Rules.Correctness/AvoidMethodsWithSideEffectsInConditionalCodeRule.cs
5821@@ -34,6 +34,7 @@ using Mono.Cecil;
5822 using Mono.Cecil.Cil;
5823 using System;
5824 using System.Collections.Generic;
5825+using System.Globalization;
5826
5827 namespace Gendarme.Rules.Correctness {
5828
5829@@ -157,7 +158,8 @@ namespace Gendarme.Rules.Correctness {
5830
5831 MethodReference impure = FindImpurity (method, ins);
5832 if (impure != null) {
5833- string mesg = string.Format ("{0}::{1} is conditionally compiled on {2} but uses the impure {3}::{4}",
5834+ string mesg = String.Format (CultureInfo.InvariantCulture,
5835+ "{0}::{1} is conditionally compiled on {2} but uses the impure {3}::{4}",
5836 target.DeclaringType.Name, target.Name, define, impure.DeclaringType.Name, impure.Name);
5837 Log.WriteLine (this, mesg);
5838
5839@@ -207,7 +209,7 @@ namespace Gendarme.Rules.Correctness {
5840 if (!attr.HasConstructorArguments)
5841 continue;
5842 if (StringConstructor.Matches (attr.Constructor)) {
5843- if (attr.AttributeType.FullName == "System.Diagnostics.ConditionalAttribute") {
5844+ if (attr.AttributeType.IsNamed ("System.Diagnostics", "ConditionalAttribute")) {
5845 return (string) attr.ConstructorArguments [0].Value;
5846 }
5847 }
5848@@ -258,7 +260,7 @@ namespace Gendarme.Rules.Correctness {
5849
5850 if (method != null) {
5851 TypeDefinition type = method.DeclaringType;
5852- string type_name = type.FullName;
5853+ string type_name = type.GetFullName ();
5854 string method_name = method.Name;
5855
5856 // getters
5857@@ -274,7 +276,7 @@ namespace Gendarme.Rules.Correctness {
5858 return true;
5859
5860 // operators
5861- if (method_name.StartsWith ("op_") && method_name != "op_Implicit" && method_name != "op_Explicit")
5862+ if (method_name.StartsWith ("op_", StringComparison.Ordinal) && method_name != "op_Implicit" && method_name != "op_Explicit")
5863 return true;
5864
5865 // Contract methods (skip namespace)
5866@@ -282,10 +284,10 @@ namespace Gendarme.Rules.Correctness {
5867 return true;
5868
5869 // System.Predicate<T> and System.Comparison<T>
5870- if (type_name.StartsWith ("System.Predicate`1"))
5871+ if (type_name.StartsWith ("System.Predicate`1", StringComparison.Ordinal))
5872 return true;
5873
5874- if (type_name.StartsWith ("System.Comparison`1"))
5875+ if (type_name.StartsWith ("System.Comparison`1", StringComparison.Ordinal))
5876 return true;
5877
5878 // delegate invocation
5879@@ -317,7 +319,7 @@ namespace Gendarme.Rules.Correctness {
5880 static bool HasPureAttribute (IList<CustomAttribute> attrs)
5881 {
5882 foreach (CustomAttribute attr in attrs) {
5883- if (attr.AttributeType.FullName.Contains ("PureAttribute")) {
5884+ if (attr.AttributeType.Name == "PureAttribute") {
5885 return true;
5886 }
5887 }
5888diff --git a/gendarme/rules/Gendarme.Rules.Correctness/BadRecursiveInvocationRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/BadRecursiveInvocationRule.cs
5889index 6593f04..356d11a 100644
5890--- a/gendarme/rules/Gendarme.Rules.Correctness/BadRecursiveInvocationRule.cs
5891+++ b/gendarme/rules/Gendarme.Rules.Correctness/BadRecursiveInvocationRule.cs
5892@@ -99,10 +99,9 @@ namespace Gendarme.Rules.Correctness {
5893 if (!explicit_interface && (t2r != null) && !t2r.IsInterface)
5894 return true;
5895
5896- string t2name = t2.FullName;
5897 // we're calling into an interface and this could be us!
5898 foreach (MethodReference mr in method1.Resolve ().Overrides) {
5899- if (t2name == mr.DeclaringType.FullName)
5900+ if (mr.DeclaringType.IsNamed (t2.Namespace, t2.Name))
5901 return true;
5902 }
5903 return false;
5904@@ -134,7 +133,7 @@ namespace Gendarme.Rules.Correctness {
5905 ParameterDefinition param = (ParameterDefinition) insn.Operand;
5906 if (method.IsStatic)
5907 paramNum++;
5908- return (param.GetSequence () == paramNum);
5909+ return (param.Index == paramNum - 1);
5910 case Code.Ldarg_0:
5911 case Code.Ldarg_1:
5912 case Code.Ldarg_2:
5913diff --git a/gendarme/rules/Gendarme.Rules.Correctness/CheckParametersNullityInVisibleMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/CheckParametersNullityInVisibleMethodsRule.cs
5914index c5e0e64..506a9c0 100644
5915--- a/gendarme/rules/Gendarme.Rules.Correctness/CheckParametersNullityInVisibleMethodsRule.cs
5916+++ b/gendarme/rules/Gendarme.Rules.Correctness/CheckParametersNullityInVisibleMethodsRule.cs
5917@@ -106,9 +106,9 @@ namespace Gendarme.Rules.Correctness {
5918 if (parameter.IsOut)
5919 return;
5920
5921- int sequence = parameter.GetSequence ();
5922+ int sequence = parameter.Index;
5923 // ldarg this - 'this' cannot be null
5924- if (sequence == 0)
5925+ if (sequence == -1)
5926 return;
5927
5928 // was there a null check done before ?
5929@@ -146,7 +146,7 @@ namespace Gendarme.Rules.Correctness {
5930 return;
5931
5932 // avoid checking parameters where a null check was already found
5933- if (has_null_check.Get (parameter.GetSequence ()))
5934+ if (has_null_check.Get (parameter.Index))
5935 return;
5936
5937 Instruction next = ins.Next;
5938@@ -158,21 +158,21 @@ namespace Gendarme.Rules.Correctness {
5939 nc = next.OpCode.Code;
5940 break;
5941 case Code.Isinst:
5942- has_null_check.Set (parameter.GetSequence ());
5943+ has_null_check.Set (parameter.Index);
5944 return;
5945 }
5946
5947 if (null_compare.Get (nc)) {
5948- has_null_check.Set (parameter.GetSequence ());
5949+ has_null_check.Set (parameter.Index);
5950 } else {
5951 // compare with null (next or previous to current instruction)
5952 // followed by a CEQ instruction
5953 if (nc == Code.Ldnull) {
5954 if (next.Next.OpCode.Code == Code.Ceq)
5955- has_null_check.Set (parameter.GetSequence ());
5956+ has_null_check.Set (parameter.Index);
5957 } else if (nc == Code.Ceq) {
5958 if (ins.Previous.OpCode.Code == Code.Ldnull)
5959- has_null_check.Set (parameter.GetSequence ());
5960+ has_null_check.Set (parameter.Index);
5961 }
5962 }
5963 }
5964@@ -204,7 +204,7 @@ namespace Gendarme.Rules.Correctness {
5965 pi = pi.Previous;
5966 ParameterDefinition p = pi.GetParameter (method);
5967 if (p != null)
5968- has_null_check.Set (p.GetSequence ());
5969+ has_null_check.Set (p.Index);
5970 }
5971 }
5972
5973diff --git a/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs
5974new file mode 100644
5975index 0000000..442572e
5976--- /dev/null
5977+++ b/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs
5978@@ -0,0 +1,96 @@
5979+//
5980+// Gendarme.Rules.Correctness.DeclareEventsExplicitlyRule
5981+//
5982+// Authors:
5983+// Sebastien Pouliot <sebastien@ximian.com>
5984+//
5985+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
5986+//
5987+// Permission is hereby granted, free of charge, to any person obtaining
5988+// a copy of this software and associated documentation files (the
5989+// "Software"), to deal in the Software without restriction, including
5990+// without limitation the rights to use, copy, modify, merge, publish,
5991+// distribute, sublicense, and/or sell copies of the Software, and to
5992+// permit persons to whom the Software is furnished to do so, subject to
5993+// the following conditions:
5994+//
5995+// The above copyright notice and this permission notice shall be
5996+// included in all copies or substantial portions of the Software.
5997+//
5998+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
5999+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6000+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
6001+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
6002+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
6003+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
6004+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6005+//
6006+
6007+using Mono.Cecil;
6008+
6009+using Gendarme.Framework;
6010+
6011+namespace Gendarme.Rules.Correctness {
6012+
6013+ /// <summary>
6014+ /// This rule detect is an event handler was declared without the <c>event</c>
6015+ /// keyword, making the declaration a simple field in its type. Such occurances
6016+ /// are likely a typo and should be fixed.
6017+ /// </summary>
6018+ /// <example>
6019+ /// Bad example:
6020+ /// <code>
6021+ /// public class EventLess {
6022+ /// public static EventHandler&lt;EventArgs&gt; MyEvent;
6023+ /// }
6024+ /// </code>
6025+ /// </example>
6026+ /// <example>
6027+ /// Good example:
6028+ /// <code>
6029+ /// public class Event {
6030+ /// public static event EventHandler&lt;EventArgs&gt; MyEvent;
6031+ /// }
6032+ /// </code>
6033+ /// </example>
6034+ // suggested in https://bugzilla.novell.com/show_bug.cgi?id=669192
6035+ [Problem ("An event handler was declared without the 'event' keyword")]
6036+ [Solution ("Add the missing 'event' keyword to your event handler declaration")]
6037+ public class DeclareEventsExplicitlyRule : Rule, ITypeRule {
6038+
6039+ static bool LookForEvent (MemberReference field, TypeDefinition type)
6040+ {
6041+ string fname = field.Name;
6042+ foreach (EventDefinition evnt in type.Events) {
6043+ if (fname == evnt.Name)
6044+ return true;
6045+ }
6046+ return false;
6047+ }
6048+
6049+ public RuleResult CheckType (TypeDefinition type)
6050+ {
6051+ if (!type.HasFields || type.IsEnum)
6052+ return RuleResult.DoesNotApply;
6053+
6054+ // allow to short-circuit LookForEvent if the type has no event
6055+ bool has_events = type.HasEvents;
6056+ foreach (FieldDefinition field in type.Fields) {
6057+ TypeReference ftype = field.FieldType;
6058+ if (ftype.Namespace != "System")
6059+ continue;
6060+
6061+ switch (ftype.Name) {
6062+ case "EventHandler":
6063+ case "EventHandler`1":
6064+ // is there (any?) event matching the field name ?
6065+ if (!has_events || !LookForEvent (field, type))
6066+ Runner.Report (field, Severity.High, Confidence.High);
6067+ break;
6068+ }
6069+ }
6070+
6071+ return Runner.CurrentRuleResult;
6072+ }
6073+ }
6074+}
6075diff --git a/gendarme/rules/Gendarme.Rules.Correctness/DisposableFieldsShouldBeDisposedRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/DisposableFieldsShouldBeDisposedRule.cs
6076index 576fff2..7152176 100644
6077--- a/gendarme/rules/Gendarme.Rules.Correctness/DisposableFieldsShouldBeDisposedRule.cs
6078+++ b/gendarme/rules/Gendarme.Rules.Correctness/DisposableFieldsShouldBeDisposedRule.cs
6079@@ -30,6 +30,7 @@
6080
6081 using System;
6082 using System.Collections.Generic;
6083+using System.Globalization;
6084
6085 using Mono.Cecil;
6086 using Mono.Cecil.Cil;
6087@@ -116,7 +117,7 @@ namespace Gendarme.Rules.Correctness {
6088
6089 // note: other rule will complain if there are disposable or native fields
6090 // in a type that doesn't implement IDisposable, so we don't bother here
6091- if (!type.Implements ("System.IDisposable"))
6092+ if (!type.Implements ("System", "IDisposable"))
6093 return RuleResult.DoesNotApply;
6094
6095 MethodDefinition implicitDisposeMethod = GetNonAbstractMethod (type, MethodSignatures.Dispose);
6096@@ -148,7 +149,7 @@ namespace Gendarme.Rules.Correctness {
6097 TypeDefinition fieldType = field.FieldType.Resolve ();
6098 if (fieldType == null)
6099 continue;
6100- if (fieldType.Implements ("System.IDisposable"))
6101+ if (fieldType.Implements ("System", "IDisposable"))
6102 disposeableFields.Add (field);
6103 }
6104
6105@@ -177,10 +178,10 @@ namespace Gendarme.Rules.Correctness {
6106 private void CheckBaseDispose (TypeDefinition type, MethodDefinition implicitDisposeMethod, MethodDefinition explicitDisposeMethod)
6107 {
6108 TypeDefinition baseType = type;
6109- while (baseType.BaseType.FullName != "System.Object") {
6110+ while (!baseType.BaseType.IsNamed ("System", "Object")) {
6111 baseType = baseType.BaseType.Resolve ();
6112 // also checks parents, so no need to search further
6113- if ((baseType == null) || !baseType.Implements ("System.IDisposable"))
6114+ if ((baseType == null) || !baseType.Implements ("System", "IDisposable"))
6115 break;
6116
6117 //we just check for Dispose() here
6118@@ -196,7 +197,7 @@ namespace Gendarme.Rules.Correctness {
6119 }
6120 }
6121
6122- private void CheckIfBaseDisposeIsCalled (MethodDefinition method, MethodDefinition baseMethod)
6123+ private void CheckIfBaseDisposeIsCalled (MethodDefinition method, MemberReference baseMethod)
6124 {
6125 bool found = false;
6126
6127@@ -215,7 +216,7 @@ namespace Gendarme.Rules.Correctness {
6128 if (call.OpCode.Code != Code.Call && call.OpCode.Code != Code.Callvirt)
6129 continue;
6130 MethodReference calledMethod = (MethodReference) call.Operand;
6131- if (calledMethod.ToString () != baseMethod.ToString ())
6132+ if (calledMethod.GetFullName () != baseMethod.GetFullName ())
6133 continue;
6134 found = true;
6135 }
6136@@ -223,7 +224,7 @@ namespace Gendarme.Rules.Correctness {
6137 }
6138
6139 if (!found) {
6140- string s = String.Format ("{0} should call base.Dispose().", method.ToString ());
6141+ string s = String.Format (CultureInfo.InvariantCulture, "{0} should call base.Dispose().", method.GetFullName ());
6142 Runner.Report (method, Severity.Medium, Confidence.High, s);
6143 }
6144 }
6145@@ -256,7 +257,8 @@ namespace Gendarme.Rules.Correctness {
6146 return;
6147
6148 foreach (FieldDefinition field in fields) {
6149- string s = string.Format ("Since {0} is Disposable {1}() should call {0}.Dispose()", field.Name, method.Name);
6150+ string s = String.Format (CultureInfo.InvariantCulture,
6151+ "Since {0} is Disposable {1}() should call {0}.Dispose()", field.Name, method.Name);
6152 Runner.Report (field, Severity.High, Confidence.High, s);
6153 }
6154 }
6155diff --git a/gendarme/rules/Gendarme.Rules.Correctness/DoNotRoundIntegersRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/DoNotRoundIntegersRule.cs
6156index a788d00..64172e6 100644
6157--- a/gendarme/rules/Gendarme.Rules.Correctness/DoNotRoundIntegersRule.cs
6158+++ b/gendarme/rules/Gendarme.Rules.Correctness/DoNotRoundIntegersRule.cs
6159@@ -27,11 +27,14 @@
6160 //
6161
6162 using System;
6163+using System.Globalization;
6164
6165 using Mono.Cecil;
6166 using Mono.Cecil.Cil;
6167
6168 using Gendarme.Framework;
6169+using Gendarme.Framework.Engines;
6170+using Gendarme.Framework.Helpers;
6171 using Gendarme.Framework.Rocks;
6172
6173 namespace Gendarme.Rules.Correctness {
6174@@ -41,8 +44,8 @@ namespace Gendarme.Rules.Correctness {
6175 // ICAST: int value cast to float and then passed to Math.round (ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND)
6176
6177 /// <summary>
6178- /// This rule check for attempts to call <c>Round</c>, <c>Ceiling</c>, <c>Floor</c> or
6179- /// <c>Truncate</c> on an integral type. This often indicate a typo in the source code
6180+ /// This rule check for attempts to call <c>System.Math.Round</c>, <c>System.Math.Ceiling</c>, <c>System.Math.Floor</c> or
6181+ /// <c>System.Math.Truncate</c> on an integral type. This often indicate a typo in the source code
6182 /// (e.g. wrong variable) or an unnecessary operation.
6183 /// </summary>
6184 /// <example>
6185@@ -63,10 +66,10 @@ namespace Gendarme.Rules.Correctness {
6186 /// }
6187 /// </code>
6188 /// </example>
6189- /// <remarks>This rule is available since Gendarme 2.0</remarks>
6190
6191 [Problem ("This method calls round/ceil/floor/truncate with an integer value.")]
6192 [Solution ("Verify the code logic. This could be a typo (wrong variable) or an unnecessary operation.")]
6193+ [EngineDependency (typeof (OpCodeEngine))]
6194 public class DoNotRoundIntegersRule : Rule, IMethodRule {
6195
6196 static TypeReference GetType (Instruction ins, MethodDefinition method)
6197@@ -105,8 +108,8 @@ namespace Gendarme.Rules.Correctness {
6198 if (rv.IsFloatingPoint ())
6199 return null;
6200 // but convertion into decimals are not...
6201- if (rv.FullName == "System.Decimal") {
6202- if (mr.DeclaringType.FullName != "System.Decimal")
6203+ if (rv.IsNamed ("System", "Decimal")) {
6204+ if (!mr.DeclaringType.IsNamed ("System", "Decimal"))
6205 return null;
6206
6207 // ... unless it's a convertion from a FP value
6208@@ -137,9 +140,13 @@ namespace Gendarme.Rules.Correctness {
6209 if (!method.HasBody)
6210 return RuleResult.DoesNotApply;
6211
6212+ // exclude methods that don't have calls
6213+ if (!OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)))
6214+ return RuleResult.DoesNotApply;
6215+
6216 foreach (Instruction ins in method.Body.Instructions) {
6217 MethodReference mr = ins.GetMethod ();
6218- if ((mr == null) || (mr.DeclaringType.FullName != "System.Math"))
6219+ if ((mr == null) || !mr.DeclaringType.IsNamed ("System", "Math"))
6220 continue;
6221
6222 Instruction value = null;
6223@@ -171,7 +178,8 @@ namespace Gendarme.Rules.Correctness {
6224 if (type == null)
6225 continue;
6226
6227- string msg = string.Format ("Math.{0} called on a {1}.", name, type.FullName);
6228+ string msg = String.Format (CultureInfo.InvariantCulture, "Math.{0} called on a {1}.",
6229+ name, type.GetFullName ());
6230 Runner.Report (method, ins, Severity.Medium, Confidence.Normal, msg);
6231 }
6232 return Runner.CurrentRuleResult;
6233diff --git a/gendarme/rules/Gendarme.Rules.Correctness/DontCompareWithNaNRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/DontCompareWithNaNRule.cs
6234index ffa5a6b..0de96ec 100644
6235--- a/gendarme/rules/Gendarme.Rules.Correctness/DontCompareWithNaNRule.cs
6236+++ b/gendarme/rules/Gendarme.Rules.Correctness/DontCompareWithNaNRule.cs
6237@@ -74,21 +74,6 @@ namespace Gendarme.Rules.Correctness {
6238 private const string EqualityMessage = "A floating point value is compared (== or !=) with [Single|Double].NaN.";
6239 private const string EqualsMessage = "[Single|Double].Equals is called using NaN.";
6240
6241- private static string[] FloatingPointTypes = { "System.Single", "System.Double" };
6242-
6243- public override void Initialize (IRunner runner)
6244- {
6245- base.Initialize (runner);
6246-
6247- // we want to avoid checking all methods if the module doesn't refer to either
6248- // System.Single or System.Double (big performance difference)
6249- // note: mscorlib.dll is an exception since it defines, not refer, System.Single and Double
6250- Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
6251- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
6252- e.CurrentModule.HasAnyTypeReference (FloatingPointTypes);
6253- };
6254- }
6255-
6256 private static bool CheckPrevious (IList<Instruction> il, int index)
6257 {
6258 for (int i = index; i >= 0; i--) {
6259@@ -143,7 +128,7 @@ namespace Gendarme.Rules.Correctness {
6260 case Code.Call:
6261 case Code.Callvirt:
6262 MemberReference callee = ins.Operand as MemberReference;
6263- if ((callee != null) && callee.Name.Equals ("Equals") && callee.DeclaringType.IsFloatingPoint ()) {
6264+ if ((callee != null) && (callee.Name == "Equals") && callee.DeclaringType.IsFloatingPoint ()) {
6265 if (!CheckPrevious (il, i - 1)) {
6266 Runner.Report (method, ins, Severity.Critical, Confidence.Total, EqualsMessage);
6267 }
6268diff --git a/gendarme/rules/Gendarme.Rules.Correctness/EnsureLocalDisposalRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/EnsureLocalDisposalRule.cs
6269index 14c0c33..6d1c73d 100644
6270--- a/gendarme/rules/Gendarme.Rules.Correctness/EnsureLocalDisposalRule.cs
6271+++ b/gendarme/rules/Gendarme.Rules.Correctness/EnsureLocalDisposalRule.cs
6272@@ -3,8 +3,10 @@
6273 //
6274 // Authors:
6275 // Cedric Vivier <cedricv@neonux.com>
6276+// Sebastien Pouliot <sebastien@ximian.com>
6277 //
6278 // Copyright (C) 2008 Cedric Vivier
6279+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
6280 //
6281 // Permission is hereby granted, free of charge, to any person obtaining a copy
6282 // of this software and associated documentation files (the "Software"), to deal
6283@@ -26,6 +28,7 @@
6284
6285 using System;
6286 using System.Collections.Generic;
6287+using System.Globalization;
6288
6289 using Mono.Cecil;
6290 using Mono.Cecil.Cil;
6291@@ -115,7 +118,7 @@ namespace Gendarme.Rules.Correctness {
6292 public sealed class EnsureLocalDisposalRule : Rule, IMethodRule {
6293
6294 OpCodeBitmask callsAndNewobjBitmask = BuildCallsAndNewobjOpCodeBitmask ();
6295- HashSet<Instruction> suspectLocals = new HashSet<Instruction> ();
6296+ Bitmask<ulong> locals = new Bitmask<ulong> ();
6297
6298 static bool IsDispose (MethodReference call)
6299 {
6300@@ -134,57 +137,109 @@ namespace Gendarme.Rules.Correctness {
6301 if (method.IsConstructor) {
6302 if (method.DeclaringType.IsGeneratedCode ())
6303 return false; //eg. generators
6304- return method.DeclaringType.Implements ("System.IDisposable");
6305+ return method.DeclaringType.Implements ("System", "IDisposable");
6306 }
6307
6308- return method.ReturnType.Implements ("System.IDisposable");
6309+ return method.ReturnType.Implements ("System", "IDisposable");
6310 }
6311
6312- static bool AreBothInstructionsInSameTryFinallyBlock (MethodBody body, Instruction a, Instruction b)
6313+ static bool IsSetter (MethodReference m)
6314 {
6315+ if (m == null)
6316+ return false;
6317+ MethodDefinition md = m.Resolve ();
6318+ if (md == null)
6319+ return m.Name.StartsWith ("set_", StringComparison.Ordinal);
6320+ return md.IsSetter;
6321+ }
6322+
6323+ static bool IsInsideFinallyBlock (MethodDefinition method, Instruction ins)
6324+ {
6325+ MethodBody body = method.Body;
6326+ if (!body.HasExceptionHandlers)
6327+ return false;
6328+
6329 foreach (ExceptionHandler eh in body.ExceptionHandlers) {
6330 if (eh.HandlerType != ExceptionHandlerType.Finally)
6331 continue;
6332- if (eh.TryStart.Offset <= a.Next.Offset && eh.TryEnd.Offset >= a.Offset
6333- && eh.HandlerStart.Offset <= b.Offset && eh.HandlerEnd.Offset >= b.Offset)
6334+ if (ins.Offset >= eh.HandlerStart.Offset || ins.Offset < eh.HandlerEnd.Offset)
6335 return true;
6336 }
6337 return false;
6338 }
6339
6340- static Instruction LocalTraceBack (IMethodSignature method, Instruction ins)
6341+ void Clear (MethodDefinition method, Instruction ins)
6342 {
6343- ins = ins.TraceBack (method);
6344- while (ins != null) {
6345- if (ins.IsLoadLocal () || ins.IsStoreLocal ())
6346- return ins;
6347- ins = ins.TraceBack (method);
6348+ VariableDefinition v = ins.GetVariable (method);
6349+ if (v != null)
6350+ locals.Clear ((ulong) v.Index);
6351+ }
6352+
6353+ void CheckForReturn (MethodDefinition method, Instruction ins)
6354+ {
6355+ if (ins.IsLoadLocal ())
6356+ Clear (method, ins);
6357+ }
6358+
6359+ void CheckForOutParameters (MethodDefinition method, Instruction ins)
6360+ {
6361+ Instruction iref = ins.TraceBack (method);
6362+ if (iref == null)
6363+ return;
6364+ ParameterDefinition p = iref.GetParameter (method);
6365+ if ((p != null) && p.IsOut) {
6366+ ins = ins.Previous;
6367+ if (ins.IsLoadLocal ())
6368+ Clear (method, ins);
6369 }
6370- return null;
6371 }
6372
6373- Instruction FindRelatedSuspectLocal (MethodDefinition method, Instruction ins)
6374+ void CheckDisposeCalls (MethodDefinition method, Instruction ins)
6375 {
6376- ins = LocalTraceBack (method, ins);
6377- if (null == ins)
6378- return null;
6379-
6380- int index = ins.GetVariable (method).Index;
6381- foreach (var local in suspectLocals) {
6382- if (local.GetVariable (method).Index == index)
6383- return local;
6384+ Instruction instance = ins.TraceBack (method);
6385+ if (instance == null)
6386+ return;
6387+
6388+ VariableDefinition v = instance.GetVariable (method);
6389+ ulong index = v == null ? UInt64.MaxValue : (ulong) v.Index;
6390+ if (v != null && locals.Get (index)) {
6391+ if (!IsInsideFinallyBlock (method, ins)) {
6392+ string msg = String.Format (CultureInfo.InvariantCulture,
6393+ "Local {0}is not guaranteed to be disposed of.",
6394+ GetFriendlyNameOrEmpty (v));
6395+ Runner.Report (method, Severity.Medium, Confidence.Normal, msg);
6396+ }
6397+ locals.Clear (index);
6398 }
6399- return null;
6400 }
6401
6402- static bool IsSetter (MethodReference m)
6403+ bool CheckCallsToOtherInstances (MethodDefinition method, Instruction ins, MethodReference call)
6404 {
6405- if (m == null)
6406+ Instruction p = ins.TraceBack (method, 0);
6407+ if (p.Is (Code.Ldarg_0))
6408 return false;
6409- MethodDefinition md = m.Resolve ();
6410- if (md == null)
6411- return m.Name.StartsWith ("set_", StringComparison.Ordinal);
6412- return md.IsSetter;
6413+
6414+ if (call.HasParameters) {
6415+ for (int i = 1; i <= call.Parameters.Count; i++) {
6416+ p = ins.TraceBack (method, -i);
6417+ Clear (method, p);
6418+ }
6419+ }
6420+ return true;
6421+ }
6422+
6423+ void CheckReassignment (MethodDefinition method, Instruction ins)
6424+ {
6425+ VariableDefinition v = ins.GetVariable (method);
6426+ ulong index = (ulong) v.Index;
6427+ if (locals.Get (index)) {
6428+ string msg = String.Format (CultureInfo.InvariantCulture,
6429+ "Local {0}is not disposed before being re-assigned.",
6430+ GetFriendlyNameOrEmpty (v));
6431+ Runner.Report (method, ins, Severity.High, Confidence.Normal, msg);
6432+ } else {
6433+ locals.Set (index);
6434+ }
6435 }
6436
6437 public RuleResult CheckMethod (MethodDefinition method)
6438@@ -193,36 +248,42 @@ namespace Gendarme.Rules.Correctness {
6439 return RuleResult.DoesNotApply;
6440
6441 //is there any potential IDisposable-getting opcode in the method?
6442- OpCodeBitmask methodBitmask = OpCodeEngine.GetBitmask (method);
6443- if (!callsAndNewobjBitmask.Intersect (methodBitmask))
6444+ if (!callsAndNewobjBitmask.Intersect (OpCodeEngine.GetBitmask (method)))
6445 return RuleResult.DoesNotApply;
6446
6447- //we ignore methods/constructors that returns IDisposable themselves
6448- //where local(s) are most likely used for disposable object construction
6449- if (DoesReturnDisposable (method))
6450- return RuleResult.DoesNotApply;
6451+ // we will not report IDiposable locals that are returned from a method
6452+ bool return_idisposable = DoesReturnDisposable (method);
6453
6454- suspectLocals.Clear ();
6455+ locals.ClearAll ();
6456
6457- MethodBody body = method.Body;
6458- foreach (Instruction ins in body.Instructions) {
6459- if (!callsAndNewobjBitmask.Get (ins.OpCode.Code))
6460+ foreach (Instruction ins in method.Body.Instructions) {
6461+ Code code = ins.OpCode.Code;
6462+ switch (code) {
6463+ case Code.Ret:
6464+ if (return_idisposable)
6465+ CheckForReturn (method, ins.Previous);
6466 continue;
6467+ case Code.Stind_Ref:
6468+ CheckForOutParameters (method, ins);
6469+ continue;
6470+ default:
6471+ if (!callsAndNewobjBitmask.Get (code))
6472+ continue;
6473+ break;
6474+ }
6475
6476 MethodReference call = (MethodReference) ins.Operand;
6477
6478 if (IsDispose (call)) {
6479- Instruction local = FindRelatedSuspectLocal (method, ins);
6480- if (local != null) {
6481- if (!AreBothInstructionsInSameTryFinallyBlock (body, local, ins)) {
6482- string msg = string.Format ("Local {0}is not guaranteed to be disposed of.", GetFriendlyNameOrEmpty (local.GetVariable (method)));
6483- Runner.Report (method, local, Severity.Medium, Confidence.Normal, msg);
6484- }
6485- suspectLocals.Remove (local);
6486- }
6487+ CheckDisposeCalls (method, ins);
6488 continue;
6489 }
6490
6491+ if (call.HasThis && (code != Code.Newobj)) {
6492+ if (!CheckCallsToOtherInstances (method, ins, call))
6493+ continue;
6494+ }
6495+
6496 if (!DoesReturnDisposable (call))
6497 continue;
6498
6499@@ -233,40 +294,47 @@ namespace Gendarme.Rules.Correctness {
6500 Code nextCode = nextInstruction.OpCode.Code;
6501 if (nextCode == Code.Pop || OpCodeBitmask.Calls.Get (nextCode)) {
6502 // We ignore setter because it is an obvious share of the IDisposable
6503- if (IsSetter (nextInstruction.Operand as MethodReference))
6504- continue;
6505-
6506- ReportCall (method, ins, call);
6507- continue;
6508+ if (!IsSetter (nextInstruction.Operand as MethodReference))
6509+ ReportCall (method, ins, call);
6510+ } else if (nextInstruction.IsStoreLocal ()) {
6511+ // make sure we're not re-assigning over a non-disposed IDisposable
6512+ CheckReassignment (method, nextInstruction);
6513 }
6514-
6515- //even if an IDisposable, it isn't stored in a local
6516- if (nextInstruction.IsStoreLocal ())
6517- suspectLocals.Add (nextInstruction);
6518 }
6519
6520- foreach (var local in suspectLocals) {
6521- string msg = string.Format ("Local {0}is not disposed of (at least not locally).", GetFriendlyNameOrEmpty (local.GetVariable (method)));
6522- Runner.Report (method, local, Severity.High, Confidence.Normal, msg);
6523- }
6524+ ReportNonDisposedLocals (method);
6525
6526 return Runner.CurrentRuleResult;
6527 }
6528
6529+ void ReportNonDisposedLocals (MethodDefinition method)
6530+ {
6531+ for (ulong i = 0; i < 64; i++) {
6532+ if (!locals.Get (i))
6533+ continue;
6534+ string msg = String.Format (CultureInfo.InvariantCulture,
6535+ "Local {0}is not disposed of (at least not locally).",
6536+ GetFriendlyNameOrEmpty (method.Body.Variables [(int) i]));
6537+ Runner.Report (method, Severity.High, Confidence.Normal, msg);
6538+ }
6539+ }
6540+
6541 static bool IsFluentLike (MethodReference method)
6542 {
6543- string rtype = method.ReturnType.FullName;
6544+ TypeReference rtype = method.ReturnType;
6545+ string nspace = rtype.Namespace;
6546+ string name = rtype.Name;
6547 // StringBuilder StringBuilder.Append (...)
6548- if (rtype == method.DeclaringType.FullName)
6549+ if (method.DeclaringType.IsNamed (nspace, name))
6550 return true;
6551- return (method.HasParameters && rtype == method.Parameters [0].ParameterType.FullName);
6552+ return (method.HasParameters && method.Parameters [0].ParameterType.IsNamed (nspace, name));
6553 }
6554
6555 void ReportCall (MethodDefinition method, Instruction ins, MethodReference call)
6556 {
6557 TypeReference type = ins.Is (Code.Newobj) ? call.DeclaringType : call.ReturnType;
6558 bool fluent = IsFluentLike (call);
6559- string msg = string.Format ("Local of type '{0}' is not disposed of ({1}).",
6560+ string msg = String.Format (CultureInfo.InvariantCulture, "Local of type '{0}' is not disposed of ({1}).",
6561 type.Name, fluent ? "is this a fluent-like API ?" : "at least not locally");
6562 Runner.Report (method, ins, Severity.High, fluent ? Confidence.Normal : Confidence.High, msg);
6563 }
6564@@ -275,8 +343,8 @@ namespace Gendarme.Rules.Correctness {
6565 {
6566 string tname = variable.VariableType.Name;
6567 if (variable.IsGeneratedName ())
6568- return string.Format ("of type '{0}' ", tname);
6569- return string.Format ("'{0}' of type '{1}' ", variable.Name, tname);
6570+ return String.Format (CultureInfo.InvariantCulture, "of type '{0}' ", tname);
6571+ return String.Format (CultureInfo.InvariantCulture, "'{0}' of type '{1}' ", variable.Name, tname);
6572 }
6573
6574 static OpCodeBitmask BuildCallsAndNewobjOpCodeBitmask ()
6575diff --git a/gendarme/rules/Gendarme.Rules.Correctness/FloatComparisonRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/FloatComparisonRule.cs
6576index 39f8fe7..51d5806 100644
6577--- a/gendarme/rules/Gendarme.Rules.Correctness/FloatComparisonRule.cs
6578+++ b/gendarme/rules/Gendarme.Rules.Correctness/FloatComparisonRule.cs
6579@@ -41,8 +41,6 @@ namespace Gendarme.Rules.Correctness {
6580 [EngineDependency (typeof (OpCodeEngine))]
6581 abstract public class FloatingComparisonRule : Rule {
6582
6583- private static string[] FloatingPointTypes = { "System.Single", "System.Double" };
6584-
6585 public override void Initialize (IRunner runner)
6586 {
6587 base.Initialize (runner);
6588@@ -52,7 +50,9 @@ namespace Gendarme.Rules.Correctness {
6589 // note: mscorlib.dll is an exception since it defines, not refer, System.Single and Double
6590 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
6591 Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
6592- e.CurrentModule.HasAnyTypeReference (FloatingPointTypes);
6593+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
6594+ return tr.IsFloatingPoint ();
6595+ });
6596 };
6597 }
6598
6599diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Gendarme.Rules.Correctness.csproj b/gendarme/rules/Gendarme.Rules.Correctness/Gendarme.Rules.Correctness.csproj
6600index 505ef8f..4258d86 100755
6601--- a/gendarme/rules/Gendarme.Rules.Correctness/Gendarme.Rules.Correctness.csproj
6602+++ b/gendarme/rules/Gendarme.Rules.Correctness/Gendarme.Rules.Correctness.csproj
6603@@ -1,5 +1,5 @@
6604 <?xml version="1.0" encoding="utf-8"?>\r
6605-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
6606+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
6607 <PropertyGroup>\r
6608 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
6609 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
6610@@ -12,9 +12,11 @@
6611 <AssemblyName>Gendarme.Rules.Correctness</AssemblyName>\r
6612 <FileUpgradeFlags>\r
6613 </FileUpgradeFlags>\r
6614- <OldToolsVersion>2.0</OldToolsVersion>\r
6615+ <OldToolsVersion>3.5</OldToolsVersion>\r
6616 <UpgradeBackupLocation>\r
6617 </UpgradeBackupLocation>\r
6618+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
6619+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
6620 <PublishUrl>http://localhost/Gendarme.Rules.Correctness/</PublishUrl>\r
6621 <Install>true</Install>\r
6622 <InstallFrom>Web</InstallFrom>\r
6623@@ -27,10 +29,9 @@
6624 <MapFileExtensions>true</MapFileExtensions>\r
6625 <ApplicationRevision>0</ApplicationRevision>\r
6626 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
6627- <IsWebBootstrapper>true</IsWebBootstrapper>\r
6628 <UseApplicationTrust>false</UseApplicationTrust>\r
6629 <BootstrapperEnabled>true</BootstrapperEnabled>\r
6630- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
6631+ <TargetFrameworkProfile />\r
6632 </PropertyGroup>\r
6633 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
6634 <DebugSymbols>true</DebugSymbols>\r
6635@@ -43,6 +44,7 @@
6636 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Correctness.xml</DocumentationFile>\r
6637 <NoWarn>1591</NoWarn>\r
6638 <WarningsAsErrors>1570</WarningsAsErrors>\r
6639+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
6640 </PropertyGroup>\r
6641 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
6642 <DebugType>pdbonly</DebugType>\r
6643@@ -54,6 +56,7 @@
6644 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Correctness.xml</DocumentationFile>\r
6645 <NoWarn>1591</NoWarn>\r
6646 <WarningsAsErrors>1570</WarningsAsErrors>\r
6647+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
6648 </PropertyGroup>\r
6649 <ItemGroup>\r
6650 <Reference Include="System" />\r
6651@@ -107,6 +110,9 @@
6652 <Compile Include="ReviewUseOfInt64BitsToDoubleRule.cs" />\r
6653 <Compile Include="ReviewUselessControlFlowRule.cs" />\r
6654 <Compile Include="ReviewUseOfModuloOneOnIntegersRule.cs" />\r
6655+ <Compile Include="TypesShouldBeDisposableBaseRule.cs" />\r
6656+ <Compile Include="TypesWithDisposableFieldsShouldBeDisposableRule.cs" />\r
6657+ <Compile Include="TypesWithNativeFieldsShouldBeDisposableRule.cs" />\r
6658 <Compile Include="UseNoInliningWithGetCallingAssemblyRule.cs" />\r
6659 <Compile Include="UseValueInPropertySetterRule.cs" />\r
6660 <None Include="ChangeLog" />\r
6661@@ -129,14 +135,33 @@
6662 </ProjectReference>\r
6663 </ItemGroup>\r
6664 <ItemGroup>\r
6665+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
6666+ <Visible>False</Visible>\r
6667+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
6668+ <Install>false</Install>\r
6669+ </BootstrapperPackage>\r
6670 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
6671 <Visible>False</Visible>\r
6672+ <ProductName>\r
6673+ </ProductName>\r
6674+ <Install>false</Install>\r
6675 </BootstrapperPackage>\r
6676 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
6677 <Visible>False</Visible>\r
6678+ <ProductName>\r
6679+ </ProductName>\r
6680+ <Install>false</Install>\r
6681 </BootstrapperPackage>\r
6682 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
6683 <Visible>False</Visible>\r
6684+ <ProductName>\r
6685+ </ProductName>\r
6686+ <Install>false</Install>\r
6687+ </BootstrapperPackage>\r
6688+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
6689+ <Visible>False</Visible>\r
6690+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
6691+ <Install>false</Install>\r
6692 </BootstrapperPackage>\r
6693 </ItemGroup>\r
6694 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
6695diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Makefile.am b/gendarme/rules/Gendarme.Rules.Correctness/Makefile.am
6696index 9dabf5f..a338289 100644
6697--- a/gendarme/rules/Gendarme.Rules.Correctness/Makefile.am
6698+++ b/gendarme/rules/Gendarme.Rules.Correctness/Makefile.am
6699@@ -6,6 +6,7 @@ rules_sources = \
6700 AvoidConstructorsInStaticTypesRule.cs \
6701 AvoidFloatingPointEqualityRule.cs \
6702 AvoidMethodsWithSideEffectsInConditionalCodeRule.cs \
6703+ DeclareEventsExplicitlyRule.cs \
6704 DoNotRecurseInEqualityRule.cs \
6705 BadRecursiveInvocationRule.cs \
6706 CallingEqualsWithNullArgRule.cs \
6707@@ -29,6 +30,9 @@ rules_sources = \
6708 ReviewUselessControlFlowRule.cs \
6709 ReviewUseOfInt64BitsToDoubleRule.cs \
6710 ReviewUseOfModuloOneOnIntegersRule.cs \
6711+ TypesShouldBeDisposableBaseRule.cs \
6712+ TypesWithDisposableFieldsShouldBeDisposableRule.cs \
6713+ TypesWithNativeFieldsShouldBeDisposableRule.cs \
6714 UseNoInliningWithGetCallingAssemblyRule.cs \
6715 UseValueInPropertySetterRule.cs
6716
6717@@ -50,6 +54,7 @@ tests_sources = \
6718 AvoidConstructorsInStaticTypesTest.cs \
6719 AvoidFloatingPointEqualityTest.cs \
6720 AvoidMethodsWithSideEffectsInConditionalCodeTest.cs \
6721+ DeclareEventsExplicitlyTest.cs \
6722 DoNotRecurseInEqualityTest.cs \
6723 BadRecursiveInvocationTest.cs \
6724 CallingEqualsWithNullArgTest.cs \
6725@@ -73,5 +78,7 @@ tests_sources = \
6726 ReviewUselessControlFlowTest.cs \
6727 ReviewUseOfInt64BitsToDoubleTest.cs \
6728 ReviewUseOfModuloOneOnIntegersTest.cs \
6729+ TypesWithDisposableFieldsShouldBeDisposableTest.cs \
6730+ TypesWithNativeFieldsShouldBeDisposableTest.cs \
6731 UseNoInliningWithGetCallingAssemblyTest.cs \
6732 UseValueInPropertySetterTest.cs
6733diff --git a/gendarme/rules/Gendarme.Rules.Correctness/MethodCanBeMadeStaticRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/MethodCanBeMadeStaticRule.cs
6734index bab18df..b760958 100644
6735--- a/gendarme/rules/Gendarme.Rules.Correctness/MethodCanBeMadeStaticRule.cs
6736+++ b/gendarme/rules/Gendarme.Rules.Correctness/MethodCanBeMadeStaticRule.cs
6737@@ -114,7 +114,7 @@ namespace Gendarme.Rules.Correctness {
6738
6739 // methods with [Conditional] can be empty (not using 'this') IL-wise but not source-wise, ignore them
6740 if (method.HasCustomAttributes) {
6741- if (method.CustomAttributes.ContainsType ("System.Diagnostics.ConditionalAttribute"))
6742+ if (method.HasAttribute ("System.Diagnostics", "ConditionalAttribute"))
6743 return RuleResult.DoesNotApply;
6744 }
6745
6746@@ -130,7 +130,7 @@ namespace Gendarme.Rules.Correctness {
6747 foreach (Instruction instr in method.Body.Instructions) {
6748 if (instr.OpCode.Code == Code.Ldarg) {
6749 ParameterDefinition pd = (instr.Operand as ParameterDefinition);
6750- if (pd.GetSequence () == 0)
6751+ if (pd.Index == -1)
6752 return RuleResult.Success;
6753 }
6754 }
6755diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectArgumentsToFormattingMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectArgumentsToFormattingMethodsRule.cs
6756index f545495..92b5753 100644
6757--- a/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectArgumentsToFormattingMethodsRule.cs
6758+++ b/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectArgumentsToFormattingMethodsRule.cs
6759@@ -28,10 +28,11 @@
6760 //
6761
6762 using System;
6763-using System.IO;
6764-using System.Resources;
6765 using System.Collections;
6766 using System.Collections.Generic;
6767+using System.Globalization;
6768+using System.IO;
6769+using System.Resources;
6770
6771 using Mono.Cecil;
6772 using Mono.Cecil.Cil;
6773@@ -115,7 +116,7 @@ namespace Gendarme.Rules.Correctness {
6774 {
6775 IList<Resource> resources = ad.MainModule.Resources;
6776 foreach (EmbeddedResource resource in resources)
6777- if (resourceClassName.Equals (resource.Name))
6778+ if (resourceClassName == resource.Name)
6779 return resource;
6780 return null;
6781 }
6782@@ -131,7 +132,7 @@ namespace Gendarme.Rules.Correctness {
6783 return null;
6784
6785 AssemblyDefinition ad = md.GetAssembly ();
6786- string resourceClassName = md.DeclaringType.FullName + ".resources";
6787+ string resourceClassName = md.DeclaringType.GetFullName () + ".resources";
6788 EmbeddedResource resource = GetEmbeddedResource (ad, resourceClassName);
6789 if (resource == null)
6790 return null;
6791@@ -242,13 +243,13 @@ namespace Gendarme.Rules.Correctness {
6792 // String.Format (string, object, object, object) -> elementsPushed = 3
6793 // String.Format (string, object[]) -> compute
6794 // String.Format (IFormatProvider, string, object[]) -> compute
6795- if (pdc [nbParameters - 1].ParameterType.FullName != "System.Object") {
6796+ if (!pdc [nbParameters - 1].ParameterType.IsNamed ("System", "Object")) {
6797 // If we cannot determine the array size, we succeed (well we don't fail/report)
6798 if (!TryComputeArraySize (call, method, nbParameters - 1, out elementsPushed))
6799 return;
6800
6801 // String.Format (IFormatProvider, string, object[]) -> formatPosition = 1
6802- if (pdc [0].ParameterType.FullName != "System.String")
6803+ if (!pdc [0].ParameterType.IsNamed ("System", "String"))
6804 formatPosition = 1;
6805 }
6806
6807@@ -266,12 +267,19 @@ namespace Gendarme.Rules.Correctness {
6808 }
6809
6810 if (expectedParameters < elementsPushed) {
6811- Runner.Report (method, call, Severity.Medium, Confidence.Normal, String.Format ("Extra parameters are provided to String.Format, {0} provided but only {1} expected", elementsPushed, expectedParameters));
6812+ string msg = String.Format (CultureInfo.InvariantCulture,
6813+ "Extra parameters are provided to String.Format, {0} provided but only {1} expected",
6814+ elementsPushed, expectedParameters);
6815+ Runner.Report (method, call, Severity.Medium, Confidence.Normal, msg);
6816 return;
6817 }
6818
6819- if (elementsPushed < expectedParameters)
6820- Runner.Report (method, call, Severity.Critical, Confidence.Normal, String.Format ("The String.Format method is expecting {0} parameters, but only {1} are found.", expectedParameters, elementsPushed));
6821+ if (elementsPushed < expectedParameters) {
6822+ string msg = String.Format (CultureInfo.InvariantCulture,
6823+ "The String.Format method is expecting {0} parameters, but only {1} are found.",
6824+ expectedParameters, elementsPushed);
6825+ Runner.Report (method, call, Severity.Critical, Confidence.Normal, msg);
6826+ }
6827 }
6828
6829 public RuleResult CheckMethod (MethodDefinition method)
6830@@ -289,7 +297,7 @@ namespace Gendarme.Rules.Correctness {
6831 continue;
6832
6833 MethodReference mr = (instruction.Operand as MethodReference);
6834- if (formatSignature.Matches (mr) && (mr.DeclaringType.FullName == "System.String"))
6835+ if (formatSignature.Matches (mr) && mr.DeclaringType.IsNamed ("System", "String"))
6836 CheckCallToFormatter (instruction, method);
6837 }
6838
6839diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectRegexPatternRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectRegexPatternRule.cs
6840index 89eb1e8..ebaa25e 100644
6841--- a/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectRegexPatternRule.cs
6842+++ b/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectRegexPatternRule.cs
6843@@ -27,6 +27,7 @@
6844 // THE SOFTWARE.
6845
6846 using System;
6847+using System.Globalization;
6848
6849 using Mono.Cecil;
6850 using Mono.Cecil.Cil;
6851@@ -91,20 +92,23 @@ namespace Gendarme.Rules.Correctness {
6852
6853 static OpCodeBitmask callsAndNewobjBitmask = BuildCallsAndNewobjOpCodeBitmask ();
6854
6855- const string RegexClass = "System.Text.RegularExpressions.Regex";
6856- const string ValidatorClass = "System.Configuration.RegexStringValidator";
6857-
6858 public override void Initialize (IRunner runner)
6859 {
6860 base.Initialize (runner);
6861
6862 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
6863- bool usingRegexClass = e.CurrentAssembly.Name.Name == "System"
6864- || e.CurrentModule.HasTypeReference (RegexClass);
6865- bool usingValidatorClass = e.CurrentModule.Runtime >= TargetRuntime.Net_2_0
6866- && (e.CurrentAssembly.Name.Name == "System.Configuration"
6867- || e.CurrentModule.HasTypeReference (ValidatorClass));
6868- Active = usingRegexClass | usingValidatorClass;
6869+ string assembly_name = e.CurrentAssembly.Name.Name;
6870+ bool usingRegexClass = (assembly_name == "System");
6871+ bool usingValidatorClass = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0) && (assembly_name == "System.Configuration");
6872+ // if we're not analyzing System.dll or System.Configuration.dll then check if we're using them
6873+ if (!usingRegexClass && !usingValidatorClass) {
6874+ Active = e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
6875+ return tr.IsNamed ("System.Text.RegularExpressions", "Regex") ||
6876+ tr.IsNamed ("System.Configuration", "RegexStringValidator");
6877+ });
6878+ } else {
6879+ Active = true;
6880+ }
6881 };
6882 }
6883
6884@@ -127,7 +131,7 @@ namespace Gendarme.Rules.Correctness {
6885 return CheckPattern (method, ins, (string) ld.Operand, confidence);
6886 case Code.Ldsfld:
6887 FieldReference f = (FieldReference) ld.Operand;
6888- if (f.Name != "Empty" || f.DeclaringType.FullName != "System.String")
6889+ if (f.Name != "Empty" || !f.DeclaringType.IsNamed ("System", "String"))
6890 return false;
6891 return CheckPattern (method, ins, null, confidence);
6892 case Code.Ldnull:
6893@@ -149,7 +153,8 @@ namespace Gendarme.Rules.Correctness {
6894 } catch (Exception e) {
6895 /* potential set of exceptions is not well documented and potentially changes with regarts to
6896 different runtime and/or runtime version. */
6897- string msg = string.Format ("Pattern '{0}' is invalid. Reason: {1}", pattern, e.Message);
6898+ string msg = String.Format (CultureInfo.InvariantCulture,
6899+ "Pattern '{0}' is invalid. Reason: {1}", pattern, e.Message);
6900 Runner.Report (method, ins, Severity.High, confidence, msg);
6901 return false;
6902 }
6903@@ -161,8 +166,9 @@ namespace Gendarme.Rules.Correctness {
6904 return;
6905 if (!call.HasParameters)
6906 return;
6907- string tname = call.DeclaringType.FullName;
6908- if (tname != RegexClass && tname != ValidatorClass)
6909+
6910+ TypeReference type = call.DeclaringType;
6911+ if (!type.IsNamed ("System.Text.RegularExpressions", "Regex") && !type.IsNamed ("System.Configuration", "RegexStringValidator"))
6912 return;
6913
6914 MethodDefinition mdef = call.Resolve ();
6915@@ -174,8 +180,8 @@ namespace Gendarme.Rules.Correctness {
6916
6917 foreach (ParameterDefinition p in mdef.Parameters) {
6918 string pname = p.Name;
6919- if ((pname == "pattern" || pname == "regex") && p.ParameterType.FullName == "System.String") {
6920- Instruction ld = ins.TraceBack (method, -(call.HasThis ? 0 : -1 + p.GetSequence ()));
6921+ if ((pname == "pattern" || pname == "regex") && p.ParameterType.IsNamed ("System", "String")) {
6922+ Instruction ld = ins.TraceBack (method, -(call.HasThis ? 0 : p.Index));
6923 if (ld != null)
6924 CheckArguments (method, ins, ld);
6925 return;
6926diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXPathExpressionRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXPathExpressionRule.cs
6927index 68d4cb4..770e78d 100644
6928--- a/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXPathExpressionRule.cs
6929+++ b/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXPathExpressionRule.cs
6930@@ -25,6 +25,7 @@
6931 // THE SOFTWARE.
6932
6933 using System;
6934+using System.Globalization;
6935 using System.Xml;
6936 using System.Xml.XPath;
6937
6938@@ -74,10 +75,6 @@ namespace Gendarme.Rules.Correctness {
6939 [EngineDependency (typeof (OpCodeEngine))]
6940 public sealed class ProvideValidXPathExpressionRule : Rule, IMethodRule {
6941
6942- const string XmlNodeClass = "System.Xml.XmlNode";
6943- const string XPathNavigatorClass = "System.Xml.XPath.XPathNavigator";
6944- const string XPathExpressionClass = "System.Xml.XPath.XPathExpression";
6945-
6946 public override void Initialize (IRunner runner)
6947 {
6948 base.Initialize (runner);
6949@@ -105,7 +102,7 @@ namespace Gendarme.Rules.Correctness {
6950 break;
6951 case Code.Ldsfld:
6952 FieldReference f = (FieldReference) ld.Operand;
6953- if (f.Name == "Empty" && f.DeclaringType.FullName == "System.String")
6954+ if (f.Name == "Empty" && f.DeclaringType.IsNamed ("System", "String"))
6955 CheckString (method, ins, null);
6956 break;
6957 case Code.Ldnull:
6958@@ -124,7 +121,8 @@ namespace Gendarme.Rules.Correctness {
6959 try {
6960 XPathExpression.Compile (expression);
6961 } catch (XPathException e) {
6962- string msg = string.Format ("Expression '{0}' is invalid. Details: {1}", expression, e.Message);
6963+ string msg = String.Format (CultureInfo.InvariantCulture,
6964+ "Expression '{0}' is invalid. Details: {1}", expression, e.Message);
6965 Runner.Report (method, ins, Severity.High, Confidence.High, msg);
6966 }
6967 }
6968@@ -137,11 +135,11 @@ namespace Gendarme.Rules.Correctness {
6969 switch (mref.Name) {
6970 case "Compile":
6971 TypeReference tr = mref.DeclaringType;
6972- if (tr.FullName == XPathExpressionClass || tr.Inherits (XPathNavigatorClass))
6973+ if (tr.IsNamed ("System.Xml.XPath", "XPathExpression") || tr.Inherits ("System.Xml.XPath", "XPathNavigator"))
6974 CheckString (method, ins, GetFirstArgumentOffset (mref));
6975 break;
6976 case "SelectNodes":
6977- if (mref.DeclaringType.FullName == XmlNodeClass)
6978+ if (mref.DeclaringType.IsNamed ("System.Xml", "XmlNode"))
6979 CheckString (method, ins, -1);
6980 break;
6981 case "Evaluate":
6982@@ -150,7 +148,7 @@ namespace Gendarme.Rules.Correctness {
6983 break;
6984 case "SelectSingleNode":
6985 CheckXPathNavigatorString (method, ins, mref);
6986- if (mref.DeclaringType.FullName == XmlNodeClass)
6987+ if (mref.DeclaringType.IsNamed ("System.Xml", "XmlNode"))
6988 CheckString (method, ins, -1);
6989 break;
6990 }
6991@@ -158,8 +156,8 @@ namespace Gendarme.Rules.Correctness {
6992
6993 void CheckXPathNavigatorString (MethodDefinition method, Instruction ins, MethodReference mref)
6994 {
6995- if (mref.Parameters [0].ParameterType.FullName == "System.String") {
6996- if (mref.DeclaringType.Inherits (XPathNavigatorClass))
6997+ if (mref.Parameters [0].ParameterType.IsNamed ("System", "String")) {
6998+ if (mref.DeclaringType.Inherits ("System.Xml.XPath", "XPathNavigator"))
6999 CheckString (method, ins, -1);
7000 }
7001 }
7002diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXmlStringRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXmlStringRule.cs
7003index 921e71a..36e7c64 100644
7004--- a/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXmlStringRule.cs
7005+++ b/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXmlStringRule.cs
7006@@ -26,6 +26,7 @@
7007
7008 using System;
7009 using System.Collections.Generic;
7010+using System.Globalization;
7011 using System.Xml;
7012 using System.Xml.XPath;
7013
7014@@ -77,10 +78,6 @@ namespace Gendarme.Rules.Correctness {
7015 [EngineDependency (typeof (OpCodeEngine))]
7016 public sealed class ProvideValidXmlStringRule : Rule, IMethodRule {
7017
7018- const string XmlDocumentClass = "System.Xml.XmlDocument";
7019- const string XmlNodeClass = "System.Xml.XmlNode";
7020- const string XPathNavigatorClass = "System.Xml.XPath.XPathNavigator";
7021-
7022 public override void Initialize (IRunner runner)
7023 {
7024 base.Initialize (runner);
7025@@ -108,7 +105,7 @@ namespace Gendarme.Rules.Correctness {
7026 break;
7027 case Code.Ldsfld:
7028 FieldReference f = (FieldReference) ld.Operand;
7029- if (f.Name == "Empty" && f.DeclaringType.FullName == "System.String")
7030+ if (f.Name == "Empty" && f.DeclaringType.IsNamed ("System", "String"))
7031 CheckString (method, ins, null);
7032 break;
7033 case Code.Ldnull:
7034@@ -127,7 +124,8 @@ namespace Gendarme.Rules.Correctness {
7035 try {
7036 (new XmlDocument ()).LoadXml (xml);
7037 } catch (XmlException e) {
7038- string msg = string.Format ("XML string '{0}' is invalid. Details: {1}", xml, e.Message);
7039+ string msg = String.Format (CultureInfo.InvariantCulture,
7040+ "XML string '{0}' is invalid. Details: {1}", xml, e.Message);
7041 Runner.Report (method, ins, Severity.High, Confidence.High, msg);
7042 }
7043 }
7044@@ -139,13 +137,13 @@ namespace Gendarme.Rules.Correctness {
7045
7046 switch (mref.Name) {
7047 case "LoadXml":
7048- if (mref.DeclaringType.FullName == XmlDocumentClass)
7049+ if (mref.DeclaringType.IsNamed ("System.Xml", "XmlDocument"))
7050 CheckString (method, ins, -1);
7051 break;
7052 case "set_InnerXml":
7053 case "set_OuterXml":
7054 TypeReference tr = mref.DeclaringType;
7055- if (tr.Inherits (XmlNodeClass) || tr.Inherits (XPathNavigatorClass))
7056+ if (tr.Inherits ("System.Xml", "XmlNode") || tr.Inherits ("System.Xml.XPath", "XPathNavigator"))
7057 CheckString (method, ins, -1);
7058 break;
7059 case "AppendChild":
7060@@ -154,8 +152,8 @@ namespace Gendarme.Rules.Correctness {
7061 case "InsertBefore":
7062 IList<ParameterDefinition> pdc = mref.Parameters;
7063 if (pdc.Count == 1
7064- && pdc [0].ParameterType.FullName == "System.String"
7065- && mref.DeclaringType.Inherits (XPathNavigatorClass))
7066+ && pdc [0].ParameterType.IsNamed ("System", "String")
7067+ && mref.DeclaringType.Inherits ("System.Xml.XPath", "XPathNavigator"))
7068 CheckString (method, ins, -1);
7069 break;
7070 }
7071diff --git a/gendarme/rules/Gendarme.Rules.Correctness/README.md b/gendarme/rules/Gendarme.Rules.Correctness/README.md
7072new file mode 100644
7073index 0000000..b7a8fc5
7074--- /dev/null
7075+++ b/gendarme/rules/Gendarme.Rules.Correctness/README.md
7076@@ -0,0 +1,9 @@
7077+# Gendarme.Rules.Correctness Rules
7078+
7079+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Correctness(git)]] pages.
7080+
7081+
7082+## Feedback
7083+
7084+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
7085+
7086diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ReviewDoubleAssignmentRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ReviewDoubleAssignmentRule.cs
7087index 79b290b..272f86e 100644
7088--- a/gendarme/rules/Gendarme.Rules.Correctness/ReviewDoubleAssignmentRule.cs
7089+++ b/gendarme/rules/Gendarme.Rules.Correctness/ReviewDoubleAssignmentRule.cs
7090@@ -27,6 +27,7 @@
7091 //
7092
7093 using System;
7094+using System.Globalization;
7095
7096 using Mono.Cecil;
7097 using Mono.Cecil.Cil;
7098@@ -113,7 +114,7 @@ namespace Gendarme.Rules.Correctness {
7099 if (stfld.TraceBack (method).GetOperand (method) != next.TraceBack (method).GetOperand (method))
7100 return String.Empty;
7101
7102- return String.Format ("Instance field '{0}' on same variable '{1}'.", fd1.Name, vd1.Name);
7103+ return String.Format (CultureInfo.InvariantCulture, "Instance field '{0}' on same variable '{1}'.", fd1.Name, vd1.Name);
7104 }
7105
7106 static string CheckDoubleAssignement (MethodDefinition method, Instruction ins, Instruction next)
7107@@ -130,7 +131,7 @@ namespace Gendarme.Rules.Correctness {
7108 if (fd1.MetadataToken.RID != fd2.MetadataToken.RID)
7109 return String.Empty;
7110
7111- return String.Format ("Static field '{0}'.", fd1.Name);
7112+ return String.Format (CultureInfo.InvariantCulture, "Static field '{0}'.", fd1.Name);
7113 } else if (ins.IsStoreLocal ()) {
7114 // for a local variable the pattern is
7115 // DUP, STLOC, STLOC
7116@@ -141,7 +142,7 @@ namespace Gendarme.Rules.Correctness {
7117 if (vd1.Index != vd2.Index)
7118 return String.Empty;
7119
7120- return String.Format ("Local variable '{0}'.", vd1.Name);
7121+ return String.Format (CultureInfo.InvariantCulture, "Local variable '{0}'.", vd1.Name);
7122 } else if (next.OpCode.Code == Code.Stfld) {
7123 // instance fields are a bit more complex...
7124 return CheckDoubleAssignementOnInstanceFields (method, ins, next);
7125diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ReviewInconsistentIdentityRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ReviewInconsistentIdentityRule.cs
7126index a79b354..67b4fc6 100644
7127--- a/gendarme/rules/Gendarme.Rules.Correctness/ReviewInconsistentIdentityRule.cs
7128+++ b/gendarme/rules/Gendarme.Rules.Correctness/ReviewInconsistentIdentityRule.cs
7129@@ -125,7 +125,7 @@ namespace Gendarme.Rules.Correctness {
7130
7131 private void GetMethods (TypeReference type)
7132 {
7133- string full_name = type.FullName;
7134+ string full_name = type.GetFullName ();
7135 args1 [0] = full_name;
7136 AddMethod (type.GetMethod (MethodSignatures.Equals));
7137 AddMethod (type.GetMethod ("Equals", "System.Boolean", args1));
7138@@ -349,7 +349,7 @@ namespace Gendarme.Rules.Correctness {
7139
7140 Log.WriteLine (this);
7141 Log.WriteLine (this, "------------------------------------");
7142- Log.WriteLine (this, type.FullName);
7143+ Log.WriteLine (this, type);
7144
7145 GetMethods (type);
7146 if (methods.Count > 0) {
7147diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ReviewSelfAssignmentRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ReviewSelfAssignmentRule.cs
7148index 5d359cc..127d7c7 100644
7149--- a/gendarme/rules/Gendarme.Rules.Correctness/ReviewSelfAssignmentRule.cs
7150+++ b/gendarme/rules/Gendarme.Rules.Correctness/ReviewSelfAssignmentRule.cs
7151@@ -27,6 +27,7 @@
7152 //
7153
7154 using System;
7155+using System.Globalization;
7156
7157 using Mono.Cecil;
7158 using Mono.Cecil.Cil;
7159@@ -122,8 +123,8 @@ namespace Gendarme.Rules.Correctness {
7160 if ((field != null) && (field == next.GetField ())) {
7161 // instance fields need extra comparison using method
7162 if (isStatic || Compare (next, ins, method)) {
7163- string msg = String.Format ("{0} field '{1}' of type '{2}'.",
7164- isStatic ? "Static" : "Instance", field.Name, field.FieldType.FullName);
7165+ string msg = String.Format (CultureInfo.InvariantCulture, "{0} field '{1}' of type '{2}'.",
7166+ isStatic ? "Static" : "Instance", field.Name, field.FieldType.GetFullName ());
7167 Runner.Report (method, ins, Severity.Medium, Confidence.Normal, msg);
7168 }
7169 }
7170@@ -158,14 +159,15 @@ namespace Gendarme.Rules.Correctness {
7171 if (variable == ins.GetVariable (method)) {
7172 // the compiler often introduce it's own variable
7173 if (!variable.Name.StartsWith ("V_"))
7174- msg = String.Format ("Variable '{0}' of type '{1}'.", variable.Name, variable.VariableType.FullName);
7175+ msg = String.Format ("Variable '{0}' of type '{1}'.", variable.Name, variable.VariableType.GetFullName ());
7176 }
7177 #endif
7178 } else if (ins.IsLoadArgument () && next.IsStoreArgument ()) {
7179 ParameterDefinition parameter = next.GetParameter (method);
7180 if (parameter == ins.GetParameter (method)) {
7181- string msg = String.Format ("Parameter '{0}' of type '{1}'.",
7182- parameter.Name, parameter.ParameterType.FullName);
7183+ string msg = String.Format (CultureInfo.InvariantCulture,
7184+ "Parameter '{0}' of type '{1}'.",
7185+ parameter.Name, parameter.ParameterType.GetFullName ());
7186 Runner.Report (method, ins, Severity.Medium, Confidence.Normal, msg);
7187 }
7188 }
7189diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ReviewUseOfInt64BitsToDoubleRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ReviewUseOfInt64BitsToDoubleRule.cs
7190index 18dbae1..11656ca 100644
7191--- a/gendarme/rules/Gendarme.Rules.Correctness/ReviewUseOfInt64BitsToDoubleRule.cs
7192+++ b/gendarme/rules/Gendarme.Rules.Correctness/ReviewUseOfInt64BitsToDoubleRule.cs
7193@@ -75,20 +75,26 @@ namespace Gendarme.Rules.Correctness {
7194 // Conv_I8, Conv_U8, Conv_Ovf_I8, Conv_Ovf_I8_Un, Conv_Ovf_U8, Conv_Ovf_U8_Un
7195 private static OpCodeBitmask Convert8 = new OpCodeBitmask (0x0, 0x220000000000, 0x60000000044, 0x0);
7196
7197- private const string BitConverter = "System.BitConverter";
7198-
7199 public override void Initialize (IRunner runner)
7200 {
7201 base.Initialize (runner);
7202
7203- // if the module does not reference System.BitConverter then no
7204- // method inside it will be calling any BitConverter.Int64BitsToDouble method
7205 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
7206- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
7207- e.CurrentModule.HasTypeReference (BitConverter);
7208+ // if the module does not reference System.BitConverter.Int64BitsToDouble then no
7209+ // then there's no point in enabling the rule
7210+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
7211+ e.CurrentModule.AnyMemberReference ((MemberReference mr) => {
7212+ return IsInt64BitsToDouble (mr);
7213+ })
7214+ );
7215 };
7216 }
7217
7218+ static bool IsInt64BitsToDouble (MemberReference method)
7219+ {
7220+ return method.IsNamed ("System", "BitConverter", "Int64BitsToDouble");
7221+ }
7222+
7223 public RuleResult CheckMethod (MethodDefinition method)
7224 {
7225 if (!method.HasBody)
7226@@ -106,10 +112,7 @@ namespace Gendarme.Rules.Correctness {
7227 if (ins.OpCode.FlowControl != FlowControl.Call)
7228 continue;
7229
7230- MethodReference mr = (ins.Operand as MethodReference);
7231- if (mr.Name != "Int64BitsToDouble")
7232- continue;
7233- if (mr.DeclaringType.FullName != BitConverter)
7234+ if (!IsInt64BitsToDouble (ins.Operand as MethodReference))
7235 continue;
7236
7237 // if the previous call convert a value into a long (int64)
7238diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/BadRecursiveInvocationTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/BadRecursiveInvocationTest.cs
7239index 74cd0c4..e7fcd69 100644
7240--- a/gendarme/rules/Gendarme.Rules.Correctness/Test/BadRecursiveInvocationTest.cs
7241+++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/BadRecursiveInvocationTest.cs
7242@@ -374,5 +374,24 @@ namespace Test.Rules.Correctness {
7243 {
7244 AssertRuleSuccess<BadRec> ("StaticGoodOverload", new Type [] { typeof (object) });
7245 }
7246+
7247+ class Array {
7248+
7249+ public virtual void SetProperty (string name, object value)
7250+ {
7251+ Console.WriteLine ("{0}: {1}", name, value);
7252+ }
7253+
7254+ internal virtual void SetProperty (string name, object [] args)
7255+ {
7256+ SetProperty (name, args [0]);
7257+ }
7258+ }
7259+
7260+ [Test]
7261+ public void ArrayOverload ()
7262+ {
7263+ AssertRuleSuccess<Array> ("SetProperty", new Type [] { typeof (string), typeof (object[]) });
7264+ }
7265 }
7266 }
7267diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/DeclareEventsExplicitlyTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/DeclareEventsExplicitlyTest.cs
7268new file mode 100644
7269index 0000000..8de18ab
7270--- /dev/null
7271+++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/DeclareEventsExplicitlyTest.cs
7272@@ -0,0 +1,82 @@
7273+//
7274+// Unit tests for DeclareEventsExplicitlyRule
7275+//
7276+// Authors:
7277+// Sebastien Pouliot <sebastien@ximian.com>
7278+//
7279+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
7280+//
7281+// Permission is hereby granted, free of charge, to any person obtaining
7282+// a copy of this software and associated documentation files (the
7283+// "Software"), to deal in the Software without restriction, including
7284+// without limitation the rights to use, copy, modify, merge, publish,
7285+// distribute, sublicense, and/or sell copies of the Software, and to
7286+// permit persons to whom the Software is furnished to do so, subject to
7287+// the following conditions:
7288+//
7289+// The above copyright notice and this permission notice shall be
7290+// included in all copies or substantial portions of the Software.
7291+//
7292+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
7293+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7294+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
7295+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
7296+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
7297+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
7298+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7299+//
7300+
7301+using System;
7302+
7303+using Gendarme.Rules.Correctness;
7304+using NUnit.Framework;
7305+
7306+using Test.Rules.Definitions;
7307+using Test.Rules.Fixtures;
7308+
7309+namespace Tests.Rules.Correctness {
7310+
7311+ [TestFixture]
7312+ public class DeclareEventsExplicitlyTest : TypeRuleTestFixture<DeclareEventsExplicitlyRule> {
7313+
7314+ struct StructInstanceCorrect {
7315+ public event EventHandler<EventArgs> MyEvent;
7316+ }
7317+
7318+ struct StructInstanceIncorrect {
7319+ public EventHandler<EventArgs> MyEvent;
7320+ }
7321+
7322+ class GenericClassStaticCorrect {
7323+ public static event EventHandler<EventArgs> MyEvent;
7324+ }
7325+
7326+ class GenericClassStaticIncorect {
7327+ public static EventHandler<EventArgs> MyEvent;
7328+ public event EventHandler<EventArgs> MyEvent2;
7329+ }
7330+
7331+ [Test]
7332+ public void DoesNotApply ()
7333+ {
7334+ AssertRuleDoesNotApply (SimpleTypes.Class);
7335+ AssertRuleDoesNotApply (SimpleTypes.Enum);
7336+ // interface cannot define fields
7337+ AssertRuleDoesNotApply (SimpleTypes.Interface);
7338+ }
7339+
7340+ [Test]
7341+ public void Success ()
7342+ {
7343+ AssertRuleSuccess<StructInstanceCorrect> ();
7344+ AssertRuleSuccess<GenericClassStaticCorrect> ();
7345+ }
7346+
7347+ [Test]
7348+ public void Failure ()
7349+ {
7350+ AssertRuleFailure<StructInstanceIncorrect> (1);
7351+ AssertRuleFailure<GenericClassStaticIncorect> (1);
7352+ }
7353+ }
7354+}
7355diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/EnsureLocalDisposalTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/EnsureLocalDisposalTest.cs
7356index ebb9a01..e375d1d 100644
7357--- a/gendarme/rules/Gendarme.Rules.Correctness/Test/EnsureLocalDisposalTest.cs
7358+++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/EnsureLocalDisposalTest.cs
7359@@ -45,15 +45,12 @@ namespace Test.Rules.Correctness {
7360
7361 StreamReader StreamReader { get; set; }
7362
7363- string DoesNotApply1 () { //no call/newobj/stloc
7364+ string DoesNotApply1 ()
7365+ {
7366+ //no call/newobj/stloc
7367 return foo;
7368 }
7369
7370- StreamReader DoesNotApply2 () { //returns IDisposable
7371- var sr = new StreamReader ("bar.xml");
7372- return sr;
7373- }
7374-
7375 string Success0 () {
7376 var o = new object ();
7377 return o.ToString ();
7378@@ -214,12 +211,6 @@ namespace Test.Rules.Correctness {
7379 }
7380
7381 [Test]
7382- public void DoesNotApply2 ()
7383- {
7384- AssertRuleDoesNotApply<DisposalCases> ("DoesNotApply2");
7385- }
7386-
7387- [Test]
7388 public void Success0 ()
7389 {
7390 AssertRuleSuccess<DisposalCases> ("Success0");
7391@@ -300,7 +291,7 @@ namespace Test.Rules.Correctness {
7392 [Test]
7393 public void Failure3 ()
7394 {
7395- AssertRuleFailure<DisposalCases> ("Failure3", 2);
7396+ AssertRuleFailure<DisposalCases> ("Failure3", 1);
7397 }
7398
7399 [Test]
7400@@ -382,11 +373,71 @@ namespace Test.Rules.Correctness {
7401 [Test]
7402 public void FluentApi ()
7403 {
7404- AssertRuleFailure<EnsureLocalDisposalTest> ("FluentTestCase", 3);
7405- // confidence is lower (normal instead of high) for fluent-like API
7406- Assert.AreEqual (Confidence.Normal, Runner.Defects [0].Confidence, "0");
7407- Assert.AreEqual (Confidence.Normal, Runner.Defects [1].Confidence, "1");
7408- Assert.AreEqual (Confidence.Normal, Runner.Defects [2].Confidence, "2");
7409+ AssertRuleSuccess<EnsureLocalDisposalTest> ("FluentTestCase");
7410+ }
7411+
7412+ // adapted (without locals variants) from https://bugzilla.novell.com/show_bug.cgi?id=666403
7413+
7414+ void OutParameter1 (out StreamReader stream)
7415+ {
7416+ var new_stream = new StreamReader ("baz.xml"); //out param
7417+ stream = new_stream;
7418+ }
7419+
7420+ bool OutParameter2 (out StreamReader stream)
7421+ {
7422+ stream = new StreamReader ("baz.xml"); //out param, no locals
7423+ return true;
7424+ }
7425+
7426+ [Test]
7427+ public void OutParameters ()
7428+ {
7429+ AssertRuleSuccess<EnsureLocalDisposalTest> ("OutParameter1");
7430+ AssertRuleSuccess<EnsureLocalDisposalTest> ("OutParameter2");
7431+ }
7432+
7433+ class SomeClassThatContainsADisposableProperty {
7434+ public StreamReader Reader { get; set; }
7435+ }
7436+
7437+ void OtherInstanceProperty1 (SomeClassThatContainsADisposableProperty someObj)
7438+ {
7439+ var reader = new StreamReader ("foobaz.xml");
7440+ someObj.Reader = reader; //property in param
7441+ }
7442+
7443+ void OtherInstanceProperty2 (SomeClassThatContainsADisposableProperty someObj)
7444+ {
7445+ someObj.Reader = new StreamReader ("foobaz.xml"); //property in param, no locals
7446+ }
7447+
7448+ [Test]
7449+ public void OtherInstance ()
7450+ {
7451+ AssertRuleSuccess<EnsureLocalDisposalTest> ("OtherInstanceProperty1");
7452+ AssertRuleSuccess<EnsureLocalDisposalTest> ("OtherInstanceProperty2");
7453+ }
7454+
7455+ StreamReader ReturnIDisposable1 ()
7456+ {
7457+ var ret = new StreamReader ("baz.xml"); //return value
7458+ return ret;
7459+ }
7460+
7461+ StreamReader ReturnIDisposable2 ()
7462+ {
7463+ return new StreamReader ("baz.xml"); //return value, no locals
7464+ }
7465+
7466+ [Test]
7467+ public void ReturnValue ()
7468+ {
7469+ // csc 10 (without /o optimize) will fail this as it introduce extra compiler generated locals
7470+#if __MonoCS__
7471+ AssertRuleSuccess<EnsureLocalDisposalTest> ("ReturnIDisposable1");
7472+#endif
7473+ AssertRuleSuccess<EnsureLocalDisposalTest> ("ReturnIDisposable2");
7474 }
7475 }
7476 }
7477diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/Resource.Designer.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/Resource.Designer.cs
7478index ec1d9e5..e55ddeb 100644
7479--- a/gendarme/rules/Gendarme.Rules.Correctness/Test/Resource.Designer.cs
7480+++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/Resource.Designer.cs
7481@@ -1,7 +1,7 @@
7482-//------------------------------------------------------------------------------
7483+//------------------------------------------------------------------------------
7484 // <auto-generated>
7485 // This code was generated by a tool.
7486-// Runtime Version:2.0.50727.4927
7487+// Runtime Version:4.0.30319.1
7488 //
7489 // Changes to this file may cause incorrect behavior and will be lost if
7490 // the code is regenerated.
7491@@ -19,7 +19,7 @@ namespace Tests.Rules.Correctness {
7492 // class via a tool like ResGen or Visual Studio.
7493 // To add or remove a member, edit your .ResX file then rerun ResGen
7494 // with the /str option, or rebuild your VS project.
7495- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
7496+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
7497 [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
7498 [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
7499 internal class Resource {
7500diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/Tests.Rules.Correctness.csproj b/gendarme/rules/Gendarme.Rules.Correctness/Test/Tests.Rules.Correctness.csproj
7501index d5e9ea2..d3e97ec 100755
7502--- a/gendarme/rules/Gendarme.Rules.Correctness/Test/Tests.Rules.Correctness.csproj
7503+++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/Tests.Rules.Correctness.csproj
7504@@ -1,5 +1,5 @@
7505 <?xml version="1.0" encoding="utf-8"?>\r
7506-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
7507+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
7508 <PropertyGroup>\r
7509 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
7510 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
7511@@ -12,9 +12,11 @@
7512 <AssemblyName>Tests.Rules.Correctness</AssemblyName>\r
7513 <FileUpgradeFlags>\r
7514 </FileUpgradeFlags>\r
7515- <OldToolsVersion>2.0</OldToolsVersion>\r
7516+ <OldToolsVersion>3.5</OldToolsVersion>\r
7517 <UpgradeBackupLocation>\r
7518 </UpgradeBackupLocation>\r
7519+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
7520+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
7521 <PublishUrl>http://localhost/Tests.Rules.Correctness/</PublishUrl>\r
7522 <Install>true</Install>\r
7523 <InstallFrom>Web</InstallFrom>\r
7524@@ -27,10 +29,9 @@
7525 <MapFileExtensions>true</MapFileExtensions>\r
7526 <ApplicationRevision>0</ApplicationRevision>\r
7527 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
7528- <IsWebBootstrapper>true</IsWebBootstrapper>\r
7529 <UseApplicationTrust>false</UseApplicationTrust>\r
7530 <BootstrapperEnabled>true</BootstrapperEnabled>\r
7531- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
7532+ <TargetFrameworkProfile />\r
7533 </PropertyGroup>\r
7534 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
7535 <DebugSymbols>true</DebugSymbols>\r
7536@@ -40,6 +41,7 @@
7537 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
7538 <ErrorReport>prompt</ErrorReport>\r
7539 <WarningLevel>4</WarningLevel>\r
7540+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
7541 </PropertyGroup>\r
7542 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
7543 <DebugType>pdbonly</DebugType>\r
7544@@ -48,6 +50,7 @@
7545 <DefineConstants>TRACE</DefineConstants>\r
7546 <ErrorReport>prompt</ErrorReport>\r
7547 <WarningLevel>4</WarningLevel>\r
7548+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
7549 </PropertyGroup>\r
7550 <ItemGroup>\r
7551 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
7552@@ -97,6 +100,8 @@
7553 <Compile Include="ReviewUselessControlFlowTest.cs" />\r
7554 <Compile Include="ReviewUseOfInt64BitsToDoubleTest.cs" />\r
7555 <Compile Include="ReviewUseOfModuloOneOnIntegersTest.cs" />\r
7556+ <Compile Include="TypesWithDisposableFieldsShouldBeDisposableTest.cs" />\r
7557+ <Compile Include="TypesWithNativeFieldsShouldBeDisposableTest.cs" />\r
7558 <Compile Include="UseNoInliningWithGetCallingAssemblyTest.cs" />\r
7559 <Compile Include="UseValueInPropertySetterTest.cs" />\r
7560 </ItemGroup>\r
7561@@ -119,14 +124,33 @@
7562 </ProjectReference>\r
7563 </ItemGroup>\r
7564 <ItemGroup>\r
7565+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
7566+ <Visible>False</Visible>\r
7567+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
7568+ <Install>false</Install>\r
7569+ </BootstrapperPackage>\r
7570 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
7571 <Visible>False</Visible>\r
7572+ <ProductName>\r
7573+ </ProductName>\r
7574+ <Install>false</Install>\r
7575 </BootstrapperPackage>\r
7576 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
7577 <Visible>False</Visible>\r
7578+ <ProductName>\r
7579+ </ProductName>\r
7580+ <Install>false</Install>\r
7581 </BootstrapperPackage>\r
7582 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
7583 <Visible>False</Visible>\r
7584+ <ProductName>\r
7585+ </ProductName>\r
7586+ <Install>false</Install>\r
7587+ </BootstrapperPackage>\r
7588+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
7589+ <Visible>False</Visible>\r
7590+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
7591+ <Install>false</Install>\r
7592 </BootstrapperPackage>\r
7593 </ItemGroup>\r
7594 <ItemGroup>\r
7595diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs
7596new file mode 100644
7597index 0000000..077889c
7598--- /dev/null
7599+++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs
7600@@ -0,0 +1,322 @@
7601+//
7602+// Unit tests for TypesWithDisposableFieldsShouldBeDisposableRule
7603+//
7604+// Authors:
7605+// Andreas Noever <andreas.noever@gmail.com>
7606+// Sebastien Pouliot <sebastien@ximian.com>
7607+//
7608+// (C) 2008 Andreas Noever
7609+// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
7610+//
7611+// Permission is hereby granted, free of charge, to any person obtaining
7612+// a copy of this software and associated documentation files (the
7613+// "Software"), to deal in the Software without restriction, including
7614+// without limitation the rights to use, copy, modify, merge, publish,
7615+// distribute, sublicense, and/or sell copies of the Software, and to
7616+// permit persons to whom the Software is furnished to do so, subject to
7617+// the following conditions:
7618+//
7619+// The above copyright notice and this permission notice shall be
7620+// included in all copies or substantial portions of the Software.
7621+//
7622+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
7623+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7624+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
7625+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
7626+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
7627+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
7628+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7629+//
7630+
7631+using System;
7632+
7633+using Gendarme.Rules.Correctness;
7634+
7635+using NUnit.Framework;
7636+using Test.Rules.Definitions;
7637+using Test.Rules.Fixtures;
7638+
7639+namespace Test.Rules.Correctness {
7640+
7641+ class Disposable : IDisposable {
7642+ public void Dispose ()
7643+ {
7644+ throw new NotImplementedException ();
7645+ }
7646+ }
7647+
7648+ class NoDisposeableFields {
7649+ int A;
7650+ object b;
7651+ }
7652+
7653+ class DisposeableFieldsImplementsIDisposeable : IDisposable {
7654+ object A;
7655+ Disposable B;
7656+
7657+ public DisposeableFieldsImplementsIDisposeable ()
7658+ {
7659+ B = new Disposable ();
7660+ }
7661+
7662+ public void Dispose ()
7663+ {
7664+ throw new NotImplementedException ();
7665+ }
7666+ }
7667+
7668+ class DisposeableFieldsImplementsIDisposeableCorrectly : IDisposable {
7669+ object A;
7670+ Disposable B;
7671+
7672+ public DisposeableFieldsImplementsIDisposeableCorrectly ()
7673+ {
7674+ B = new Disposable ();
7675+ }
7676+
7677+ public void Dispose ()
7678+ {
7679+ B.Dispose (); // not really correct but Dispose is called :)
7680+ }
7681+ }
7682+
7683+ class DisposeableFieldsExplicit : IDisposable {
7684+ object A;
7685+ Disposable B;
7686+
7687+ void IDisposable.Dispose ()
7688+ {
7689+ throw new NotImplementedException ();
7690+ }
7691+ }
7692+
7693+ abstract class DisposeableFieldsImplementsIDisposeableAbstract : IDisposable {
7694+ object A;
7695+ Disposable B;
7696+ public void Dispose (object asd) { B.Dispose (); }
7697+ public abstract void Dispose ();
7698+ }
7699+
7700+ abstract class DisposeableFieldsImplementsIDisposeableAbstractAssigned : IDisposable {
7701+ object A;
7702+ Disposable B;
7703+
7704+ protected DisposeableFieldsImplementsIDisposeableAbstractAssigned ()
7705+ {
7706+ B = new Disposable ();
7707+ }
7708+
7709+ public abstract void Dispose ();
7710+ }
7711+
7712+ public class DisposeableFieldsNeverAssigned : ICloneable {
7713+ object A;
7714+ Disposable B;
7715+
7716+ public object Clone ()
7717+ {
7718+ throw new NotImplementedException ();
7719+ }
7720+ }
7721+
7722+ public class DisposeableFieldsNullAssigned : ICloneable {
7723+ object A;
7724+ Disposable B;
7725+
7726+ public DisposeableFieldsNullAssigned ()
7727+ {
7728+ A = null;
7729+ B = null;
7730+ }
7731+
7732+ public object Clone ()
7733+ {
7734+ throw new NotImplementedException ();
7735+ }
7736+ }
7737+
7738+ public class DisposeableFieldsAssigned : ICloneable {
7739+ object A;
7740+ Disposable B;
7741+
7742+ public DisposeableFieldsAssigned ()
7743+ {
7744+ A = null;
7745+ B = new Disposable ();
7746+ }
7747+
7748+ public object Clone ()
7749+ {
7750+ throw new NotImplementedException ();
7751+ }
7752+ }
7753+
7754+ class DisposeableFieldsReferenced : ICloneable {
7755+ object A;
7756+ Disposable B;
7757+
7758+ public DisposeableFieldsReferenced (Disposable instance)
7759+ {
7760+ A = null;
7761+ B = instance;
7762+ }
7763+
7764+ public object Clone ()
7765+ {
7766+ throw new NotImplementedException ();
7767+ }
7768+ }
7769+
7770+ class DisposeableFieldsArray : ICloneable {
7771+ object A;
7772+ Disposable [] B;
7773+
7774+ public object Clone ()
7775+ {
7776+ throw new NotImplementedException ();
7777+ }
7778+ }
7779+
7780+ class DisposeableFieldsArrayAssigned : ICloneable {
7781+ object A;
7782+ Disposable [] B;
7783+
7784+ public object Clone ()
7785+ {
7786+ // the array itself is not not IDisposable
7787+ B = new Disposable [10];
7788+ A = B;
7789+ return A;
7790+ }
7791+ }
7792+
7793+ class DisposeableFieldsArrayMembers : ICloneable {
7794+ object A;
7795+ Disposable [] B;
7796+
7797+ public object Clone ()
7798+ {
7799+ B = new Disposable [1];
7800+ // assignation (newobj+stfld) does not need to to be inside ctor
7801+ // note: fxcop does not catch this one
7802+ B [0] = new Disposable ();
7803+ A = B;
7804+ return A;
7805+ }
7806+ }
7807+
7808+ struct StructWithDisposeableFields {
7809+ Disposable a;
7810+ object b;
7811+
7812+ public StructWithDisposeableFields (object obj)
7813+ {
7814+ b = obj;
7815+ a = new Disposable ();
7816+ }
7817+ }
7818+
7819+ class DisposeableStaticFieldsArray {
7820+ object A;
7821+ static Disposable [] B;
7822+
7823+ static DisposeableStaticFieldsArray ()
7824+ {
7825+ B = new Disposable [1];
7826+ B [0] = new Disposable ();
7827+ }
7828+ }
7829+
7830+ // test case from https://bugzilla.novell.com/show_bug.cgi?id=671029
7831+
7832+ interface ISession : IDisposable {
7833+ void Query (string s);
7834+ }
7835+
7836+ class SomeRepository {
7837+ ISession session;
7838+ public SomeRepository (ISession session)
7839+ {
7840+ this.session = session;
7841+ }
7842+ public void DoSomeQuery ()
7843+ {
7844+ session.Query ("whatever");
7845+ }
7846+ }
7847+
7848+
7849+ [TestFixture]
7850+ public class TypesWithDisposableFieldsShouldBeDisposableTest : TypeRuleTestFixture<TypesWithDisposableFieldsShouldBeDisposableRule> {
7851+
7852+ [Test]
7853+ public void DoesNotApply ()
7854+ {
7855+ AssertRuleDoesNotApply (SimpleTypes.Delegate);
7856+ AssertRuleDoesNotApply (SimpleTypes.Enum);
7857+ AssertRuleDoesNotApply (SimpleTypes.Interface);
7858+ AssertRuleDoesNotApply (SimpleTypes.Structure);
7859+ }
7860+
7861+ [Test]
7862+ public void TestNoDisposeableFields ()
7863+ {
7864+ AssertRuleSuccess<NoDisposeableFields> ();
7865+ }
7866+
7867+ [Test]
7868+ public void TestDisposeableFieldsImplementsIDisposeable ()
7869+ {
7870+ AssertRuleSuccess<DisposeableFieldsImplementsIDisposeable> ();
7871+ AssertRuleSuccess<DisposeableFieldsImplementsIDisposeableCorrectly> ();
7872+ }
7873+
7874+ [Test]
7875+ public void TestDisposeableFieldsExplicit ()
7876+ {
7877+ AssertRuleSuccess<DisposeableFieldsExplicit> ();
7878+ }
7879+
7880+ [Test]
7881+ public void TestDisposeableFieldsImplementsIDisposeableAbstract ()
7882+ {
7883+ AssertRuleFailure<DisposeableFieldsImplementsIDisposeableAbstract> (1);
7884+ AssertRuleFailure<DisposeableFieldsImplementsIDisposeableAbstractAssigned> (2);
7885+ }
7886+
7887+ [Test]
7888+ public void TestDisposeableFields ()
7889+ {
7890+ AssertRuleSuccess<DisposeableFieldsNeverAssigned> ();
7891+ AssertRuleSuccess<DisposeableFieldsNullAssigned> ();
7892+ AssertRuleSuccess<DisposeableFieldsReferenced> ();
7893+ AssertRuleFailure<DisposeableFieldsAssigned> (1);
7894+ }
7895+
7896+ [Test]
7897+ public void TestDisposeableFieldsArray ()
7898+ {
7899+ AssertRuleSuccess<DisposeableFieldsArray> ();
7900+ AssertRuleSuccess<DisposeableFieldsArrayAssigned> ();
7901+ AssertRuleFailure<DisposeableFieldsArrayMembers> (1);
7902+ }
7903+
7904+ [Test]
7905+ public void TestStructWithDisposeableFields ()
7906+ {
7907+ AssertRuleDoesNotApply<StructWithDisposeableFields> ();
7908+ }
7909+
7910+ [Test]
7911+ public void TestDisposeableStaticFieldsArray ()
7912+ {
7913+ AssertRuleSuccess<DisposeableStaticFieldsArray> ();
7914+ }
7915+
7916+ [Test]
7917+ public void Bug671029 ()
7918+ {
7919+ AssertRuleSuccess<SomeRepository> ();
7920+ }
7921+ }
7922+}
7923diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs
7924new file mode 100644
7925index 0000000..b66fcbf
7926--- /dev/null
7927+++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs
7928@@ -0,0 +1,324 @@
7929+//
7930+// Unit tests for TypesWithNativeFieldsShouldBeDisposableRule
7931+//
7932+// Authors:
7933+// Andreas Noever <andreas.noever@gmail.com>
7934+// Sebastien Pouliot <sebastien@ximian.com>
7935+//
7936+// (C) 2008 Andreas Noever
7937+// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
7938+//
7939+// Permission is hereby granted, free of charge, to any person obtaining
7940+// a copy of this software and associated documentation files (the
7941+// "Software"), to deal in the Software without restriction, including
7942+// without limitation the rights to use, copy, modify, merge, publish,
7943+// distribute, sublicense, and/or sell copies of the Software, and to
7944+// permit persons to whom the Software is furnished to do so, subject to
7945+// the following conditions:
7946+//
7947+// The above copyright notice and this permission notice shall be
7948+// included in all copies or substantial portions of the Software.
7949+//
7950+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
7951+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7952+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
7953+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
7954+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
7955+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
7956+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7957+//
7958+
7959+using System;
7960+using System.Runtime.InteropServices;
7961+
7962+using Gendarme.Rules.Correctness;
7963+
7964+using NUnit.Framework;
7965+using Test.Rules.Definitions;
7966+using Test.Rules.Fixtures;
7967+
7968+namespace Test.Rules.Design {
7969+
7970+ class NoNativeFields {
7971+ int A;
7972+ object b;
7973+ }
7974+
7975+ class NativeFieldsImplementsIDisposeable : IDisposable {
7976+ object A;
7977+ IntPtr B;
7978+
7979+ public void Dispose ()
7980+ {
7981+ throw new NotImplementedException ();
7982+ }
7983+ }
7984+
7985+ class NativeFieldsExplicit : IDisposable {
7986+ object A;
7987+ IntPtr B;
7988+
7989+ void IDisposable.Dispose ()
7990+ {
7991+ throw new NotImplementedException ();
7992+ }
7993+ }
7994+
7995+
7996+ class NativeFieldsIntPtr : ICloneable {
7997+ object A;
7998+ IntPtr B;
7999+
8000+ public object Clone ()
8001+ {
8002+ throw new NotImplementedException ();
8003+ }
8004+ }
8005+
8006+ class NativeFieldsIntPtrAssigned : ICloneable {
8007+ object A;
8008+ IntPtr B;
8009+
8010+ public NativeFieldsIntPtrAssigned ()
8011+ {
8012+ B = IntPtr.Zero;
8013+ }
8014+
8015+ public object Clone ()
8016+ {
8017+ throw new NotImplementedException ();
8018+ }
8019+ }
8020+
8021+ class NativeFieldsIntPtrAllocated : ICloneable {
8022+ object A;
8023+ IntPtr B;
8024+
8025+ public NativeFieldsIntPtrAllocated ()
8026+ {
8027+ B = Marshal.AllocCoTaskMem (1);
8028+ }
8029+
8030+ public object Clone ()
8031+ {
8032+ throw new NotImplementedException ();
8033+ }
8034+ }
8035+
8036+ class NativeFieldsUIntPtr : ICloneable {
8037+ object A;
8038+ UIntPtr B;
8039+
8040+ public object Clone ()
8041+ {
8042+ throw new NotImplementedException ();
8043+ }
8044+ }
8045+
8046+ class NativeFieldsUIntPtrAssigned : ICloneable {
8047+ object A;
8048+ UIntPtr B;
8049+
8050+ public NativeFieldsUIntPtrAssigned ()
8051+ {
8052+ B = (UIntPtr) 0x1f00;
8053+ }
8054+
8055+ public object Clone ()
8056+ {
8057+ throw new NotImplementedException ();
8058+ }
8059+ }
8060+
8061+ class NativeFieldsUIntPtrAllocated : ICloneable {
8062+ object A;
8063+ UIntPtr B;
8064+
8065+ [DllImport ("liberty")]
8066+ extern static UIntPtr Alloc (int x);
8067+
8068+ public NativeFieldsUIntPtrAllocated ()
8069+ {
8070+ B = Alloc (1);
8071+ }
8072+
8073+ public object Clone ()
8074+ {
8075+ throw new NotImplementedException ();
8076+ }
8077+ }
8078+
8079+ class NativeFieldsHandleRef : ICloneable {
8080+ object A;
8081+ HandleRef B;
8082+
8083+ public object Clone ()
8084+ {
8085+ throw new NotImplementedException ();
8086+ }
8087+ }
8088+
8089+ class NativeFieldsHandleRefAssigned : ICloneable {
8090+ object A;
8091+ HandleRef B;
8092+
8093+ public NativeFieldsHandleRefAssigned ()
8094+ {
8095+ GCHandle handle = GCHandle.Alloc (A, GCHandleType.Pinned);
8096+ B = new HandleRef (handle, handle.AddrOfPinnedObject ());
8097+ }
8098+
8099+ public object Clone ()
8100+ {
8101+ throw new NotImplementedException ();
8102+ }
8103+ }
8104+
8105+ class NativeFieldsHandleRefAllocatedElsewhere: ICloneable {
8106+ object A;
8107+ HandleRef B;
8108+
8109+ HandleRef GetHandleReference ()
8110+ {
8111+ return new HandleRef (A, IntPtr.Zero);
8112+ }
8113+
8114+ public NativeFieldsHandleRefAllocatedElsewhere ()
8115+ {
8116+ // fxcop does not trigger on this (or similar cases)
8117+ B = GetHandleReference ();
8118+ }
8119+
8120+ public object Clone ()
8121+ {
8122+ throw new NotImplementedException ();
8123+ }
8124+ }
8125+
8126+ abstract class AbstractNativeFields : IDisposable {
8127+ object A;
8128+ HandleRef B;
8129+
8130+ public abstract void Dispose ();
8131+ }
8132+
8133+ abstract class AbstractNativeFields2 : IDisposable {
8134+ object A;
8135+ HandleRef B;
8136+
8137+ public abstract void Dispose ();
8138+
8139+
8140+ void IDisposable.Dispose ()
8141+ {
8142+ throw new NotImplementedException ();
8143+ }
8144+ }
8145+
8146+ class NativeFieldsArray : ICloneable {
8147+ object A;
8148+ IntPtr [] B;
8149+
8150+ public object Clone ()
8151+ {
8152+ B = new IntPtr [1];
8153+ // assignation (newobj+stfld) does not need to to be inside ctor
8154+ // note: fxcop does not catch this one
8155+ B [0] = Marshal.AllocCoTaskMem (1);
8156+ A = B;
8157+ return A;
8158+ }
8159+ }
8160+
8161+ struct StructWithNativeFields {
8162+ public IntPtr a;
8163+ public UIntPtr b;
8164+ public HandleRef c;
8165+ }
8166+
8167+ class NativeStaticFieldsArray {
8168+ object A;
8169+ static UIntPtr [] B;
8170+ }
8171+
8172+ [TestFixture]
8173+ public class TypesWithNativeFieldsShouldBeDisposableTest : TypeRuleTestFixture<TypesWithNativeFieldsShouldBeDisposableRule> {
8174+
8175+ [Test]
8176+ public void DoesNotApply ()
8177+ {
8178+ AssertRuleDoesNotApply (SimpleTypes.Delegate);
8179+ AssertRuleDoesNotApply (SimpleTypes.Enum);
8180+ AssertRuleDoesNotApply (SimpleTypes.Interface);
8181+ AssertRuleDoesNotApply (SimpleTypes.Structure);
8182+ }
8183+
8184+ [Test]
8185+ public void TestNoNativeFields ()
8186+ {
8187+ AssertRuleSuccess<NoNativeFields> ();
8188+ }
8189+
8190+ [Test]
8191+ public void TestNativeFieldsImplementsIDisposeable ()
8192+ {
8193+ AssertRuleSuccess<NativeFieldsImplementsIDisposeable> ();
8194+ }
8195+
8196+ [Test]
8197+ public void TestNativeFieldsExplicit ()
8198+ {
8199+ AssertRuleSuccess<NativeFieldsExplicit> ();
8200+ }
8201+
8202+ [Test]
8203+ public void TestNativeFieldsIntPtr ()
8204+ {
8205+ AssertRuleSuccess<NativeFieldsIntPtr> ();
8206+ AssertRuleSuccess<NativeFieldsIntPtrAssigned> ();
8207+ AssertRuleFailure<NativeFieldsIntPtrAllocated> (1);
8208+ }
8209+
8210+ [Test]
8211+ public void TestNativeFieldsUIntPtr ()
8212+ {
8213+ AssertRuleSuccess<NativeFieldsUIntPtr> ();
8214+ AssertRuleSuccess<NativeFieldsUIntPtrAssigned> ();
8215+ AssertRuleFailure<NativeFieldsUIntPtrAllocated> (1);
8216+ }
8217+
8218+ [Test]
8219+ public void TestNativeFieldsHandleRef ()
8220+ {
8221+ AssertRuleSuccess<NativeFieldsHandleRef> ();
8222+ AssertRuleSuccess<NativeFieldsHandleRefAssigned> ();
8223+ AssertRuleFailure<NativeFieldsHandleRefAllocatedElsewhere> (1);
8224+ }
8225+
8226+ [Test]
8227+ public void TestAbstractNativeFields ()
8228+ {
8229+ AssertRuleFailure<AbstractNativeFields> (1);
8230+ AssertRuleFailure<AbstractNativeFields2> (1);
8231+ }
8232+
8233+ [Test]
8234+ public void TestNativeFieldsArray ()
8235+ {
8236+ AssertRuleFailure<NativeFieldsArray> (1);
8237+ }
8238+
8239+ [Test]
8240+ public void TestStructWithNativeFields ()
8241+ {
8242+ AssertRuleDoesNotApply<StructWithNativeFields> ();
8243+ }
8244+
8245+ [Test]
8246+ public void TestNativeStaticFieldsArray ()
8247+ {
8248+ AssertRuleSuccess<NativeStaticFieldsArray> ();
8249+ }
8250+ }
8251+}
8252+
8253diff --git a/gendarme/rules/Gendarme.Rules.Correctness/TypesShouldBeDisposableBaseRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/TypesShouldBeDisposableBaseRule.cs
8254new file mode 100644
8255index 0000000..247d01a
8256--- /dev/null
8257+++ b/gendarme/rules/Gendarme.Rules.Correctness/TypesShouldBeDisposableBaseRule.cs
8258@@ -0,0 +1,127 @@
8259+//
8260+// Gendarme.Rules.Correctness.TypesShouldBeDisposableBaseRule
8261+//
8262+// Authors:
8263+// Andreas Noever <andreas.noever@gmail.com>
8264+// Sebastien Pouliot <sebastien@ximian.com>
8265+//
8266+// (C) 2008 Andreas Noever
8267+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
8268+//
8269+// Permission is hereby granted, free of charge, to any person obtaining
8270+// a copy of this software and associated documentation files (the
8271+// "Software"), to deal in the Software without restriction, including
8272+// without limitation the rights to use, copy, modify, merge, publish,
8273+// distribute, sublicense, and/or sell copies of the Software, and to
8274+// permit persons to whom the Software is furnished to do so, subject to
8275+// the following conditions:
8276+//
8277+// The above copyright notice and this permission notice shall be
8278+// included in all copies or substantial portions of the Software.
8279+//
8280+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
8281+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8282+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
8283+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
8284+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
8285+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
8286+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8287+//
8288+
8289+using System.Collections.Generic;
8290+
8291+using Mono.Cecil;
8292+
8293+using Gendarme.Framework;
8294+using Gendarme.Framework.Helpers;
8295+using Gendarme.Framework.Rocks;
8296+
8297+namespace Gendarme.Rules.Correctness {
8298+
8299+ public abstract class TypesShouldBeDisposableBaseRule : Rule, ITypeRule {
8300+
8301+ protected TypesShouldBeDisposableBaseRule ()
8302+ {
8303+ FieldCandidates = new HashSet<FieldDefinition> ();
8304+ }
8305+
8306+ protected HashSet<FieldDefinition> FieldCandidates { get; private set; }
8307+
8308+ protected abstract string AbstractTypeMessage { get; }
8309+ protected abstract string TypeMessage { get; }
8310+ protected abstract string AbstractDisposeMessage { get; }
8311+
8312+ static bool IsAbstract (MethodDefinition method)
8313+ {
8314+ return ((method != null) && (method.IsAbstract));
8315+ }
8316+
8317+ protected abstract void CheckMethod (MethodDefinition method, bool abstractWarning);
8318+
8319+ protected abstract bool FieldTypeIsCandidate (TypeDefinition type);
8320+
8321+ public RuleResult CheckType (TypeDefinition type)
8322+ {
8323+ // that will cover interfaces, delegates too
8324+ if (!type.HasFields)
8325+ return RuleResult.DoesNotApply;
8326+
8327+ // rule doesn't apply to enums, interfaces, structs, delegates or generated code
8328+ if (type.IsEnum || type.IsValueType || type.IsGeneratedCode ())
8329+ return RuleResult.DoesNotApply;
8330+
8331+ MethodDefinition explicitDisposeMethod = null;
8332+ MethodDefinition implicitDisposeMethod = null;
8333+
8334+ bool abstractWarning = false;
8335+
8336+ if (type.Implements ("System", "IDisposable")) {
8337+ implicitDisposeMethod = type.GetMethod (MethodSignatures.Dispose);
8338+ explicitDisposeMethod = type.GetMethod (MethodSignatures.DisposeExplicit);
8339+
8340+ if (IsAbstract (implicitDisposeMethod) || IsAbstract (explicitDisposeMethod)) {
8341+ abstractWarning = true;
8342+ } else {
8343+ return RuleResult.Success;
8344+ }
8345+ }
8346+
8347+ FieldCandidates.Clear ();
8348+
8349+ foreach (FieldDefinition field in type.Fields) {
8350+ // we can't dispose static fields in IDisposable
8351+ if (field.IsStatic)
8352+ continue;
8353+ TypeDefinition fieldType = field.FieldType.GetElementType ().Resolve ();
8354+ if (fieldType == null)
8355+ continue;
8356+ if (FieldTypeIsCandidate (fieldType))
8357+ FieldCandidates.Add (field);
8358+ }
8359+
8360+ // if there are fields types that implements IDisposable
8361+ if (type.HasMethods && (FieldCandidates.Count > 0)) {
8362+ // check if we're assigning new object to them
8363+ foreach (MethodDefinition method in type.Methods) {
8364+ CheckMethod (method, abstractWarning);
8365+ }
8366+ }
8367+
8368+ // Warn about possible confusion if the Dispose methods are abstract
8369+ if (IsAbstract (implicitDisposeMethod))
8370+ Runner.Report (implicitDisposeMethod, Severity.Medium, Confidence.High, AbstractDisposeMessage);
8371+
8372+ return Runner.CurrentRuleResult;
8373+ }
8374+#if false
8375+ public void Bitmask ()
8376+ {
8377+ OpCodeBitmask mask = new OpCodeBitmask ();
8378+ mask.Set (Code.Stfld);
8379+ mask.Set (Code.Stelem_Ref);
8380+ Console.WriteLine (mask);
8381+ }
8382+#endif
8383+ }
8384+}
8385+
8386diff --git a/gendarme/rules/Gendarme.Rules.Correctness/TypesWithDisposableFieldsShouldBeDisposableRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/TypesWithDisposableFieldsShouldBeDisposableRule.cs
8387new file mode 100644
8388index 0000000..1731951
8389--- /dev/null
8390+++ b/gendarme/rules/Gendarme.Rules.Correctness/TypesWithDisposableFieldsShouldBeDisposableRule.cs
8391@@ -0,0 +1,136 @@
8392+//
8393+// Gendarme.Rules.Correctness.TypesWithDisposableFieldsShouldBeDisposableRule
8394+//
8395+// Authors:
8396+// Andreas Noever <andreas.noever@gmail.com>
8397+// Sebastien Pouliot <sebastien@ximian.com>
8398+//
8399+// (C) 2008 Andreas Noever
8400+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
8401+//
8402+// Permission is hereby granted, free of charge, to any person obtaining
8403+// a copy of this software and associated documentation files (the
8404+// "Software"), to deal in the Software without restriction, including
8405+// without limitation the rights to use, copy, modify, merge, publish,
8406+// distribute, sublicense, and/or sell copies of the Software, and to
8407+// permit persons to whom the Software is furnished to do so, subject to
8408+// the following conditions:
8409+//
8410+// The above copyright notice and this permission notice shall be
8411+// included in all copies or substantial portions of the Software.
8412+//
8413+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
8414+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8415+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
8416+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
8417+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
8418+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
8419+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8420+//
8421+
8422+using Mono.Cecil;
8423+using Mono.Cecil.Cil;
8424+
8425+using Gendarme.Framework;
8426+using Gendarme.Framework.Engines;
8427+using Gendarme.Framework.Helpers;
8428+using Gendarme.Framework.Rocks;
8429+
8430+namespace Gendarme.Rules.Correctness {
8431+
8432+ /// <summary>
8433+ /// This rule will fire if a type contains disposable fields, i.e. fields whose types implements
8434+ /// <c>System.IDisposable</c>, but where the type itself does not implement <c>System.IDisposable</c>.
8435+ /// The rule will not report types that are not assigning themselves new instances to the fields.
8436+ /// </summary>
8437+ /// <example>
8438+ /// Bad examples:
8439+ /// <code>
8440+ /// class DoesNotImplementIDisposable {
8441+ /// IDisposable field;
8442+ /// }
8443+ ///
8444+ /// class AbstractDispose : IDisposable {
8445+ /// IDisposable field;
8446+ ///
8447+ /// // the field should be disposed in the type that declares it
8448+ /// public abstract void Dispose ();
8449+ /// }
8450+ /// </code>
8451+ /// </example>
8452+ /// <example>
8453+ /// Good example:
8454+ /// <code>
8455+ /// class Dispose : IDisposable {
8456+ /// IDisposable field;
8457+ ///
8458+ /// public void Dispose ()
8459+ /// {
8460+ /// field.Dispose ();
8461+ /// }
8462+ /// }
8463+ /// </code>
8464+ /// </example>
8465+
8466+ [Problem ("This type contains disposable field(s) but doesn't implement IDisposable.")]
8467+ [Solution ("Implement IDisposable and free the disposable field(s) in the Dispose method.")]
8468+ [FxCopCompatibility ("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
8469+ [EngineDependency (typeof (OpCodeEngine))]
8470+ public class TypesWithDisposableFieldsShouldBeDisposableRule : TypesShouldBeDisposableBaseRule {
8471+
8472+ static OpCodeBitmask StoreFieldBitmask = new OpCodeBitmask (0x0, 0x400000000000000, 0x80000000, 0x0);
8473+
8474+ protected override string AbstractTypeMessage {
8475+ get { return "Field implement IDisposable. Type should implement a non-abstract Dispose() method"; }
8476+ }
8477+
8478+ protected override string TypeMessage {
8479+ get { return "Field implement IDisposable. Type should implement a Dispose() method"; }
8480+ }
8481+
8482+ protected override string AbstractDisposeMessage {
8483+ get { return "Some field(s) implement IDisposable. Making this method abstract shifts the reponsability of disposing those fields to the inheritors of this class."; }
8484+ }
8485+
8486+ protected override void CheckMethod (MethodDefinition method, bool abstractWarning)
8487+ {
8488+ if ((method == null) || !method.HasBody)
8489+ return;
8490+
8491+ OpCodeBitmask bitmask = OpCodeEngine.GetBitmask (method);
8492+ // method must have a NEWOBJ and either STFLD or STELEM_REF
8493+ if (!bitmask.Get (Code.Newobj) || !bitmask.Intersect (StoreFieldBitmask))
8494+ return;
8495+
8496+ foreach (Instruction ins in method.Body.Instructions) {
8497+ if (!ins.Is (Code.Newobj))
8498+ continue;
8499+
8500+ FieldDefinition field = null;
8501+ Instruction next = ins.Next;
8502+ if (next.Is (Code.Stfld)) {
8503+ field = next.Operand as FieldDefinition;
8504+ } else if (next.Is (Code.Stelem_Ref)) {
8505+ Instruction origin = next.TraceBack (method);
8506+ if (origin != null)
8507+ field = origin.Operand as FieldDefinition;
8508+ }
8509+
8510+ if (field != null && FieldCandidates.Contains (field)) {
8511+ Runner.Report (field, Severity.High, Confidence.High,
8512+ abstractWarning ? AbstractTypeMessage : TypeMessage);
8513+ }
8514+ }
8515+ }
8516+
8517+ protected override bool FieldTypeIsCandidate (TypeDefinition type)
8518+ {
8519+ // enums and primitives don't implement IDisposable
8520+ if ((type == null) || type.IsEnum || type.IsPrimitive)
8521+ return false;
8522+
8523+ return type.Implements ("System", "IDisposable");
8524+ }
8525+ }
8526+}
8527+
8528diff --git a/gendarme/rules/Gendarme.Rules.Correctness/TypesWithNativeFieldsShouldBeDisposableRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/TypesWithNativeFieldsShouldBeDisposableRule.cs
8529new file mode 100644
8530index 0000000..1273a75
8531--- /dev/null
8532+++ b/gendarme/rules/Gendarme.Rules.Correctness/TypesWithNativeFieldsShouldBeDisposableRule.cs
8533@@ -0,0 +1,134 @@
8534+//
8535+// Gendarme.Rules.Correctness.TypesWithNativeFieldsShouldBeDisposableRule
8536+//
8537+// Authors:
8538+// Andreas Noever <andreas.noever@gmail.com>
8539+// Sebastien Pouliot <sebastien@ximian.com>
8540+//
8541+// (C) 2008 Andreas Noever
8542+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
8543+//
8544+// Permission is hereby granted, free of charge, to any person obtaining
8545+// a copy of this software and associated documentation files (the
8546+// "Software"), to deal in the Software without restriction, including
8547+// without limitation the rights to use, copy, modify, merge, publish,
8548+// distribute, sublicense, and/or sell copies of the Software, and to
8549+// permit persons to whom the Software is furnished to do so, subject to
8550+// the following conditions:
8551+//
8552+// The above copyright notice and this permission notice shall be
8553+// included in all copies or substantial portions of the Software.
8554+//
8555+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
8556+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8557+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
8558+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
8559+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
8560+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
8561+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8562+//
8563+
8564+using Mono.Cecil;
8565+using Mono.Cecil.Cil;
8566+
8567+using Gendarme.Framework;
8568+using Gendarme.Framework.Engines;
8569+using Gendarme.Framework.Helpers;
8570+using Gendarme.Framework.Rocks;
8571+
8572+namespace Gendarme.Rules.Correctness {
8573+
8574+ /// <summary>
8575+ /// This rule will fire if a type contains <c>IntPtr</c>, <c>UIntPtr</c>, or
8576+ /// <c>HandleRef</c> fields but does not implement <c>System.IDisposable</c>.
8577+ /// </summary>
8578+ /// <example>
8579+ /// Bad examples:
8580+ /// <code>
8581+ /// public class DoesNotImplementIDisposable {
8582+ /// IntPtr field;
8583+ /// }
8584+ ///
8585+ /// abstract public class AbstractDispose : IDisposable {
8586+ /// IntPtr field;
8587+ ///
8588+ /// // the field should be disposed in the type that declares it
8589+ /// public abstract void Dispose ();
8590+ /// }
8591+ /// </code>
8592+ /// </example>
8593+ /// <example>
8594+ /// Good example:
8595+ /// <code>
8596+ /// public class Dispose : IDisposable {
8597+ /// IDisposable field;
8598+ ///
8599+ /// public void Dispose ()
8600+ /// {
8601+ /// UnmanagedFree (field);
8602+ /// }
8603+ /// }
8604+ /// </code>
8605+ /// </example>
8606+
8607+ [Problem ("This type contains native field(s) but doesn't implement IDisposable.")]
8608+ [Solution ("Implement IDisposable and free the native field(s) in the Dispose method.")]
8609+ [FxCopCompatibility ("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")]
8610+ [EngineDependency (typeof (OpCodeEngine))]
8611+ public class TypesWithNativeFieldsShouldBeDisposableRule : TypesShouldBeDisposableBaseRule {
8612+
8613+ static OpCodeBitmask StoreFieldBitmask = new OpCodeBitmask (0x0, 0x400000000000000, 0x80000000, 0x0);
8614+
8615+ protected override string AbstractTypeMessage {
8616+ get { return "Field is native. Type should implement a non-abstract Dispose() method"; }
8617+ }
8618+
8619+ protected override string TypeMessage {
8620+ get { return "Field is native. Type should implement a Dispose() method"; }
8621+ }
8622+
8623+ protected override string AbstractDisposeMessage {
8624+ get { return "Some fields are native pointers. Making this method abstract shifts the reponsability of disposing those fields to the inheritors of this class."; }
8625+ }
8626+
8627+ protected override void CheckMethod (MethodDefinition method, bool abstractWarning)
8628+ {
8629+ if ((method == null) || !method.HasBody)
8630+ return;
8631+
8632+ OpCodeBitmask bitmask = OpCodeEngine.GetBitmask (method);
8633+ // method must have a CALL[VIRT] and either STFLD or STELEM_REF
8634+ if (!bitmask.Intersect (OpCodeBitmask.Calls) || !bitmask.Intersect (StoreFieldBitmask))
8635+ return;
8636+
8637+ foreach (Instruction ins in method.Body.Instructions) {
8638+ MethodReference mr = (ins.Operand as MethodReference);
8639+ if (mr == null || mr.DeclaringType.IsNative ())
8640+ continue;
8641+
8642+ FieldDefinition field = null;
8643+ Instruction next = ins.Next;
8644+ if (next.Is (Code.Stfld)) {
8645+ field = next.Operand as FieldDefinition;
8646+ } else if (next.Is (Code.Stobj) || next.Is (Code.Stind_I)) {
8647+ Instruction origin = next.TraceBack (method);
8648+ if (origin.Is (Code.Ldelema)) {
8649+ origin = origin.TraceBack (method);
8650+ if (origin != null)
8651+ field = origin.Operand as FieldDefinition;
8652+ }
8653+ }
8654+
8655+ if (field != null && FieldCandidates.Contains (field)) {
8656+ Runner.Report (field, Severity.High, Confidence.High,
8657+ abstractWarning ? AbstractTypeMessage : TypeMessage);
8658+ }
8659+ }
8660+ }
8661+
8662+ protected override bool FieldTypeIsCandidate (TypeDefinition type)
8663+ {
8664+ return ((type != null) && type.IsNative ());
8665+ }
8666+ }
8667+}
8668diff --git a/gendarme/rules/Gendarme.Rules.Correctness/UseNoInliningWithGetCallingAssemblyRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/UseNoInliningWithGetCallingAssemblyRule.cs
8669index 0026e04..702ab6b 100644
8670--- a/gendarme/rules/Gendarme.Rules.Correctness/UseNoInliningWithGetCallingAssemblyRule.cs
8671+++ b/gendarme/rules/Gendarme.Rules.Correctness/UseNoInliningWithGetCallingAssemblyRule.cs
8672@@ -71,32 +71,33 @@ namespace Gendarme.Rules.Correctness {
8673 [EngineDependency (typeof (OpCodeEngine))]
8674 public class UseNoInliningWithGetCallingAssemblyRule : Rule, IMethodRule {
8675
8676- private const string Assembly = "System.Reflection.Assembly";
8677-
8678 public override void Initialize (IRunner runner)
8679 {
8680 base.Initialize (runner);
8681
8682 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
8683- // if the module does not reference System.Reflection.Assembly
8684- // then no method inside it will be calling GetCallingAssembly
8685+ // if the module does not reference System.Reflection.Assembly.GetCallingAssembly
8686+ // then there's no point in enabling the rule
8687 Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
8688- e.CurrentModule.HasTypeReference (Assembly));
8689+ e.CurrentModule.AnyMemberReference ((MemberReference mr) => {
8690+ return IsGetCallingAssembly (mr);
8691+ })
8692+ );
8693 };
8694 }
8695
8696+ static bool IsGetCallingAssembly (MemberReference method)
8697+ {
8698+ return method.IsNamed ("System.Reflection", "Assembly", "GetCallingAssembly");
8699+ }
8700+
8701 static bool IsCallToGetCallingAssembly (Instruction instruction)
8702 {
8703 var code = instruction.OpCode.Code;
8704 if (code != Code.Call && code != Code.Callvirt)
8705 return false;
8706
8707- var method = instruction.Operand as MethodReference;
8708- if (method == null)
8709- return false;
8710-
8711- return method.Name == "GetCallingAssembly"
8712- && method.DeclaringType.FullName == Assembly;
8713+ return IsGetCallingAssembly (instruction.GetMethod ());
8714 }
8715
8716 public RuleResult CheckMethod (MethodDefinition method)
8717diff --git a/gendarme/rules/Gendarme.Rules.Correctness/UseValueInPropertySetterRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/UseValueInPropertySetterRule.cs
8718index 0e55cbc..c97e3ee 100644
8719--- a/gendarme/rules/Gendarme.Rules.Correctness/UseValueInPropertySetterRule.cs
8720+++ b/gendarme/rules/Gendarme.Rules.Correctness/UseValueInPropertySetterRule.cs
8721@@ -103,7 +103,7 @@ namespace Gendarme.Rules.Correctness {
8722 ParameterDefinition pd = instruction.GetParameter (method);
8723 if (pd != null) {
8724 empty = false;
8725- if (pd.GetSequence () == 1) // value
8726+ if (pd.Index == 0) // value
8727 return RuleResult.Success;
8728 continue;
8729 }
8730diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidDeclaringCustomDelegatesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidDeclaringCustomDelegatesRule.cs
8731index 467157a..9156493 100644
8732--- a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidDeclaringCustomDelegatesRule.cs
8733+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidDeclaringCustomDelegatesRule.cs
8734@@ -38,9 +38,8 @@ using Gendarme.Framework.Rocks;
8735 namespace Gendarme.Rules.Design.Generic {
8736
8737 /// <summary>
8738- /// This rule will fire if custom delegates are defined when either pre-defined
8739- /// <code>Action</code>, <code>Action&lt;T[,...]&gt;</code> or <code>Func&lt;[Tx,...]TResult&gt;</code>
8740- /// could have been used. This rule applies only to code using the framework version 2.0 (or later).
8741+ /// This rule will fire if custom delegates are defined when either pre-defined <code>System.Action</code>,
8742+ /// <code>Action&lt;T[,...]&gt;</code> or <code>Func&lt;[Tx,...]TResult&gt;</code> could have been used.
8743 /// </summary>
8744 /// <example>
8745 /// Bad example (without return value):
8746@@ -68,32 +67,10 @@ namespace Gendarme.Rules.Design.Generic {
8747 /// private Func&lt;int,string,int&gt; func_delegate;
8748 /// </code>
8749 /// </example>
8750- /// <remarks>This rule is available since Gendarme 2.8</remarks>
8751+ /// <remarks>This rule applies only to assemblies targeting .NET 2.0 and later.</remarks>
8752 [Problem ("This delegate could be replaced with an existing framework delegate.")]
8753 [Solution ("Prefer the use of Action, Action<T...> and Func<...,TResult> types.")]
8754- public class AvoidDeclaringCustomDelegatesRule : Rule, ITypeRule {
8755-
8756- private int MaxParameter = 4; // NET_2_0
8757-
8758- public override void Initialize (IRunner runner)
8759- {
8760- base.Initialize (runner);
8761-
8762- // we only want to run this on assemblies that use 2.0 or later
8763- // since generics were not available before
8764- Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
8765- TargetRuntime runtime = e.CurrentModule.Runtime;
8766- if (runtime >= TargetRuntime.Net_4_0) {
8767- MaxParameter = 16;
8768- Active = true;
8769- } else if (runtime >= TargetRuntime.Net_2_0) {
8770- MaxParameter = 4;
8771- Active = true;
8772- } else {
8773- Active = false;
8774- }
8775- };
8776- }
8777+ public class AvoidDeclaringCustomDelegatesRule : GenericsBaseRule, ITypeRule {
8778
8779 static string[] ActionMessage = {
8780 "Replace with Action()",
8781@@ -157,7 +134,7 @@ namespace Gendarme.Rules.Design.Generic {
8782 n = pdc.Count;
8783 // too many parameters to directly use Action/Func
8784 // so we lower severity and suggest grouping them
8785- if (n > MaxParameter) {
8786+ if (n > ((type.Module.Runtime >= TargetRuntime.Net_4_0) ? 16 : 4)) {
8787 severity = Severity.Low;
8788 n = 1;
8789 use_structure = true;
8790@@ -170,7 +147,7 @@ namespace Gendarme.Rules.Design.Generic {
8791 }
8792 }
8793
8794- string msg = (invoke.ReturnType.FullName == "System.Void") ? ActionMessage [n] : FuncMessage [n];
8795+ string msg = invoke.ReturnType.IsNamed ("System", "Void") ? ActionMessage [n] : FuncMessage [n];
8796 if (use_structure)
8797 msg += " and use a structure to hold all your parameters into <T>.";
8798 Runner.Report (type, severity, Confidence.High, msg);
8799diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidExcessiveParametersOnGenericTypesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidExcessiveParametersOnGenericTypesRule.cs
8800index e5a8353..d4d02d0 100644
8801--- a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidExcessiveParametersOnGenericTypesRule.cs
8802+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidExcessiveParametersOnGenericTypesRule.cs
8803@@ -37,7 +37,8 @@ using Gendarme.Framework.Rocks;
8804 namespace Gendarme.Rules.Design.Generic {
8805
8806 /// <summary>
8807- /// A type should not have more than two generic parameters.
8808+ /// A visible type should not have more than two generic parameters. This makes it
8809+ /// hard for consumers to remember what each parameter is required for.
8810 /// </summary>
8811 /// <example>
8812 /// Bad example:
8813@@ -53,11 +54,12 @@ namespace Gendarme.Rules.Design.Generic {
8814 /// }
8815 /// </code>
8816 /// </example>
8817-
8818- [Problem ("A type has more than two generic parameters.")]
8819+ /// <remarks>This rule applies only to assemblies targeting .NET 2.0 and later.</remarks>
8820+ [Problem ("A visible type has more than two generic parameters.")]
8821 [Solution ("Redesign the type so it doesn't take more than two generic parameters.")]
8822 [FxCopCompatibility ("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
8823- public class AvoidExcessiveParametersOnGenericTypesRule : Rule, ITypeRule {
8824+ public class AvoidExcessiveParametersOnGenericTypesRule : GenericsBaseRule, ITypeRule {
8825+
8826 public RuleResult CheckType (TypeDefinition type)
8827 {
8828 if (!type.IsClass || !type.HasGenericParameters || !type.IsVisible ())
8829diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidMethodWithUnusedGenericTypeRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidMethodWithUnusedGenericTypeRule.cs
8830index b369332..18d21eb 100644
8831--- a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidMethodWithUnusedGenericTypeRule.cs
8832+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidMethodWithUnusedGenericTypeRule.cs
8833@@ -27,6 +27,7 @@
8834 //
8835
8836 using System;
8837+using System.Globalization;
8838
8839 using Mono.Cecil;
8840
8841@@ -75,50 +76,37 @@ namespace Gendarme.Rules.Design.Generic {
8842 /// }
8843 /// </code>
8844 /// </example>
8845- /// <remarks>This rule is available since Gendarme 2.2</remarks>
8846-
8847+ /// <remarks>This rule applies only to assemblies targeting .NET 2.0 and later.</remarks>
8848 [Problem ("One or more generic type parameters are not used in the formal parameter list.")]
8849 [Solution ("This prevents the compiler from inferring types when the method is used which results in hard to use API definitions.")]
8850 [FxCopCompatibility ("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
8851- public class AvoidMethodWithUnusedGenericTypeRule : Rule, IMethodRule {
8852-
8853- public override void Initialize (IRunner runner)
8854- {
8855- base.Initialize (runner);
8856-
8857- // we only want to run this on assemblies that use 2.0 or later
8858- // since generics were not available before
8859- Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
8860- Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
8861- };
8862- }
8863+ public class AvoidMethodWithUnusedGenericTypeRule : GenericsBaseRule, IMethodRule {
8864
8865- static bool FindGenericType (IGenericInstance git, string fullname)
8866+ static bool FindGenericType (IGenericInstance git, string nameSpace, string name)
8867 {
8868 foreach (object o in git.GenericArguments) {
8869- if (IsGenericParameter (o, fullname))
8870+ if (IsGenericParameter (o, nameSpace, name))
8871 return true;
8872
8873 GenericInstanceType inner = (o as GenericInstanceType);
8874- if ((inner != null) && (FindGenericType (inner, fullname)))
8875+ if ((inner != null) && (FindGenericType (inner, nameSpace, name)))
8876 return true;
8877 }
8878 return false;
8879 }
8880
8881- static bool IsGenericParameter (object obj, string fullname)
8882+ static bool IsGenericParameter (object obj, string nameSpace, string name)
8883 {
8884- GenericParameter gp = (obj as GenericParameter);
8885- return ((gp != null) && (gp.FullName == fullname));
8886+ return (obj as GenericParameter).IsNamed (nameSpace, name);
8887 }
8888
8889- static bool IsGenericType (MemberReference type, string fullname)
8890+ static bool IsGenericType (TypeReference type, string nspace, string name)
8891 {
8892- if (type.FullName == fullname)
8893+ if (type.IsNamed (nspace, name))
8894 return true;
8895
8896 var type_spec = type as TypeSpecification;
8897- if (type_spec != null && type_spec.ElementType.FullName == fullname)
8898+ if (type_spec != null && type_spec.ElementType.IsNamed (nspace, name))
8899 return true;
8900
8901 // handle things like ICollection<T>
8902@@ -126,7 +114,7 @@ namespace Gendarme.Rules.Design.Generic {
8903 if (git == null)
8904 return false;
8905
8906- return FindGenericType (git, fullname);
8907+ return FindGenericType (git, nspace, name);
8908 }
8909
8910 public RuleResult CheckMethod (MethodDefinition method)
8911@@ -139,21 +127,23 @@ namespace Gendarme.Rules.Design.Generic {
8912 foreach (GenericParameter gp in method.GenericParameters) {
8913 Severity severity = Severity.Medium;
8914 bool found = false;
8915- string gp_fullname = gp.FullName;
8916+ string nspace = gp.Namespace;
8917+ string name = gp.Name;
8918 // ... is being used by the method parameters
8919 foreach (ParameterDefinition pd in method.Parameters) {
8920- if (IsGenericType (pd.ParameterType, gp_fullname)) {
8921+ if (IsGenericType (pd.ParameterType, nspace, name)) {
8922 found = true;
8923 break;
8924 }
8925 }
8926 if (!found) {
8927 // it's a defect when used only for the return value - but we reduce its severity
8928- if (IsGenericType (method.ReturnType, gp_fullname))
8929+ if (IsGenericType (method.ReturnType, nspace, name))
8930 severity = Severity.Low;
8931 }
8932 if (!found) {
8933- string msg = String.Format ("Generic parameter '{0}' is not used by the method parameters.", gp_fullname);
8934+ string msg = String.Format (CultureInfo.InvariantCulture,
8935+ "Generic parameter '{0}.{1}' is not used by the method parameters.", nspace, name);
8936 Runner.Report (method, severity, Confidence.High, msg);
8937 }
8938 }
8939diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotDeclareStaticMembersOnGenericTypesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotDeclareStaticMembersOnGenericTypesRule.cs
8940index 00badaa..bc77797 100644
8941--- a/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotDeclareStaticMembersOnGenericTypesRule.cs
8942+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotDeclareStaticMembersOnGenericTypesRule.cs
8943@@ -33,13 +33,14 @@ using Gendarme.Framework.Rocks;
8944 namespace Gendarme.Rules.Design.Generic {
8945
8946 /// <summary>
8947- /// This rule checks for generic types that contain static members.
8948+ /// This rule checks for generic types that contain static members. Such members requires the type argument
8949+ /// to be specified when consumed, leading to harder to use or confusing API.
8950 /// </summary>
8951 /// <example>
8952 /// Bad example:
8953 /// <code>
8954 /// public class BadClass&lt;T&gt; {
8955- /// public static string member () {
8956+ /// public static string Member () {
8957 /// }
8958 /// }
8959 /// </code>
8960@@ -48,16 +49,16 @@ namespace Gendarme.Rules.Design.Generic {
8961 /// Good example:
8962 /// <code>
8963 /// public class GoodClass&lt;T&gt; {
8964- /// public string member () {
8965+ /// public string Member () {
8966 /// }
8967 /// }
8968 /// </code>
8969 /// </example>
8970-
8971+ /// <remarks>This rule applies only to assemblies targeting .NET 2.0 and later.</remarks>
8972 [Problem ("An externally visible generic type has a static member.")]
8973 [Solution ("Remove the static member or change it to an instance member.")]
8974 [FxCopCompatibility ("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
8975- public class DoNotDeclareStaticMembersOnGenericTypesRule : Rule, ITypeRule {
8976+ public class DoNotDeclareStaticMembersOnGenericTypesRule : GenericsBaseRule, ITypeRule {
8977 public RuleResult CheckType (TypeDefinition type)
8978 {
8979 if (!type.IsClass || !type.HasGenericParameters || !type.IsVisible ())
8980diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeGenericListsRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeGenericListsRule.cs
8981index c8712ad..37f3904 100644
8982--- a/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeGenericListsRule.cs
8983+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeGenericListsRule.cs
8984@@ -37,8 +37,8 @@ using Gendarme.Framework.Rocks;
8985 namespace Gendarme.Rules.Design.Generic {
8986
8987 /// <summary>
8988- /// A type has an externally visible member that is, returns, or has a signature containing a
8989- /// System.Collections.Generic.List&lt;T&gt;.
8990+ /// A type has an externally visible member that is, returns or has a signature containing a
8991+ /// <c>System.Collections.Generic.List&lt;T&gt;</c>.
8992 /// </summary>
8993 /// <example>
8994 /// Bad example:
8995@@ -56,17 +56,17 @@ namespace Gendarme.Rules.Design.Generic {
8996 /// }
8997 /// </code>
8998 /// </example>
8999-
9000+ /// <remarks>This rule applies only to assemblies targeting .NET 2.0 and later.</remarks>
9001 [Problem ("The type exposes System.Collections.Generic.List<T>.")]
9002 [Solution ("Use a type such as System.Collections.ObjectModel.Collection<T> instead.")]
9003 [FxCopCompatibility ("Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
9004- public class DoNotExposeGenericListsRule : Rule, ITypeRule {
9005+ public class DoNotExposeGenericListsRule : GenericsBaseRule, ITypeRule {
9006 private const string List = "List`1";
9007
9008 private static bool IsList (TypeReference type)
9009 {
9010 return type.Namespace == "System.Collections.Generic" &&
9011- type.Name.StartsWith (List);
9012+ type.Name.StartsWith (List, StringComparison.Ordinal);
9013 }
9014
9015 private void CheckField (FieldReference field)
9016@@ -80,9 +80,7 @@ namespace Gendarme.Rules.Design.Generic {
9017 if (!IsList (property.PropertyType))
9018 return;
9019
9020- MethodDefinition getm = property.GetMethod;
9021- MethodDefinition setm = property.SetMethod;
9022- if (((getm != null) && getm.IsVisible ()) || ((setm != null) && setm.IsVisible ()))
9023+ if (property.GetMethod.IsVisible () || property.SetMethod.IsVisible ())
9024 Runner.Report (property, Severity.Medium, Confidence.Total);
9025 }
9026
9027diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeNestedGenericSignaturesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeNestedGenericSignaturesRule.cs
9028index 40450bc..d8c5f01 100644
9029--- a/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeNestedGenericSignaturesRule.cs
9030+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeNestedGenericSignaturesRule.cs
9031@@ -41,7 +41,7 @@ namespace Gendarme.Rules.Design.Generic {
9032 /// <c>List&lt;List&lt;int&gt;&gt;</c>. Such types are hard to construct and should
9033 /// be avoided because simpler alternatives generally exist.
9034 /// Since some language, like C#, have direct support for nullable types, i.e.
9035- /// <c>Nullable&lt;T&gt;</c> this specific case is ignored by the rule.
9036+ /// <c>System.Nullable&lt;T&gt;</c> this specific case is ignored by the rule.
9037 /// </summary>
9038 /// <example>
9039 /// Bad example:
9040@@ -63,23 +63,11 @@ namespace Gendarme.Rules.Design.Generic {
9041 /// }
9042 /// </code>
9043 /// </example>
9044- /// <remarks>This rule is available since Gendarme 2.4</remarks>
9045-
9046+ /// <remarks>This rule applies only to assemblies targeting .NET 2.0 and later.</remarks>
9047 [Problem ("This method exposes a nested generic type in its signature.")]
9048 [Solution ("Remove the nested generics to keep the visible API simple to use.")]
9049 [FxCopCompatibility ("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
9050- public class DoNotExposeNestedGenericSignaturesRule : Rule, IMethodRule {
9051-
9052- public override void Initialize (IRunner runner)
9053- {
9054- base.Initialize (runner);
9055-
9056- // we only want to run this on assemblies that use 2.0 or later
9057- // since generics were not available before
9058- Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
9059- Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
9060- };
9061- }
9062+ public class DoNotExposeNestedGenericSignaturesRule : GenericsBaseRule, IMethodRule {
9063
9064 static Severity? Check (TypeReference type)
9065 {
9066@@ -91,7 +79,7 @@ namespace Gendarme.Rules.Design.Generic {
9067 // nullable are an exception because there is syntaxic sugar (at
9068 // least in some language like C#) to make them easier to use
9069 // note: FxCop does not ignore them
9070- if (git.ElementType.FullName == "System.Nullable`1")
9071+ if (git.ElementType.IsNamed ("System", "Nullable`1"))
9072 return null;
9073 // FIXME: we should look at ignoring LINQ queries too, because it
9074 // too pretty much hides the complexity of nested generics
9075diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/Gendarme.Rules.Design.Generic.csproj b/gendarme/rules/Gendarme.Rules.Design.Generic/Gendarme.Rules.Design.Generic.csproj
9076index 9ab2871..17731ea 100644
9077--- a/gendarme/rules/Gendarme.Rules.Design.Generic/Gendarme.Rules.Design.Generic.csproj
9078+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/Gendarme.Rules.Design.Generic.csproj
9079@@ -1,5 +1,5 @@
9080 <?xml version="1.0" encoding="utf-8"?>\r
9081-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
9082+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
9083 <PropertyGroup>\r
9084 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
9085 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
9086@@ -10,8 +10,28 @@
9087 <AppDesignerFolder>Properties</AppDesignerFolder>\r
9088 <RootNamespace>Gendarme.Rules.Design.Generic</RootNamespace>\r
9089 <AssemblyName>Gendarme.Rules.Design.Generic</AssemblyName>\r
9090- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
9091+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
9092 <FileAlignment>512</FileAlignment>\r
9093+ <FileUpgradeFlags>\r
9094+ </FileUpgradeFlags>\r
9095+ <OldToolsVersion>3.5</OldToolsVersion>\r
9096+ <UpgradeBackupLocation />\r
9097+ <PublishUrl>publish\</PublishUrl>\r
9098+ <Install>true</Install>\r
9099+ <InstallFrom>Disk</InstallFrom>\r
9100+ <UpdateEnabled>false</UpdateEnabled>\r
9101+ <UpdateMode>Foreground</UpdateMode>\r
9102+ <UpdateInterval>7</UpdateInterval>\r
9103+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
9104+ <UpdatePeriodically>false</UpdatePeriodically>\r
9105+ <UpdateRequired>false</UpdateRequired>\r
9106+ <MapFileExtensions>true</MapFileExtensions>\r
9107+ <ApplicationRevision>0</ApplicationRevision>\r
9108+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
9109+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
9110+ <UseApplicationTrust>false</UseApplicationTrust>\r
9111+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
9112+ <TargetFrameworkProfile />\r
9113 </PropertyGroup>\r
9114 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
9115 <DebugSymbols>true</DebugSymbols>\r
9116@@ -24,6 +44,7 @@
9117 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Design.Generic.xml</DocumentationFile>\r
9118 <NoWarn>1591</NoWarn>\r
9119 <WarningsAsErrors>1570</WarningsAsErrors>\r
9120+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
9121 </PropertyGroup>\r
9122 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
9123 <DebugType>pdbonly</DebugType>\r
9124@@ -35,6 +56,7 @@
9125 <NoWarn>1591</NoWarn>\r
9126 <WarningsAsErrors>1570</WarningsAsErrors>\r
9127 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Design.Generic.xml</DocumentationFile>\r
9128+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
9129 </PropertyGroup>\r
9130 <ItemGroup>\r
9131 <Reference Include="System" />\r
9132@@ -52,6 +74,7 @@
9133 <Compile Include="DoNotDeclareStaticMembersOnGenericTypesRule.cs" />\r
9134 <Compile Include="DoNotExposeGenericListsRule.cs" />\r
9135 <Compile Include="DoNotExposeNestedGenericSignaturesRule.cs" />\r
9136+ <Compile Include="GenericsBaseRule.cs" />\r
9137 <Compile Include="ImplementGenericCollectionInterfacesRule.cs" />\r
9138 <Compile Include="UseGenericEventHandlerRule.cs" />\r
9139 <Compile Include="PreferGenericsOverRefObjectRule.cs" />\r
9140@@ -66,6 +89,23 @@
9141 <Name>Gendarme.Framework</Name>\r
9142 </ProjectReference>\r
9143 </ItemGroup>\r
9144+ <ItemGroup>\r
9145+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
9146+ <Visible>False</Visible>\r
9147+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
9148+ <Install>false</Install>\r
9149+ </BootstrapperPackage>\r
9150+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
9151+ <Visible>False</Visible>\r
9152+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
9153+ <Install>true</Install>\r
9154+ </BootstrapperPackage>\r
9155+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
9156+ <Visible>False</Visible>\r
9157+ <ProductName>Windows Installer 3.1</ProductName>\r
9158+ <Install>true</Install>\r
9159+ </BootstrapperPackage>\r
9160+ </ItemGroup>\r
9161 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
9162 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
9163 Other similar extension points exist, see Microsoft.Common.targets.
9164diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/GenericsBaseRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/GenericsBaseRule.cs
9165new file mode 100644
9166index 0000000..12be75c
9167--- /dev/null
9168+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/GenericsBaseRule.cs
9169@@ -0,0 +1,50 @@
9170+//
9171+// Gendarme.Rules.Design.Generic.GenericBaseRule
9172+//
9173+// Authors:
9174+// Sebastien Pouliot <sebastien@ximian.com>
9175+//
9176+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
9177+//
9178+// Permission is hereby granted, free of charge, to any person obtaining
9179+// a copy of this software and associated documentation files (the
9180+// "Software"), to deal in the Software without restriction, including
9181+// without limitation the rights to use, copy, modify, merge, publish,
9182+// distribute, sublicense, and/or sell copies of the Software, and to
9183+// permit persons to whom the Software is furnished to do so, subject to
9184+// the following conditions:
9185+//
9186+// The above copyright notice and this permission notice shall be
9187+// included in all copies or substantial portions of the Software.
9188+//
9189+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
9190+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9191+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
9192+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
9193+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
9194+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
9195+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9196+//
9197+
9198+using System;
9199+using Mono.Cecil;
9200+
9201+using Gendarme.Framework;
9202+
9203+namespace Gendarme.Rules.Design.Generic {
9204+
9205+ public abstract class GenericsBaseRule : Rule {
9206+
9207+ public override void Initialize (IRunner runner)
9208+ {
9209+ base.Initialize (runner);
9210+
9211+ // we only want to run Design.Generic.* rules on assemblies that
9212+ // use 2.0 or later since generics were not available before
9213+ Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
9214+ Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
9215+ };
9216+ }
9217+ }
9218+}
9219+
9220diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/ImplementGenericCollectionInterfacesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/ImplementGenericCollectionInterfacesRule.cs
9221index 87391eb..c2d2c32 100644
9222--- a/gendarme/rules/Gendarme.Rules.Design.Generic/ImplementGenericCollectionInterfacesRule.cs
9223+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/ImplementGenericCollectionInterfacesRule.cs
9224@@ -36,9 +36,9 @@ using Gendarme.Framework.Rocks;
9225 namespace Gendarme.Rules.Design.Generic {
9226
9227 /// <summary>
9228- /// This rule checks for types which implement the non-generic IEnumerable interface but
9229- /// not the IEnumerable&lt;T&gt; interface. Implementing the generic version
9230- /// of IEnumerable avoids casts, and possibly boxing, when iterating the collection.
9231+ /// This rule checks for types which implement the non-generic <code>System.IEnumerable</code> interface but
9232+ /// not the <code>System.IEnumerable&lt;T&gt;</code> interface. Implementing the generic version
9233+ /// of <code>System.IEnumerable</code> avoids casts, and possibly boxing, when iterating the collection.
9234 /// </summary>
9235 /// <example>
9236 /// Bad example:
9237@@ -64,23 +64,11 @@ namespace Gendarme.Rules.Design.Generic {
9238 /// }
9239 /// </code>
9240 /// </example>
9241- /// <remarks>Before Gendarme 2.2 this rule was part of Gendarme.Rules.Design assembly.</remarks>
9242-
9243+ /// <remarks>This rule applies only to assemblies targeting .NET 2.0 and later.</remarks>
9244 [Problem ("This type implements the non-generic IEnumerable interface but not IEnumerable<T> which would make your collection type-safe.")]
9245 [Solution ("Implement one of generic collection interfaces such as IEnumerable<T>, ICollection<T> or IList<T>.")]
9246 [FxCopCompatibility ("Microsoft.Design", "CA1010:CollectionsShouldImplementGenericInterface")]
9247- public class ImplementGenericCollectionInterfacesRule : Rule, ITypeRule {
9248-
9249- public override void Initialize (IRunner runner)
9250- {
9251- base.Initialize (runner);
9252-
9253- // we only want to run this on assemblies that use 2.0 or later
9254- // since generics were not available before
9255- Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
9256- Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
9257- };
9258- }
9259+ public class ImplementGenericCollectionInterfacesRule : GenericsBaseRule, ITypeRule {
9260
9261 public RuleResult CheckType (TypeDefinition type)
9262 {
9263@@ -93,15 +81,15 @@ namespace Gendarme.Rules.Design.Generic {
9264 return RuleResult.DoesNotApply;
9265
9266 // rule only applies if the type implements IEnumerable
9267- if (!type.Implements ("System.Collections.IEnumerable"))
9268+ if (!type.Implements ("System.Collections", "IEnumerable"))
9269 return RuleResult.DoesNotApply;
9270
9271 // rule does not apply to the types implementing IDictionary
9272- if (type.Implements ("System.Collections.IDictionary"))
9273+ if (type.Implements ("System.Collections", "IDictionary"))
9274 return RuleResult.DoesNotApply;
9275
9276 // the type should implement IEnumerable<T> too
9277- if (!type.Implements ("System.Collections.Generic.IEnumerable`1"))
9278+ if (!type.Implements ("System.Collections.Generic", "IEnumerable`1"))
9279 Runner.Report (type, Severity.Medium, Confidence.High);
9280
9281 return Runner.CurrentRuleResult;
9282diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/Makefile.am b/gendarme/rules/Gendarme.Rules.Design.Generic/Makefile.am
9283index 4e50027..701ad0e 100644
9284--- a/gendarme/rules/Gendarme.Rules.Design.Generic/Makefile.am
9285+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/Makefile.am
9286@@ -7,6 +7,7 @@ rules_sources = \
9287 DoNotDeclareStaticMembersOnGenericTypesRule.cs \
9288 DoNotExposeGenericListsRule.cs \
9289 DoNotExposeNestedGenericSignaturesRule.cs \
9290+ GenericsBaseRule.cs \
9291 ImplementGenericCollectionInterfacesRule.cs \
9292 PreferGenericsOverRefObjectRule.cs \
9293 UseGenericEventHandlerRule.cs
9294diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/PreferGenericsOverRefObjectRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/PreferGenericsOverRefObjectRule.cs
9295index 56f67a4..fe94e7f 100644
9296--- a/gendarme/rules/Gendarme.Rules.Design.Generic/PreferGenericsOverRefObjectRule.cs
9297+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/PreferGenericsOverRefObjectRule.cs
9298@@ -38,7 +38,7 @@ namespace Gendarme.Rules.Design.Generic {
9299
9300 /// <summary>
9301 /// This rule fires if a method has a reference argument (<c>ref</c> or
9302- /// <c>out</c> in C#) to System.Object. These methods can generally be
9303+ /// <c>out</c> in C#) to <c>System.Object</c>. These methods can generally be
9304 /// rewritten in .NET 2.0 using generics which provides type safety, eliminates
9305 /// casts, and makes the API easier to consume.
9306 /// </summary>
9307@@ -61,23 +61,11 @@ namespace Gendarme.Rules.Design.Generic {
9308 /// }
9309 /// </code>
9310 /// </example>
9311- /// <remarks>This rule is available since Gendarme 2.2</remarks>
9312-
9313+ /// <remarks>This rule applies only to assemblies targeting .NET 2.0 and later.</remarks>
9314 [Problem ("This method contains a reference parameter to System.Object which is often an indication that the code is not type safe.")]
9315 [Solution ("Change the parameter to use a generic type where the caller will provide the type.")]
9316 [FxCopCompatibility ("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
9317- public class PreferGenericsOverRefObjectRule : Rule, IMethodRule {
9318-
9319- public override void Initialize (IRunner runner)
9320- {
9321- base.Initialize (runner);
9322-
9323- // we only want to run this on assemblies that use 2.0 or later
9324- // since generics were not available before
9325- Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
9326- Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
9327- };
9328- }
9329+ public class PreferGenericsOverRefObjectRule : GenericsBaseRule, IMethodRule {
9330
9331 public RuleResult CheckMethod (MethodDefinition method)
9332 {
9333@@ -86,11 +74,11 @@ namespace Gendarme.Rules.Design.Generic {
9334 return RuleResult.DoesNotApply;
9335
9336 // exclude the "bool Try* (ref)" pattern from the rule
9337- if (method.Name.StartsWith ("Try", StringComparison.Ordinal) && (method.ReturnType.FullName == "System.Boolean"))
9338+ if (method.Name.StartsWith ("Try", StringComparison.Ordinal) && method.ReturnType.IsNamed ("System", "Boolean"))
9339 return RuleResult.DoesNotApply;
9340
9341 foreach (ParameterDefinition parameter in method.Parameters) {
9342- if (parameter.ParameterType.FullName != "System.Object&")
9343+ if (!parameter.ParameterType.IsNamed ("System", "Object&"))
9344 continue;
9345
9346 // suggest using generics
9347diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/README.md b/gendarme/rules/Gendarme.Rules.Design.Generic/README.md
9348new file mode 100644
9349index 0000000..f7ce631
9350--- /dev/null
9351+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/README.md
9352@@ -0,0 +1,9 @@
9353+# Gendarme.Rules.Design.Generic Rules
9354+
9355+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design.Generic(git)]] pages.
9356+
9357+
9358+## Feedback
9359+
9360+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
9361+
9362diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/Test/Tests.Rules.Design.Generic.csproj b/gendarme/rules/Gendarme.Rules.Design.Generic/Test/Tests.Rules.Design.Generic.csproj
9363index ca2b70d..5eb62ff 100644
9364--- a/gendarme/rules/Gendarme.Rules.Design.Generic/Test/Tests.Rules.Design.Generic.csproj
9365+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/Test/Tests.Rules.Design.Generic.csproj
9366@@ -1,5 +1,5 @@
9367 <?xml version="1.0" encoding="utf-8"?>\r
9368-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
9369+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
9370 <PropertyGroup>\r
9371 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
9372 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
9373@@ -10,8 +10,28 @@
9374 <AppDesignerFolder>Properties</AppDesignerFolder>\r
9375 <RootNamespace>Tests.Rules.Design.Generic</RootNamespace>\r
9376 <AssemblyName>Tests.Rules.Design.Generic</AssemblyName>\r
9377- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
9378+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
9379 <FileAlignment>512</FileAlignment>\r
9380+ <FileUpgradeFlags>\r
9381+ </FileUpgradeFlags>\r
9382+ <OldToolsVersion>3.5</OldToolsVersion>\r
9383+ <UpgradeBackupLocation />\r
9384+ <PublishUrl>publish\</PublishUrl>\r
9385+ <Install>true</Install>\r
9386+ <InstallFrom>Disk</InstallFrom>\r
9387+ <UpdateEnabled>false</UpdateEnabled>\r
9388+ <UpdateMode>Foreground</UpdateMode>\r
9389+ <UpdateInterval>7</UpdateInterval>\r
9390+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
9391+ <UpdatePeriodically>false</UpdatePeriodically>\r
9392+ <UpdateRequired>false</UpdateRequired>\r
9393+ <MapFileExtensions>true</MapFileExtensions>\r
9394+ <ApplicationRevision>0</ApplicationRevision>\r
9395+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
9396+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
9397+ <UseApplicationTrust>false</UseApplicationTrust>\r
9398+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
9399+ <TargetFrameworkProfile />\r
9400 </PropertyGroup>\r
9401 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
9402 <DebugSymbols>true</DebugSymbols>\r
9403@@ -21,6 +41,7 @@
9404 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
9405 <ErrorReport>prompt</ErrorReport>\r
9406 <WarningLevel>4</WarningLevel>\r
9407+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
9408 </PropertyGroup>\r
9409 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
9410 <DebugType>pdbonly</DebugType>\r
9411@@ -29,6 +50,7 @@
9412 <DefineConstants>TRACE</DefineConstants>\r
9413 <ErrorReport>prompt</ErrorReport>\r
9414 <WarningLevel>4</WarningLevel>\r
9415+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
9416 </PropertyGroup>\r
9417 <ItemGroup>\r
9418 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
9419@@ -76,6 +98,23 @@
9420 <ItemGroup>\r
9421 <Folder Include="Properties\" />\r
9422 </ItemGroup>\r
9423+ <ItemGroup>\r
9424+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
9425+ <Visible>False</Visible>\r
9426+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
9427+ <Install>false</Install>\r
9428+ </BootstrapperPackage>\r
9429+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
9430+ <Visible>False</Visible>\r
9431+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
9432+ <Install>true</Install>\r
9433+ </BootstrapperPackage>\r
9434+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
9435+ <Visible>False</Visible>\r
9436+ <ProductName>Windows Installer 3.1</ProductName>\r
9437+ <Install>true</Install>\r
9438+ </BootstrapperPackage>\r
9439+ </ItemGroup>\r
9440 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
9441 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
9442 Other similar extension points exist, see Microsoft.Common.targets.
9443diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/UseGenericEventHandlerRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/UseGenericEventHandlerRule.cs
9444index 9535a2a..71083fd 100644
9445--- a/gendarme/rules/Gendarme.Rules.Design.Generic/UseGenericEventHandlerRule.cs
9446+++ b/gendarme/rules/Gendarme.Rules.Design.Generic/UseGenericEventHandlerRule.cs
9447@@ -38,8 +38,8 @@ using Gendarme.Framework.Rocks;
9448 namespace Gendarme.Rules.Design.Generic {
9449
9450 /// <summary>
9451- /// This rule fires if an assembly targets .NET 2.0 or later and defines a delegate
9452- /// which can be replaced by <c>System.EventHandler&lt;TEventArgs&gt;</c>.
9453+ /// This rule fires if an assembly defines a delegate which can be
9454+ /// replaced by <c>System.EventHandler&lt;TEventArgs&gt;</c>.
9455 /// </summary>
9456 /// <example>
9457 /// Bad example:
9458@@ -57,23 +57,11 @@ namespace Gendarme.Rules.Design.Generic {
9459 /// public event EventHandler&lt;AuthenticityEventArgs&gt; CheckedAuthenticity;
9460 /// </code>
9461 /// </example>
9462- /// <remarks>This rule is available since Gendarme 2.2</remarks>
9463-
9464+ /// <remarks>This rule applies only to assemblies targeting .NET 2.0 and later.</remarks>
9465 [Problem ("This delegate definition is not needed with .NET 2.0 and later runtimes.")]
9466 [Solution ("Replace the delegate with System.EventHandler<TEventArgs>.")]
9467 [FxCopCompatibility ("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances")]
9468- public class UseGenericEventHandlerRule : Rule, ITypeRule {
9469-
9470- public override void Initialize (IRunner runner)
9471- {
9472- base.Initialize (runner);
9473-
9474- // we only want to run this on assemblies that use 2.0 or later
9475- // since generics were not available before
9476- Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
9477- Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
9478- };
9479- }
9480+ public class UseGenericEventHandlerRule : GenericsBaseRule, ITypeRule {
9481
9482 public RuleResult CheckType (TypeDefinition type)
9483 {
9484@@ -86,7 +74,7 @@ namespace Gendarme.Rules.Design.Generic {
9485 if (invoke == null)
9486 return RuleResult.DoesNotApply;
9487
9488- if (invoke.ReturnType.FullName != "System.Void")
9489+ if (!invoke.ReturnType.IsNamed ("System", "Void"))
9490 return RuleResult.Success;
9491
9492 if (!invoke.HasParameters)
9493@@ -95,9 +83,9 @@ namespace Gendarme.Rules.Design.Generic {
9494 IList<ParameterDefinition> pdc = invoke.Parameters;
9495 if (pdc.Count != 2)
9496 return RuleResult.Success;
9497- if (pdc [0].ParameterType.FullName != "System.Object")
9498+ if (!pdc [0].ParameterType.IsNamed ("System", "Object"))
9499 return RuleResult.Success;
9500- if (!pdc [1].ParameterType.Inherits ("System.EventArgs"))
9501+ if (!pdc [1].ParameterType.Inherits ("System", "EventArgs"))
9502 return RuleResult.Success;
9503
9504 Runner.Report (type, Severity.Medium, Confidence.High);
9505diff --git a/gendarme/rules/Gendarme.Rules.Design.Linq/AvoidExtensionMethodOnSystemObjectRule.cs b/gendarme/rules/Gendarme.Rules.Design.Linq/AvoidExtensionMethodOnSystemObjectRule.cs
9506index a5935e0..a2f1308 100644
9507--- a/gendarme/rules/Gendarme.Rules.Design.Linq/AvoidExtensionMethodOnSystemObjectRule.cs
9508+++ b/gendarme/rules/Gendarme.Rules.Design.Linq/AvoidExtensionMethodOnSystemObjectRule.cs
9509@@ -77,8 +77,11 @@ namespace Gendarme.Rules.Design.Linq {
9510 // extension methods are only available in FX3.5
9511 // check runtime >= NET2_0 (fast) then check if [ExtensionAttribute] is referenced
9512 Runner.AnalyzeModule += (object o, RunnerEventArgs e) => {
9513- Active = e.CurrentModule.Runtime >= TargetRuntime.Net_2_0 &&
9514- e.CurrentModule.HasTypeReference ("System.Runtime.CompilerServices.ExtensionAttribute");
9515+ Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0 &&
9516+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
9517+ return tr.IsNamed ("System.Runtime.CompilerServices", "ExtensionAttribute");
9518+ })
9519+ );
9520 };
9521 }
9522
9523@@ -92,7 +95,7 @@ namespace Gendarme.Rules.Design.Linq {
9524 if (!method.HasParameters)
9525 return false;
9526
9527- return method.HasAttribute ("System.Runtime.CompilerServices.ExtensionAttribute");
9528+ return method.HasAttribute ("System.Runtime.CompilerServices", "ExtensionAttribute");
9529 }
9530
9531 public RuleResult CheckMethod (MethodDefinition method)
9532@@ -100,7 +103,7 @@ namespace Gendarme.Rules.Design.Linq {
9533 if (!IsExtension (method))
9534 return RuleResult.DoesNotApply;
9535
9536- if (method.Parameters [0].ParameterType.FullName != "System.Object")
9537+ if (!method.Parameters [0].ParameterType.IsNamed ("System", "Object"))
9538 return RuleResult.Success;
9539
9540 Runner.Report (method, Severity.High, Confidence.High);
9541diff --git a/gendarme/rules/Gendarme.Rules.Design.Linq/Gendarme.Rules.Design.Linq.csproj b/gendarme/rules/Gendarme.Rules.Design.Linq/Gendarme.Rules.Design.Linq.csproj
9542index 6a09a06..135c620 100644
9543--- a/gendarme/rules/Gendarme.Rules.Design.Linq/Gendarme.Rules.Design.Linq.csproj
9544+++ b/gendarme/rules/Gendarme.Rules.Design.Linq/Gendarme.Rules.Design.Linq.csproj
9545@@ -1,5 +1,5 @@
9546 <?xml version="1.0" encoding="utf-8"?>\r
9547-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
9548+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
9549 <PropertyGroup>\r
9550 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
9551 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
9552@@ -10,8 +10,28 @@
9553 <AppDesignerFolder>Properties</AppDesignerFolder>\r
9554 <RootNamespace>Gendarme.Rules.Design.Linq</RootNamespace>\r
9555 <AssemblyName>Gendarme.Rules.Design.Linq</AssemblyName>\r
9556- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
9557+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
9558 <FileAlignment>512</FileAlignment>\r
9559+ <FileUpgradeFlags>\r
9560+ </FileUpgradeFlags>\r
9561+ <OldToolsVersion>3.5</OldToolsVersion>\r
9562+ <UpgradeBackupLocation />\r
9563+ <PublishUrl>publish\</PublishUrl>\r
9564+ <Install>true</Install>\r
9565+ <InstallFrom>Disk</InstallFrom>\r
9566+ <UpdateEnabled>false</UpdateEnabled>\r
9567+ <UpdateMode>Foreground</UpdateMode>\r
9568+ <UpdateInterval>7</UpdateInterval>\r
9569+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
9570+ <UpdatePeriodically>false</UpdatePeriodically>\r
9571+ <UpdateRequired>false</UpdateRequired>\r
9572+ <MapFileExtensions>true</MapFileExtensions>\r
9573+ <ApplicationRevision>0</ApplicationRevision>\r
9574+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
9575+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
9576+ <UseApplicationTrust>false</UseApplicationTrust>\r
9577+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
9578+ <TargetFrameworkProfile />\r
9579 </PropertyGroup>\r
9580 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
9581 <DebugSymbols>true</DebugSymbols>\r
9582@@ -24,6 +44,7 @@
9583 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Design.Linq.xml</DocumentationFile>\r
9584 <NoWarn>1591</NoWarn>\r
9585 <WarningsAsErrors>1570</WarningsAsErrors>\r
9586+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
9587 </PropertyGroup>\r
9588 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
9589 <DebugType>pdbonly</DebugType>\r
9590@@ -35,6 +56,7 @@
9591 <NoWarn>1591</NoWarn>\r
9592 <WarningsAsErrors>1570</WarningsAsErrors>\r
9593 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Design.Linq.xml</DocumentationFile>\r
9594+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
9595 </PropertyGroup>\r
9596 <ItemGroup>\r
9597 <Reference Include="System" />\r
9598@@ -58,6 +80,23 @@
9599 <Name>Gendarme.Framework</Name>\r
9600 </ProjectReference>\r
9601 </ItemGroup>\r
9602+ <ItemGroup>\r
9603+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
9604+ <Visible>False</Visible>\r
9605+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
9606+ <Install>false</Install>\r
9607+ </BootstrapperPackage>\r
9608+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
9609+ <Visible>False</Visible>\r
9610+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
9611+ <Install>true</Install>\r
9612+ </BootstrapperPackage>\r
9613+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
9614+ <Visible>False</Visible>\r
9615+ <ProductName>Windows Installer 3.1</ProductName>\r
9616+ <Install>true</Install>\r
9617+ </BootstrapperPackage>\r
9618+ </ItemGroup>\r
9619 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
9620 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
9621 Other similar extension points exist, see Microsoft.Common.targets.\r
9622diff --git a/gendarme/rules/Gendarme.Rules.Design.Linq/README.md b/gendarme/rules/Gendarme.Rules.Design.Linq/README.md
9623new file mode 100644
9624index 0000000..d80660c
9625--- /dev/null
9626+++ b/gendarme/rules/Gendarme.Rules.Design.Linq/README.md
9627@@ -0,0 +1,9 @@
9628+# Gendarme.Rules.Design.Linq Rules
9629+
9630+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design.Linq(git)]] pages.
9631+
9632+
9633+## Feedback
9634+
9635+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
9636+
9637diff --git a/gendarme/rules/Gendarme.Rules.Design.Linq/Test/Tests.Rules.Design.Linq.csproj b/gendarme/rules/Gendarme.Rules.Design.Linq/Test/Tests.Rules.Design.Linq.csproj
9638index 2a013ee..10db1dc 100644
9639--- a/gendarme/rules/Gendarme.Rules.Design.Linq/Test/Tests.Rules.Design.Linq.csproj
9640+++ b/gendarme/rules/Gendarme.Rules.Design.Linq/Test/Tests.Rules.Design.Linq.csproj
9641@@ -1,5 +1,5 @@
9642 <?xml version="1.0" encoding="utf-8"?>\r
9643-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
9644+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
9645 <PropertyGroup>\r
9646 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
9647 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
9648@@ -10,8 +10,28 @@
9649 <AppDesignerFolder>Properties</AppDesignerFolder>\r
9650 <RootNamespace>Tests.Rules.Design.Linq</RootNamespace>\r
9651 <AssemblyName>Tests.Rules.Design.Linq</AssemblyName>\r
9652- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
9653+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
9654 <FileAlignment>512</FileAlignment>\r
9655+ <FileUpgradeFlags>\r
9656+ </FileUpgradeFlags>\r
9657+ <OldToolsVersion>3.5</OldToolsVersion>\r
9658+ <UpgradeBackupLocation />\r
9659+ <PublishUrl>publish\</PublishUrl>\r
9660+ <Install>true</Install>\r
9661+ <InstallFrom>Disk</InstallFrom>\r
9662+ <UpdateEnabled>false</UpdateEnabled>\r
9663+ <UpdateMode>Foreground</UpdateMode>\r
9664+ <UpdateInterval>7</UpdateInterval>\r
9665+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
9666+ <UpdatePeriodically>false</UpdatePeriodically>\r
9667+ <UpdateRequired>false</UpdateRequired>\r
9668+ <MapFileExtensions>true</MapFileExtensions>\r
9669+ <ApplicationRevision>0</ApplicationRevision>\r
9670+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
9671+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
9672+ <UseApplicationTrust>false</UseApplicationTrust>\r
9673+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
9674+ <TargetFrameworkProfile />\r
9675 </PropertyGroup>\r
9676 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
9677 <DebugSymbols>true</DebugSymbols>\r
9678@@ -21,6 +41,7 @@
9679 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
9680 <ErrorReport>prompt</ErrorReport>\r
9681 <WarningLevel>4</WarningLevel>\r
9682+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
9683 </PropertyGroup>\r
9684 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
9685 <DebugType>pdbonly</DebugType>\r
9686@@ -29,6 +50,7 @@
9687 <DefineConstants>TRACE</DefineConstants>\r
9688 <ErrorReport>prompt</ErrorReport>\r
9689 <WarningLevel>4</WarningLevel>\r
9690+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
9691 </PropertyGroup>\r
9692 <ItemGroup>\r
9693 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
9694@@ -68,6 +90,23 @@
9695 <ItemGroup>\r
9696 <Folder Include="Properties\" />\r
9697 </ItemGroup>\r
9698+ <ItemGroup>\r
9699+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
9700+ <Visible>False</Visible>\r
9701+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
9702+ <Install>false</Install>\r
9703+ </BootstrapperPackage>\r
9704+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
9705+ <Visible>False</Visible>\r
9706+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
9707+ <Install>true</Install>\r
9708+ </BootstrapperPackage>\r
9709+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
9710+ <Visible>False</Visible>\r
9711+ <ProductName>Windows Installer 3.1</ProductName>\r
9712+ <Install>true</Install>\r
9713+ </BootstrapperPackage>\r
9714+ </ItemGroup>\r
9715 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
9716 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
9717 Other similar extension points exist, see Microsoft.Common.targets.
9718diff --git a/gendarme/rules/Gendarme.Rules.Design/AttributeArgumentsShouldHaveAccessorsRule.cs b/gendarme/rules/Gendarme.Rules.Design/AttributeArgumentsShouldHaveAccessorsRule.cs
9719index df472de..cc037aa 100644
9720--- a/gendarme/rules/Gendarme.Rules.Design/AttributeArgumentsShouldHaveAccessorsRule.cs
9721+++ b/gendarme/rules/Gendarme.Rules.Design/AttributeArgumentsShouldHaveAccessorsRule.cs
9722@@ -26,6 +26,7 @@
9723
9724 using System;
9725 using System.Collections.Generic;
9726+using System.Globalization;
9727
9728 using Mono.Cecil;
9729
9730@@ -106,11 +107,18 @@ namespace Gendarme.Rules.Design {
9731
9732 // look through getters
9733 allProperties.Clear ();
9734- foreach (PropertyDefinition property in type.Properties) {
9735- if (property.GetMethod != null) {
9736- allProperties.Add (property.Name);
9737+
9738+ TypeDefinition t = type;
9739+ // Walk up the inheritance tree so that inherited properties are counted
9740+ do
9741+ {
9742+ foreach (PropertyDefinition property in t.Properties) {
9743+ if (property.GetMethod != null) {
9744+ allProperties.Add (property.Name);
9745+ }
9746 }
9747- }
9748+ t = t.BaseType != null ? t.BaseType.Resolve () : null;
9749+ } while (t != null && !t.IsNamed ("System", "Attribute"));
9750
9751 // look through parameters
9752 foreach (MethodDefinition constructor in type.Methods) {
9753@@ -119,9 +127,11 @@ namespace Gendarme.Rules.Design {
9754
9755 foreach (ParameterDefinition param in constructor.Parameters) {
9756 // pascal case it
9757- string correspondingPropertyName = Char.ToUpper (param.Name [0]).ToString () + param.Name.Substring (1);
9758+ string correspondingPropertyName = Char.ToUpper (param.Name [0], CultureInfo.InvariantCulture).ToString (CultureInfo.InvariantCulture) +
9759+ param.Name.Substring (1);
9760 if (!allProperties.Contains (correspondingPropertyName)) {
9761- string s = String.Format ("Add '{0}' property to the attribute class.", correspondingPropertyName);
9762+ string s = String.Format (CultureInfo.InvariantCulture,
9763+ "Add '{0}' property to the attribute class.", correspondingPropertyName);
9764 Runner.Report (param, Severity.Medium, Confidence.High, s);
9765 allProperties.Add (correspondingPropertyName); // to avoid double catching same property (e.g. from different constructors)
9766 }
9767diff --git a/gendarme/rules/Gendarme.Rules.Design/AvoidPublicInstanceFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Design/AvoidPublicInstanceFieldsRule.cs
9768index 0641913..9932c47 100644
9769--- a/gendarme/rules/Gendarme.Rules.Design/AvoidPublicInstanceFieldsRule.cs
9770+++ b/gendarme/rules/Gendarme.Rules.Design/AvoidPublicInstanceFieldsRule.cs
9771@@ -25,6 +25,7 @@
9772 // THE SOFTWARE.
9773
9774 using System;
9775+using System.Globalization;
9776
9777 using Mono.Cecil;
9778
9779@@ -89,11 +90,13 @@ namespace Gendarme.Rules.Design {
9780
9781 string name = fd.Name;
9782 if (fd.FieldType.IsArray) {
9783- string s = String.Format ("Consider changing the field '{0}' to a private or internal field and add a 'Set{1}{2}' method.",
9784- name, Char.ToUpper (name [0]).ToString (), name.Substring (1));
9785+ string s = String.Format (CultureInfo.InvariantCulture,
9786+ "Consider changing the field '{0}' to a private or internal field and add a 'Set{1}{2}' method.",
9787+ name, Char.ToUpper (name [0], CultureInfo.InvariantCulture).ToString (CultureInfo.InvariantCulture), name.Substring (1));
9788 Runner.Report (fd, Severity.Medium, Confidence.Total, s);
9789 } else {
9790- string s = String.Format ("Field '{0}' should be private or internal and its value accessed through a property.", name);
9791+ string s = String.Format (CultureInfo.InvariantCulture,
9792+ "Field '{0}' should be private or internal and its value accessed through a property.", name);
9793 Runner.Report (fd, Severity.Medium, Confidence.Total, s);
9794 }
9795 }
9796diff --git a/gendarme/rules/Gendarme.Rules.Design/AvoidRefAndOutParametersRule.cs b/gendarme/rules/Gendarme.Rules.Design/AvoidRefAndOutParametersRule.cs
9797index 2e86234..b8828e9 100644
9798--- a/gendarme/rules/Gendarme.Rules.Design/AvoidRefAndOutParametersRule.cs
9799+++ b/gendarme/rules/Gendarme.Rules.Design/AvoidRefAndOutParametersRule.cs
9800@@ -27,6 +27,7 @@
9801 //
9802
9803 using System;
9804+using System.Globalization;
9805 using Mono.Cecil;
9806
9807 using Gendarme.Framework;
9808@@ -139,7 +140,7 @@ namespace Gendarme.Rules.Design {
9809 string how = null;
9810 if (parameter.IsOut) {
9811 // out is permitted for the "bool Try* (...)" pattern
9812- if ((method.ReturnType.FullName == "System.Boolean") &&
9813+ if (method.ReturnType.IsNamed ("System", "Boolean") &&
9814 method.Name.StartsWith ("Try", StringComparison.Ordinal)) {
9815 continue;
9816 }
9817@@ -153,7 +154,8 @@ namespace Gendarme.Rules.Design {
9818 if ((how != null) && !IsSignatureDictatedByInterface (method)) {
9819 // goal is to keep the API as simple as possible so this is more severe for public than protected methods
9820 Severity severity = method.IsPublic ? Severity.Medium : Severity.Low;
9821- string msg = String.Format ("Parameter '{0}' passed by reference ({1}).", parameter.Name, how);
9822+ string msg = String.Format (CultureInfo.InvariantCulture,
9823+ "Parameter '{0}' passed by reference ({1}).", parameter.Name, how);
9824 Runner.Report (parameter, severity, Confidence.Total, msg);
9825 }
9826 }
9827diff --git a/gendarme/rules/Gendarme.Rules.Design/AvoidSmallNamespaceRule.cs b/gendarme/rules/Gendarme.Rules.Design/AvoidSmallNamespaceRule.cs
9828index 138b556..76f590a 100644
9829--- a/gendarme/rules/Gendarme.Rules.Design/AvoidSmallNamespaceRule.cs
9830+++ b/gendarme/rules/Gendarme.Rules.Design/AvoidSmallNamespaceRule.cs
9831@@ -29,6 +29,7 @@
9832 using System;
9833 using System.Collections.Generic;
9834 using System.ComponentModel;
9835+using System.Globalization;
9836
9837 using Mono.Cecil;
9838
9839@@ -164,7 +165,8 @@ namespace Gendarme.Rules.Design {
9840 // e.g. VS.NET adds a .Properties namespace to SWF apps
9841 if ((count > 0) && (count < Minimum)) {
9842 NamespaceDefinition n = NamespaceDefinition.GetDefinition (ns);
9843- string msg = String.Format ("Only {0} visible types are defined inside this namespace.", count);
9844+ string msg = String.Format (CultureInfo.CurrentCulture,
9845+ "Only {0} visible types are defined inside this namespace.", count);
9846 // overloads of Report cannot be used here since the 'target' has been lost in the runner
9847 Runner.Report (new Defect (this, n, n, Severity.Low, Confidence.Total, msg));
9848 }
9849diff --git a/gendarme/rules/Gendarme.Rules.Design/ConsiderAddingInterfaceRule.cs b/gendarme/rules/Gendarme.Rules.Design/ConsiderAddingInterfaceRule.cs
9850index 342218f..ddcb92a 100644
9851--- a/gendarme/rules/Gendarme.Rules.Design/ConsiderAddingInterfaceRule.cs
9852+++ b/gendarme/rules/Gendarme.Rules.Design/ConsiderAddingInterfaceRule.cs
9853@@ -28,6 +28,7 @@
9854
9855 using System;
9856 using System.Collections.Generic;
9857+using System.Globalization;
9858 using System.Linq;
9859
9860 using Mono.Cecil;
9861@@ -143,7 +144,8 @@ namespace Gendarme.Rules.Design {
9862 if (HasConstraints (type))
9863 continue;
9864 if (DoesTypeStealthilyImplementInterface (type, iface)) {
9865- string msg = string.Format ("Type implements '{0}' interface but does not declare it.", iface);
9866+ string msg = string.Format (CultureInfo.InvariantCulture,
9867+ "Type implements '{0}' interface but does not declare it.", iface);
9868 // use our own Defect since the *real* target (of analysis) is 'type' not 'iface'
9869 Runner.Report (new Defect (this, type, type, Severity.Medium, Confidence.High, msg));
9870 }
9871@@ -165,7 +167,7 @@ namespace Gendarme.Rules.Design {
9872 return false;
9873
9874 //type already publicly says it implements the interface
9875- if (type.Implements (iface.FullName))
9876+ if (type.Implements (iface.Namespace, iface.Name))
9877 return false;
9878
9879 foreach (MethodDefinition m in mdc) {
9880diff --git a/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingFieldToNullableRule.cs b/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingFieldToNullableRule.cs
9881index 453fc23..e5ffcfc 100644
9882--- a/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingFieldToNullableRule.cs
9883+++ b/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingFieldToNullableRule.cs
9884@@ -25,6 +25,7 @@
9885 // THE SOFTWARE.
9886
9887 using System;
9888+using System.Globalization;
9889
9890 using Mono.Cecil;
9891
9892@@ -75,7 +76,7 @@ namespace Gendarme.Rules.Design {
9893
9894 static bool IsHasField (FieldReference fd, ref string prefix, ref string suffix)
9895 {
9896- if (fd.FieldType.FullName != "System.Boolean")
9897+ if (!fd.FieldType.IsNamed ("System", "Boolean"))
9898 return false;
9899
9900 string name = fd.Name;
9901@@ -122,7 +123,9 @@ namespace Gendarme.Rules.Design {
9902 && HasValueTypeField(type, string.Concat(prefix,suffix)) ) {
9903 //TODO: check if they are both used in the same method? does the complexity worth it?
9904 string s = (Runner.VerbosityLevel > 0)
9905- ? String.Format ("Field '{0}' should probably be a nullable if '{1}' purpose is to inform if '{0}' has been set.", fd.Name, suffix)
9906+ ? String.Format (CultureInfo.InvariantCulture,
9907+ "Field '{0}' should probably be a nullable if '{1}' purpose is to inform if '{0}' has been set.",
9908+ fd.Name, suffix)
9909 : string.Empty;
9910 Runner.Report (fd, Severity.Low, Confidence.Low, s);
9911 }
9912@@ -140,7 +143,7 @@ namespace Gendarme.Rules.Design {
9913 {
9914 foreach (FieldDefinition field in type.Fields) {
9915 if (field.FieldType.IsValueType
9916- && "System.Nullable`1" != field.FieldType.GetElementType().FullName
9917+ && !field.FieldType.GetElementType ().IsNamed ("System", "Nullable`1")
9918 && 0 == string.Compare(name, field.Name, StringComparison.OrdinalIgnoreCase))
9919 return field;
9920 }
9921diff --git a/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingMethodToPropertyRule.cs b/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingMethodToPropertyRule.cs
9922index 9d4ebbe..01622f4 100644
9923--- a/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingMethodToPropertyRule.cs
9924+++ b/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingMethodToPropertyRule.cs
9925@@ -90,9 +90,9 @@ namespace Gendarme.Rules.Design {
9926 string ReportAssociatedSetter (MethodDefinition getter)
9927 {
9928 string name = "Set" + getter.Name.Substring (3);
9929- parameter [0] = getter.ReturnType.FullName;
9930+ parameter [0] = getter.ReturnType.GetFullName ();
9931 MethodDefinition setter = getter.DeclaringType.GetMethod (name, Void, parameter);
9932- return setter == null ? String.Empty : setter.ToString ();
9933+ return setter == null ? String.Empty : setter.GetFullName ();
9934 }
9935
9936 public RuleResult CheckMethod (MethodDefinition method)
9937@@ -130,7 +130,7 @@ namespace Gendarme.Rules.Design {
9938 bool get = name.StartsWith ("get", StringComparison.OrdinalIgnoreCase);
9939 bool isp = name.StartsWith ("is", StringComparison.OrdinalIgnoreCase);
9940 bool has = name.StartsWith ("has", StringComparison.OrdinalIgnoreCase);
9941- if ((get || isp || has) && (method.Parameters.Count == 0) && (return_type.FullName != Void)) {
9942+ if ((get || isp || has) && !method.HasParameters && !return_type.IsNamed ("System", "Void")) {
9943 // if it's a getter then look for a setter (to complete the report)
9944 string msg = get ? ReportAssociatedSetter (method) : String.Empty;
9945 Runner.Report (method, Severity.Low, Confidence.Normal, msg);
9946diff --git a/gendarme/rules/Gendarme.Rules.Design/ConsiderUsingStaticTypeRule.cs b/gendarme/rules/Gendarme.Rules.Design/ConsiderUsingStaticTypeRule.cs
9947index d6a5691..d024c20 100644
9948--- a/gendarme/rules/Gendarme.Rules.Design/ConsiderUsingStaticTypeRule.cs
9949+++ b/gendarme/rules/Gendarme.Rules.Design/ConsiderUsingStaticTypeRule.cs
9950@@ -4,7 +4,7 @@
9951 // Authors:
9952 // Sebastien Pouliot <sebastien@ximian.com>
9953 //
9954-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
9955+// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
9956 //
9957 // Permission is hereby granted, free of charge, to any person obtaining
9958 // a copy of this software and associated documentation files (the
9959@@ -37,8 +37,8 @@ namespace Gendarme.Rules.Design {
9960
9961 /// <summary>
9962 /// This rule checks for types that contain only static members and, if the assembly
9963- /// targets the CLR version 2.0 or later, suggests that the type be made <c>static</c>.
9964- /// The rule will ignore assemblies targeting earlier versions of the CLR.
9965+ /// targets the CLR version 2.0 or later, suggests that the type be made <c>static</c>
9966+ /// or, for earlier versions, that the type be made <c>sealed</c>.
9967 /// </summary>
9968 /// <example>
9969 /// Bad example:
9970@@ -51,7 +51,7 @@ namespace Gendarme.Rules.Design {
9971 /// </code>
9972 /// </example>
9973 /// <example>
9974- /// Good example:
9975+ /// Good example (targetting CLR 2.0 and later):
9976 /// <code>
9977 /// public static class Class {
9978 /// public static void Method ()
9979@@ -60,22 +60,22 @@ namespace Gendarme.Rules.Design {
9980 /// }
9981 /// </code>
9982 /// </example>
9983+ /// <example>
9984+ /// Good example (targetting CLR 1.x):
9985+ /// <code>
9986+ /// public sealed class Class {
9987+ /// public static void Method ()
9988+ /// {
9989+ /// }
9990+ /// }
9991+ /// </code>
9992+ /// </example>
9993
9994 [Problem ("This type contains only static fields and methods and should be static.")]
9995- [Solution ("Change this type into a static type to gain clarity and better error reporting.")]
9996+ [Solution ("Change this type into a static (or sealed for 1.x) type gain clarity and better error reporting.")]
9997+ [FxCopCompatibility ("Microsoft.Design", "CA1052:StaticHolderTypesShouldBeSealed")]
9998 public class ConsiderUsingStaticTypeRule : Rule, ITypeRule {
9999
10000- public override void Initialize (IRunner runner)
10001- {
10002- base.Initialize (runner);
10003-
10004- // Static type exists only since 2.0 so there's no point to execute this
10005- // rule on every type if the assembly target runtime is earlier than 2.0
10006- Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
10007- Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
10008- };
10009- }
10010-
10011 static bool IsAllStatic (TypeDefinition type)
10012 {
10013 if (type.HasMethods) {
10014@@ -99,31 +99,15 @@ namespace Gendarme.Rules.Design {
10015 return true;
10016 }
10017
10018- static int GetMethodCount (TypeDefinition type)
10019- {
10020- if (!type.HasMethods)
10021- return 0;
10022-
10023- int methods = 0;
10024-
10025- foreach (var method in type.Methods) {
10026- if (!method.IsConstructor)
10027- methods++;
10028- }
10029-
10030- return methods;
10031- }
10032-
10033 public RuleResult CheckType (TypeDefinition type)
10034 {
10035 // rule applies only if the type isn't: an enum, an interface, a struct, a delegate or compiler generated
10036- if (type.IsEnum || type.IsInterface || type.IsValueType || !type.HasFields && GetMethodCount (type) == 0
10037- || type.IsDelegate () || type.IsGeneratedCode ()
10038- || type.BaseType != null && type.BaseType.FullName != "System.Object")
10039+ if (type.IsEnum || type.IsInterface || type.IsValueType || type.IsDelegate () || type.IsGeneratedCode ()
10040+ || type.BaseType != null && !type.BaseType.IsNamed ("System", "Object"))
10041 return RuleResult.DoesNotApply;
10042
10043- // success if the type is already static
10044- if (type.IsStatic ())
10045+ // success if the type is already static or, before 2.0, is it's sealed
10046+ if ((type.Module.Runtime >= TargetRuntime.Net_2_0) ? type.IsStatic () : type.IsSealed)
10047 return RuleResult.Success;
10048
10049 if (IsAllStatic (type)) {
10050diff --git a/gendarme/rules/Gendarme.Rules.Design/DeclareEventHandlersCorrectlyRule.cs b/gendarme/rules/Gendarme.Rules.Design/DeclareEventHandlersCorrectlyRule.cs
10051index 82386a2..d6cf62b 100644
10052--- a/gendarme/rules/Gendarme.Rules.Design/DeclareEventHandlersCorrectlyRule.cs
10053+++ b/gendarme/rules/Gendarme.Rules.Design/DeclareEventHandlersCorrectlyRule.cs
10054@@ -28,6 +28,7 @@
10055
10056 using System;
10057 using System.Collections.Generic;
10058+using System.Globalization;
10059 using Gendarme.Framework;
10060 using Gendarme.Framework.Rocks;
10061 using Gendarme.Framework.Helpers;
10062@@ -85,11 +86,12 @@ namespace Gendarme.Rules.Design {
10063
10064 private bool CheckReturnVoid (IMetadataTokenProvider eventType, IMethodSignature invoke)
10065 {
10066- string full_name = invoke.ReturnType.FullName;
10067- if (String.Compare (full_name, "System.Void") == 0)
10068+ TypeReference rtype = invoke.ReturnType;
10069+ if (rtype.IsNamed ("System", "Void"))
10070 return true;
10071
10072- string msg = String.Format ("The delegate should return void, not {0}", full_name);
10073+ string msg = String.Format (CultureInfo.InvariantCulture,
10074+ "The delegate should return void, not {0}", rtype.GetFullName ());
10075 Runner.Report (eventType, Severity.Medium, Confidence.High, msg);
10076 return false;
10077 }
10078@@ -112,14 +114,16 @@ namespace Gendarme.Rules.Design {
10079 IList<ParameterDefinition> pdc = invoke.Parameters;
10080 int count = pdc.Count;
10081 if (count >= 1) {
10082- string type_name = pdc [0].ParameterType.FullName;
10083- if (String.Compare (type_name, "System.Object") != 0) {
10084- Runner.Report (eventType, Severity.Medium, Confidence.High, String.Format ("The first parameter should have an object, not {0}", type_name));
10085+ TypeReference ptype = pdc [0].ParameterType;
10086+ if (!ptype.IsNamed ("System", "Object")) {
10087+ string msg = String.Format (CultureInfo.InvariantCulture,
10088+ "The first parameter should have an object, not {0}", ptype.GetFullName ());
10089+ Runner.Report (eventType, Severity.Medium, Confidence.High, msg);
10090 ok = false;
10091 }
10092 }
10093 if (count >= 2) {
10094- if (!pdc [1].ParameterType.Inherits ("System.EventArgs")) {
10095+ if (!pdc [1].ParameterType.Inherits ("System", "EventArgs")) {
10096 Runner.Report (eventType, Severity.Medium, Confidence.High, "The second parameter should be a subclass of System.EventArgs");
10097 ok = false;
10098 }
10099@@ -129,10 +133,12 @@ namespace Gendarme.Rules.Design {
10100
10101 private bool CheckParameterName (IMetadataTokenProvider eventType, ParameterReference invokeParameter, string expectedName)
10102 {
10103- if (String.Compare (invokeParameter.Name, expectedName) == 0)
10104+ if (invokeParameter.Name == expectedName)
10105 return true;
10106
10107- Runner.Report (eventType, Severity.Low, Confidence.High, String.Format ("The expected name is {0}, not {1}", expectedName, invokeParameter.Name));
10108+ string msg = String.Format (CultureInfo.InvariantCulture, "The expected name is {0}, not {1}",
10109+ expectedName, invokeParameter.Name);
10110+ Runner.Report (eventType, Severity.Low, Confidence.High, msg);
10111 return false;
10112 }
10113
10114@@ -189,9 +195,9 @@ namespace Gendarme.Rules.Design {
10115 return valid;
10116 }
10117
10118- private bool CheckGenericDelegate (MemberReference type)
10119+ private bool CheckGenericDelegate (TypeReference type)
10120 {
10121- if (type.FullName == "System.EventHandler`1")
10122+ if (type.IsNamed ("System", "EventHandler`1"))
10123 return true;
10124
10125 Runner.Report (type, Severity.Medium, Confidence.High, "Generic delegates should use EventHandler<TEventArgs>");
10126diff --git a/gendarme/rules/Gendarme.Rules.Design/DisposableTypesShouldHaveFinalizerRule.cs b/gendarme/rules/Gendarme.Rules.Design/DisposableTypesShouldHaveFinalizerRule.cs
10127index 56133c9..dff2b48 100644
10128--- a/gendarme/rules/Gendarme.Rules.Design/DisposableTypesShouldHaveFinalizerRule.cs
10129+++ b/gendarme/rules/Gendarme.Rules.Design/DisposableTypesShouldHaveFinalizerRule.cs
10130@@ -75,7 +75,7 @@ namespace Gendarme.Rules.Design {
10131 return RuleResult.DoesNotApply;
10132
10133 // rule onyly applies to type that implements IDisposable
10134- if (!type.Implements ("System.IDisposable"))
10135+ if (!type.Implements ("System", "IDisposable"))
10136 return RuleResult.DoesNotApply;
10137
10138 // no problem is a finalizer is found
10139diff --git a/gendarme/rules/Gendarme.Rules.Design/DoNotDeclareSettersOnCollectionPropertiesRule.cs b/gendarme/rules/Gendarme.Rules.Design/DoNotDeclareSettersOnCollectionPropertiesRule.cs
10140new file mode 100644
10141index 0000000..37c7b8c
10142--- /dev/null
10143+++ b/gendarme/rules/Gendarme.Rules.Design/DoNotDeclareSettersOnCollectionPropertiesRule.cs
10144@@ -0,0 +1,124 @@
10145+//
10146+// Gendarme.Rules.Design.DoNotDeclareSettersOnCollectionPropertiesRule
10147+//
10148+// Authors:
10149+// Sebastien Pouliot <sebastien@ximian.com>
10150+//
10151+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
10152+//
10153+// Permission is hereby granted, free of charge, to any person obtaining a copy
10154+// of this software and associated documentation files (the "Software"), to deal
10155+// in the Software without restriction, including without limitation the rights
10156+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10157+// copies of the Software, and to permit persons to whom the Software is
10158+// furnished to do so, subject to the following conditions:
10159+//
10160+// The above copyright notice and this permission notice shall be included in
10161+// all copies or substantial portions of the Software.
10162+//
10163+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
10164+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
10165+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
10166+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
10167+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10168+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10169+// THE SOFTWARE.
10170+
10171+using Mono.Cecil;
10172+
10173+using Gendarme.Framework;
10174+using Gendarme.Framework.Rocks;
10175+
10176+namespace Gendarme.Rules.Design {
10177+
10178+ /// <summary>
10179+ /// The rule detect <c>System.Collections.ICollection</c> and
10180+ /// <c>System.Collections.Generic.ICollection&lt;T&gt;</c> properties that declare a visible setter.
10181+ /// There is rarely a need to be able to replace the collection (e.g. most collections provide a <c>Clear</c>
10182+ /// method) and having a getter only does not prevent the consumer from adding and removing items in the collection.
10183+ /// Also read-only properties have special support for binary and XML serialization, making your code more useful.
10184+ /// A special exception is made for <c>System.Security.PermissionSet</c> and types that derives from it.
10185+ /// </summary>
10186+ /// <example>
10187+ /// Bad example:
10188+ /// <code>
10189+ /// public class Holder {
10190+ /// public string Name { get; set; }
10191+ /// public ICollection&lt;string&gt; List { get; set; }
10192+ /// }
10193+ ///
10194+ /// public static Holder Copy (Holder h)
10195+ /// {
10196+ /// Holder copy = new Holder ();
10197+ /// copy.Name = h.Name;
10198+ /// // bad, same list would be shared between instances
10199+ /// copy.List = h.List;
10200+ /// copy.List.AddRange (h.List);
10201+ /// return copy;
10202+ /// }
10203+ /// </code>
10204+ /// </example>
10205+ /// <example>
10206+ /// Good example:
10207+ /// <code>
10208+ /// public class Holder {
10209+ /// List&lt;string&gt; list;
10210+ ///
10211+ /// public Holder ()
10212+ /// {
10213+ /// list = new List&lt;string&gt; ();
10214+ /// }
10215+ ///
10216+ /// public string Name { get; set; }
10217+ ///
10218+ /// public ICollection&lt;string&gt; List {
10219+ /// get { return list; }
10220+ /// }
10221+ /// }
10222+ ///
10223+ /// public static Holder Copy (Holder h)
10224+ /// {
10225+ /// Holder copy = new Holder ();
10226+ /// copy.Name = h.Name;
10227+ /// copy.List.AddRange (h.List);
10228+ /// return copy;
10229+ /// }
10230+ /// </code>
10231+ /// </example>
10232+ [Problem ("A visible setter is declared for an ICollection (or derived) property")]
10233+ [Solution ("Replace the setter with a method or decrease the setter visibility")]
10234+ [FxCopCompatibility ("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
10235+ public class DoNotDeclareSettersOnCollectionPropertiesRule : Rule, ITypeRule {
10236+
10237+ static bool IsICollection (TypeReference type)
10238+ {
10239+ if (type.Implements ("System.Collections", "ICollection"))
10240+ return true;
10241+
10242+ return type.Implements ("System.Collections.Generic", "ICollection`1");
10243+ }
10244+
10245+ static bool IsSpecialCase (TypeReference type)
10246+ {
10247+ return type.Inherits ("System.Security", "PermissionSet");
10248+ }
10249+
10250+ public RuleResult CheckType (TypeDefinition type)
10251+ {
10252+ if (!type.HasProperties || !type.IsVisible ())
10253+ return RuleResult.DoesNotApply;
10254+
10255+ bool is_interface = type.IsInterface;
10256+ foreach (PropertyDefinition pd in type.Properties) {
10257+ MethodDefinition setter = pd.SetMethod;
10258+ if ((setter == null) || (!is_interface && !setter.IsVisible ()))
10259+ continue;
10260+
10261+ TypeReference ptype = pd.PropertyType;
10262+ if (IsICollection (ptype) && !IsSpecialCase (ptype))
10263+ Runner.Report (setter, Severity.Medium, Confidence.High);
10264+ }
10265+ return Runner.CurrentRuleResult;
10266+ }
10267+ }
10268+}
10269diff --git a/gendarme/rules/Gendarme.Rules.Design/EnsureSymmetryForOverloadedOperatorsRule.cs b/gendarme/rules/Gendarme.Rules.Design/EnsureSymmetryForOverloadedOperatorsRule.cs
10270index 7f45898..33d8fce 100644
10271--- a/gendarme/rules/Gendarme.Rules.Design/EnsureSymmetryForOverloadedOperatorsRule.cs
10272+++ b/gendarme/rules/Gendarme.Rules.Design/EnsureSymmetryForOverloadedOperatorsRule.cs
10273@@ -28,6 +28,7 @@
10274
10275 using System;
10276 using System.Collections.Generic;
10277+using System.Globalization;
10278 using Mono.Cecil;
10279
10280 using Gendarme.Framework;
10281@@ -124,7 +125,7 @@ namespace Gendarme.Rules.Design {
10282 return; //both are defined
10283 }
10284
10285- string s = string.Format (Message, pair.Key.Name, pair.Value.Name);
10286+ string s = string.Format (CultureInfo.InvariantCulture, Message, pair.Key.Name, pair.Value.Name);
10287 Runner.Report (op, severity, Confidence.Total, s);
10288 }
10289 }
10290diff --git a/gendarme/rules/Gendarme.Rules.Design/EnumeratorsShouldBeStronglyTypedRule.cs b/gendarme/rules/Gendarme.Rules.Design/EnumeratorsShouldBeStronglyTypedRule.cs
10291index 815b329..a3bc8e4 100644
10292--- a/gendarme/rules/Gendarme.Rules.Design/EnumeratorsShouldBeStronglyTypedRule.cs
10293+++ b/gendarme/rules/Gendarme.Rules.Design/EnumeratorsShouldBeStronglyTypedRule.cs
10294@@ -78,29 +78,40 @@ namespace Gendarme.Rules.Design {
10295 [FxCopCompatibility ("Microsoft.Design", "CA1038:EnumeratorsShouldBeStronglyTyped")]
10296 public class EnumeratorsShouldBeStronglyTypedRule : StronglyTypedRule, ITypeRule {
10297
10298+ private MethodSignature [] Empty = { };
10299+ private static string [] Current = { "Current" };
10300+
10301 protected override MethodSignature [] GetMethods ()
10302 {
10303- return new MethodSignature [] { };
10304+ return Empty;
10305 }
10306
10307 protected override string [] GetProperties ()
10308 {
10309- return new string [] { "Current" };
10310+ return Current;
10311 }
10312
10313 protected override string InterfaceName {
10314- get { return "System.Collections.IEnumerator"; }
10315+ get { return "IEnumerator"; }
10316+ }
10317+
10318+ protected override string InterfaceNamespace {
10319+ get { return "System.Collections"; }
10320 }
10321
10322 override public RuleResult CheckType (TypeDefinition type)
10323 {
10324 TypeReference baseType = type;
10325 while (baseType != null) {
10326- string name = baseType.FullName;
10327- if (name == "System.Collections.CollectionBase" ||
10328- name == "System.Collections.DictionaryBase" ||
10329- name == "System.Collections.ReadOnlyCollectionBase")
10330- return RuleResult.DoesNotApply;
10331+ if (baseType.Namespace == "System.Collections") {
10332+ switch (baseType.Name) {
10333+ case "CollectionBase":
10334+ case "DictionaryBase":
10335+ case "ReadOnlyCollectionBase":
10336+ return RuleResult.DoesNotApply;
10337+ }
10338+ }
10339+
10340 TypeDefinition td = baseType.Resolve ();
10341 if (td != null)
10342 baseType = td.BaseType;
10343diff --git a/gendarme/rules/Gendarme.Rules.Design/EnumsShouldUseInt32Rule.cs b/gendarme/rules/Gendarme.Rules.Design/EnumsShouldUseInt32Rule.cs
10344index 13460c2..3d2da47 100644
10345--- a/gendarme/rules/Gendarme.Rules.Design/EnumsShouldUseInt32Rule.cs
10346+++ b/gendarme/rules/Gendarme.Rules.Design/EnumsShouldUseInt32Rule.cs
10347@@ -25,6 +25,7 @@
10348 // THE SOFTWARE.
10349
10350 using System;
10351+using System.Globalization;
10352
10353 using Mono.Cecil;
10354
10355@@ -89,33 +90,36 @@ namespace Gendarme.Rules.Design {
10356
10357 // rule applies!
10358
10359- string value_type = null;
10360+ TypeReference ftype = null;
10361
10362 foreach (FieldDefinition field in type.Fields) {
10363 // we looking for the special value__
10364 if (!field.IsStatic) {
10365- value_type = field.FieldType.FullName;
10366+ ftype = field.FieldType;
10367 break;
10368 }
10369 }
10370
10371- Severity severity;
10372- switch (value_type) {
10373- case "System.Int32":
10374- return RuleResult.Success;
10375- // some are bad choice (when possible) but usable by all CLS compliant languages
10376- case "System.Byte":
10377- case "System.Int16":
10378- case "System.Int64":
10379+ Severity severity = Severity.Critical;
10380+ if ((ftype != null) && (ftype.Namespace == "System")) {
10381+ switch (ftype.Name) {
10382+ case "Int32":
10383+ return RuleResult.Success;
10384+ // some are bad choice (when possible) but usable by all CLS compliant languages
10385+ case "Byte":
10386+ case "Int16":
10387+ case "Int64":
10388 severity = Severity.High;
10389- break;
10390- // while others are not usable in non-CLS compliant languages
10391- default: // System.SByte, System.UInt16, System.UInt32, System.UInt64
10392- severity = Severity.Critical;
10393- break;
10394+ break;
10395+ // while others are not usable in non-CLS compliant languages
10396+ default: // System.SByte, System.UInt16, System.UInt32, System.UInt64
10397+ severity = Severity.Critical;
10398+ break;
10399+ }
10400 }
10401
10402- string text = String.Format ("Enums should use System.Int32 instead of '{0}'.", value_type);
10403+ string text = String.Format (CultureInfo.InvariantCulture,
10404+ "Enums should use System.Int32 instead of '{0}'.", ftype.GetFullName ());
10405 Runner.Report (type, severity, Confidence.Total, text);
10406 return RuleResult.Failure;
10407 }
10408diff --git a/gendarme/rules/Gendarme.Rules.Design/Gendarme.Rules.Design.csproj b/gendarme/rules/Gendarme.Rules.Design/Gendarme.Rules.Design.csproj
10409index c9f8ed4..9f6ad7c 100755
10410--- a/gendarme/rules/Gendarme.Rules.Design/Gendarme.Rules.Design.csproj
10411+++ b/gendarme/rules/Gendarme.Rules.Design/Gendarme.Rules.Design.csproj
10412@@ -1,5 +1,5 @@
10413 <?xml version="1.0" encoding="utf-8"?>\r
10414-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
10415+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
10416 <PropertyGroup>\r
10417 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
10418 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
10419@@ -10,8 +10,28 @@
10420 <AppDesignerFolder>Properties</AppDesignerFolder>\r
10421 <RootNamespace>Gendarme.Rules.Design</RootNamespace>\r
10422 <AssemblyName>Gendarme.Rules.Design</AssemblyName>\r
10423- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
10424+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
10425 <FileAlignment>512</FileAlignment>\r
10426+ <FileUpgradeFlags>\r
10427+ </FileUpgradeFlags>\r
10428+ <OldToolsVersion>3.5</OldToolsVersion>\r
10429+ <UpgradeBackupLocation />\r
10430+ <PublishUrl>publish\</PublishUrl>\r
10431+ <Install>true</Install>\r
10432+ <InstallFrom>Disk</InstallFrom>\r
10433+ <UpdateEnabled>false</UpdateEnabled>\r
10434+ <UpdateMode>Foreground</UpdateMode>\r
10435+ <UpdateInterval>7</UpdateInterval>\r
10436+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
10437+ <UpdatePeriodically>false</UpdatePeriodically>\r
10438+ <UpdateRequired>false</UpdateRequired>\r
10439+ <MapFileExtensions>true</MapFileExtensions>\r
10440+ <ApplicationRevision>0</ApplicationRevision>\r
10441+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
10442+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
10443+ <UseApplicationTrust>false</UseApplicationTrust>\r
10444+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
10445+ <TargetFrameworkProfile />\r
10446 </PropertyGroup>\r
10447 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
10448 <DebugSymbols>true</DebugSymbols>\r
10449@@ -24,6 +44,7 @@
10450 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Design.xml</DocumentationFile>\r
10451 <NoWarn>1591</NoWarn>\r
10452 <WarningsAsErrors>1570</WarningsAsErrors>\r
10453+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
10454 </PropertyGroup>\r
10455 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
10456 <DebugType>pdbonly</DebugType>\r
10457@@ -35,6 +56,7 @@
10458 <NoWarn>1591</NoWarn>\r
10459 <WarningsAsErrors>1570</WarningsAsErrors>\r
10460 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Design.xml</DocumentationFile>\r
10461+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
10462 </PropertyGroup>\r
10463 <ItemGroup>\r
10464 <Reference Include="System" />\r
10465@@ -90,8 +112,6 @@
10466 <Compile Include="ProvideTryParseAlternativeRule.cs" />\r
10467 <Compile Include="StronglyTypedRule.cs" />\r
10468 <Compile Include="TypesShouldBeInsideNamespacesRule.cs" />\r
10469- <Compile Include="TypesWithDisposableFieldsShouldBeDisposableRule.cs" />\r
10470- <Compile Include="TypesWithNativeFieldsShouldBeDisposableRule.cs" />\r
10471 <Compile Include="UseCorrectDisposeSignaturesRule.cs" />\r
10472 <Compile Include="UseFlagsAttributeRule.cs" />\r
10473 <Compile Include="UsingCloneWithoutImplementingICloneableRule.cs" />\r
10474@@ -107,6 +127,23 @@
10475 <Name>Gendarme.Framework</Name>\r
10476 </ProjectReference>\r
10477 </ItemGroup>\r
10478+ <ItemGroup>\r
10479+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
10480+ <Visible>False</Visible>\r
10481+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
10482+ <Install>false</Install>\r
10483+ </BootstrapperPackage>\r
10484+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
10485+ <Visible>False</Visible>\r
10486+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
10487+ <Install>true</Install>\r
10488+ </BootstrapperPackage>\r
10489+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
10490+ <Visible>False</Visible>\r
10491+ <ProductName>Windows Installer 3.1</ProductName>\r
10492+ <Install>true</Install>\r
10493+ </BootstrapperPackage>\r
10494+ </ItemGroup>\r
10495 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
10496 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
10497 Other similar extension points exist, see Microsoft.Common.targets.
10498diff --git a/gendarme/rules/Gendarme.Rules.Design/ImplementEqualsAndGetHashCodeInPairRule.cs b/gendarme/rules/Gendarme.Rules.Design/ImplementEqualsAndGetHashCodeInPairRule.cs
10499index 14e555f..c1e01c5 100644
10500--- a/gendarme/rules/Gendarme.Rules.Design/ImplementEqualsAndGetHashCodeInPairRule.cs
10501+++ b/gendarme/rules/Gendarme.Rules.Design/ImplementEqualsAndGetHashCodeInPairRule.cs
10502@@ -27,6 +27,7 @@
10503 // THE SOFTWARE.
10504
10505 using System;
10506+using System.Globalization;
10507
10508 using Mono.Cecil;
10509
10510@@ -99,13 +100,13 @@ namespace Gendarme.Rules.Design {
10511
10512 // if we have Equals but no GetHashCode method
10513 if (equals && !getHashCode) {
10514- string text = String.Format (Message, MethodSignatures.Equals, MethodSignatures.GetHashCode);
10515+ string text = String.Format (CultureInfo.InvariantCulture, Message, MethodSignatures.Equals, MethodSignatures.GetHashCode);
10516 Runner.Report (type, Severity.Critical, Confidence.High, text);
10517 }
10518
10519 // if we have GetHashCode but no Equals method
10520 if (!equals && getHashCode) {
10521- string text = String.Format (Message, MethodSignatures.GetHashCode, MethodSignatures.Equals);
10522+ string text = String.Format (CultureInfo.InvariantCulture, Message, MethodSignatures.GetHashCode, MethodSignatures.Equals);
10523 Runner.Report (type, Severity.Medium, Confidence.High, text);
10524 }
10525
10526diff --git a/gendarme/rules/Gendarme.Rules.Design/ImplementIComparableCorreclyRule.cs b/gendarme/rules/Gendarme.Rules.Design/ImplementIComparableCorreclyRule.cs
10527index a214f80..11c45aa 100644
10528--- a/gendarme/rules/Gendarme.Rules.Design/ImplementIComparableCorreclyRule.cs
10529+++ b/gendarme/rules/Gendarme.Rules.Design/ImplementIComparableCorreclyRule.cs
10530@@ -110,8 +110,10 @@ namespace Gendarme.Rules.Design {
10531 // Note: we do not use Implements rock because we do not want a recursive answer
10532 bool icomparable = false;
10533 foreach (TypeReference iface in type.Interfaces) {
10534+ if (iface.Namespace != "System")
10535+ continue;
10536 // catch both System.IComparable and System.IComparable`1<X>
10537- if (iface.FullName.StartsWith ("System.IComparable", StringComparison.Ordinal)) {
10538+ if (iface.Name.StartsWith ("IComparable", StringComparison.Ordinal)) {
10539 icomparable = true;
10540 break;
10541 }
10542diff --git a/gendarme/rules/Gendarme.Rules.Design/ListsAreStronglyTypedRule.cs b/gendarme/rules/Gendarme.Rules.Design/ListsAreStronglyTypedRule.cs
10543index f669c6a..9595df1 100644
10544--- a/gendarme/rules/Gendarme.Rules.Design/ListsAreStronglyTypedRule.cs
10545+++ b/gendarme/rules/Gendarme.Rules.Design/ListsAreStronglyTypedRule.cs
10546@@ -74,8 +74,9 @@ namespace Gendarme.Rules.Design {
10547 [Problem ("Types that implement IList should have strongly typed versions of IList.Item, IList.Add, IList.Contains, IList.IndexOf, IList.Insert and IList.Remove")]
10548 [Solution ("Explicitly implement IList members and provide strongly typed alternatives to them.")]
10549 [FxCopCompatibility ("Microsoft.Design", "CA1039:ListsAreStronglyTyped")]
10550- public class ListsAreStronglyTypedRule : StronglyTypedRule, ITypeRule
10551- {
10552+ public class ListsAreStronglyTypedRule : StronglyTypedRule, ITypeRule {
10553+
10554+ private static string [] Item = new string [] { "Item" };
10555
10556 private static string[] SystemObject = new string[] {"System.Object"};
10557 private static MethodSignature Add = new MethodSignature ("Add", "System.Int32", SystemObject);
10558@@ -83,25 +84,31 @@ namespace Gendarme.Rules.Design {
10559 private static MethodSignature IndexOf = new MethodSignature ("IndexOf", "System.Int32", SystemObject);
10560 private static MethodSignature Insert = new MethodSignature ("Insert", "System.Void", new string [] { "System.Int32", "System.Object" });
10561 private static MethodSignature Remove = new MethodSignature ("Remove", "System.Void", SystemObject);
10562-
10563+
10564+ private static MethodSignature [] Signatures = {
10565+ Add,
10566+ Contains,
10567+ IndexOf,
10568+ Insert,
10569+ Remove,
10570+ };
10571+
10572 protected override MethodSignature [] GetMethods ()
10573 {
10574- return new MethodSignature[] {
10575- Add,
10576- Contains,
10577- IndexOf,
10578- Insert,
10579- Remove,
10580- };
10581+ return Signatures;
10582 }
10583
10584 protected override string [] GetProperties ()
10585 {
10586- return new string [] { "Item" };
10587+ return Item;
10588 }
10589
10590 protected override string InterfaceName {
10591- get { return "System.Collections.IList"; }
10592+ get { return "IList"; }
10593+ }
10594+
10595+ protected override string InterfaceNamespace {
10596+ get { return "System.Collections"; }
10597 }
10598 }
10599 }
10600diff --git a/gendarme/rules/Gendarme.Rules.Design/Makefile.am b/gendarme/rules/Gendarme.Rules.Design/Makefile.am
10601index d6c861d..e9545b3 100644
10602--- a/gendarme/rules/Gendarme.Rules.Design/Makefile.am
10603+++ b/gendarme/rules/Gendarme.Rules.Design/Makefile.am
10604@@ -17,6 +17,7 @@ rules_sources = \
10605 DeclareEventHandlersCorrectlyRule.cs \
10606 DefineAZeroValueRule.cs \
10607 DisposableTypesShouldHaveFinalizerRule.cs \
10608+ DoNotDeclareSettersOnCollectionPropertiesRule.cs \
10609 DoNotDeclareVirtualMethodsInSealedTypeRule.cs \
10610 DontDeclareProtectedFieldsInSealedClassRule.cs \
10611 EnsureSymmetryForOverloadedOperatorsRule.cs \
10612@@ -46,8 +47,6 @@ rules_sources = \
10613 StronglyTypedRule.cs \
10614 StronglyTypeICollectionMembersRule.cs \
10615 TypesShouldBeInsideNamespacesRule.cs \
10616- TypesWithDisposableFieldsShouldBeDisposableRule.cs \
10617- TypesWithNativeFieldsShouldBeDisposableRule.cs \
10618 UseFlagsAttributeRule.cs \
10619 UseCorrectDisposeSignaturesRule.cs \
10620 UsingCloneWithoutImplementingICloneableRule.cs
10621@@ -70,6 +69,7 @@ tests_sources = \
10622 ConsiderUsingStaticTypeTest.cs \
10623 DeclareEventHandlersCorrectlyTest.cs \
10624 DisposableTypesShouldHaveFinalizerTest.cs \
10625+ DoNotDeclareSettersOnCollectionPropertiesTest.cs \
10626 DoNotDeclareVirtualMethodsInSealedTypeTest.cs \
10627 DontDeclareProtectedFieldsInSealedClassTest.cs \
10628 EnsureSymmetryForOverloadedOperatorsTest.cs \
10629@@ -98,8 +98,6 @@ tests_sources = \
10630 ProvideAlternativeNamesForOperatorOverloadsTest.cs \
10631 StronglyTypeICollectionMembersTest.cs \
10632 TypesShouldBeInsideNamespacesTest.cs \
10633- TypesWithDisposableFieldsShouldBeDisposableTest.cs \
10634- TypesWithNativeFieldsShouldBeDisposableTest.cs \
10635 UseFlagsAttributeTest.cs \
10636 UseCorrectDisposeSignaturesTest.cs \
10637 UsingCloneWithoutImplementingICloneableTest.cs
10638diff --git a/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithAttributeRule.cs b/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithAttributeRule.cs
10639index 031667a..f9dc4af 100644
10640--- a/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithAttributeRule.cs
10641+++ b/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithAttributeRule.cs
10642@@ -38,6 +38,7 @@ namespace Gendarme.Rules.Design {
10643
10644 abstract public class MarkAssemblyWithAttributeRule : Rule, IAssemblyRule {
10645
10646+ abstract protected string AttributeNamespace { get; }
10647 abstract protected string AttributeName { get; }
10648
10649 abstract protected Severity Severity { get; }
10650@@ -47,7 +48,7 @@ namespace Gendarme.Rules.Design {
10651 if (!assembly.HasCustomAttributes)
10652 return RuleResult.DoesNotApply;
10653
10654- if (assembly.HasAttribute (AttributeName))
10655+ if (assembly.HasAttribute (AttributeNamespace, AttributeName))
10656 return RuleResult.Success;
10657
10658 Runner.Report (assembly, Severity, Confidence.Total);
10659diff --git a/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithCLSCompliantRule.cs b/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithCLSCompliantRule.cs
10660index a2594c8..c686d4b 100644
10661--- a/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithCLSCompliantRule.cs
10662+++ b/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithCLSCompliantRule.cs
10663@@ -56,8 +56,12 @@ namespace Gendarme.Rules.Design {
10664 [FxCopCompatibility ("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant")]
10665 public class MarkAssemblyWithCLSCompliantRule : MarkAssemblyWithAttributeRule {
10666
10667+ protected override string AttributeNamespace {
10668+ get { return "System"; }
10669+ }
10670+
10671 protected override string AttributeName {
10672- get { return "System.CLSCompliantAttribute"; }
10673+ get { return "CLSCompliantAttribute"; }
10674 }
10675
10676 protected override Severity Severity {
10677diff --git a/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithComVisibleRule.cs b/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithComVisibleRule.cs
10678index ca2dcc4..59dfac8 100644
10679--- a/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithComVisibleRule.cs
10680+++ b/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithComVisibleRule.cs
10681@@ -55,8 +55,12 @@ namespace Gendarme.Rules.Design {
10682 [FxCopCompatibility ("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")]
10683 public class MarkAssemblyWithComVisibleRule : MarkAssemblyWithAttributeRule {
10684
10685+ protected override string AttributeNamespace {
10686+ get { return "System.Runtime.InteropServices"; }
10687+ }
10688+
10689 protected override string AttributeName {
10690- get { return "System.Runtime.InteropServices.ComVisibleAttribute"; }
10691+ get { return "ComVisibleAttribute"; }
10692 }
10693
10694 protected override Severity Severity {
10695diff --git a/gendarme/rules/Gendarme.Rules.Design/MissingAttributeUsageOnCustomAttributeRule.cs b/gendarme/rules/Gendarme.Rules.Design/MissingAttributeUsageOnCustomAttributeRule.cs
10696index addc0d5..e0e5135 100644
10697--- a/gendarme/rules/Gendarme.Rules.Design/MissingAttributeUsageOnCustomAttributeRule.cs
10698+++ b/gendarme/rules/Gendarme.Rules.Design/MissingAttributeUsageOnCustomAttributeRule.cs
10699@@ -66,15 +66,13 @@ namespace Gendarme.Rules.Design {
10700 [FxCopCompatibility ("Microsoft.Design", "CA1018:MarkAttributesWithAttributeUsage")]
10701 public class MissingAttributeUsageOnCustomAttributeRule : Rule, ITypeRule {
10702
10703- private const string AttributeUsageAttribute = "System.AttributeUsageAttribute";
10704-
10705 public RuleResult CheckType (TypeDefinition type)
10706 {
10707 // rule applies only to attributes
10708 if (!type.IsAttribute ())
10709 return RuleResult.DoesNotApply;
10710
10711- if (type.HasAttribute (AttributeUsageAttribute)) // it's ok
10712+ if (type.HasAttribute ("System", "AttributeUsageAttribute")) // it's ok
10713 return RuleResult.Success;
10714
10715 Runner.Report (type, Severity.High, Confidence.Total);
10716diff --git a/gendarme/rules/Gendarme.Rules.Design/PreferIntegerOrStringForIndexersRule.cs b/gendarme/rules/Gendarme.Rules.Design/PreferIntegerOrStringForIndexersRule.cs
10717index ff8f07b..8da1533 100644
10718--- a/gendarme/rules/Gendarme.Rules.Design/PreferIntegerOrStringForIndexersRule.cs
10719+++ b/gendarme/rules/Gendarme.Rules.Design/PreferIntegerOrStringForIndexersRule.cs
10720@@ -80,16 +80,22 @@ namespace Gendarme.Rules.Design {
10721 return RuleResult.Success;
10722
10723 foreach (ParameterDefinition parameter in method.Parameters) {
10724- switch (parameter.ParameterType.FullName) {
10725- case "System.Int32":
10726- case "System.Int64":
10727- case "System.String":
10728- case "System.Object": // tolerable in some circumstances
10729- break;
10730- default:
10731- Runner.Report (parameter, Severity.Medium, Confidence.Total);
10732- break;
10733+ TypeReference ptype = parameter.ParameterType;
10734+ bool ok = (ptype.Namespace == "System");
10735+ if (ok) {
10736+ switch (ptype.Name) {
10737+ case "Int32":
10738+ case "Int64":
10739+ case "String":
10740+ case "Object": // tolerable in some circumstances
10741+ break;
10742+ default:
10743+ ok = false;
10744+ break;
10745+ }
10746 }
10747+ if (!ok)
10748+ Runner.Report (parameter, Severity.Medium, Confidence.Total);
10749 }
10750 return Runner.CurrentRuleResult;
10751 }
10752diff --git a/gendarme/rules/Gendarme.Rules.Design/PreferUriOverStringRule.cs b/gendarme/rules/Gendarme.Rules.Design/PreferUriOverStringRule.cs
10753index cc15916..8143bda 100644
10754--- a/gendarme/rules/Gendarme.Rules.Design/PreferUriOverStringRule.cs
10755+++ b/gendarme/rules/Gendarme.Rules.Design/PreferUriOverStringRule.cs
10756@@ -34,6 +34,7 @@ using Gendarme.Framework.Rocks;
10757 using System;
10758 using System.Linq;
10759 using System.Collections.Generic;
10760+using System.Globalization;
10761
10762 namespace Gendarme.Rules.Design {
10763
10764@@ -100,7 +101,7 @@ namespace Gendarme.Rules.Design {
10765 // We assume the name is pascal- or camel- cased: to prevent false-positives (such as the urn in return),
10766 // the position is only returned if the character is the first in the string, or is an uppercase letter.
10767 while ((index = memberName.IndexOf (token, index, StringComparison.OrdinalIgnoreCase)) != -1) {
10768- if (index == 0 || char.IsUpper (memberName [index]))
10769+ if (index == 0 || Char.IsUpper (memberName [index]))
10770 break;
10771 index += token.Length;
10772 }
10773@@ -110,10 +111,10 @@ namespace Gendarme.Rules.Design {
10774 private static bool IsUri (string memberName)
10775 {
10776 int index = 0;
10777- while ((index = FindTokenStart (memberName, "ur", index)) != -1) {
10778- if (memberName.Length < index + 2)
10779+ while ((index = FindTokenStart(memberName, "ur", index)) != -1){
10780+ if (memberName.Length <= index + 2)
10781 break;
10782- if (url_enders.Contains (char.ToLower (memberName [index + 2])))
10783+ if (url_enders.Contains(Char.ToLower(memberName[index + 2], CultureInfo.InvariantCulture)))
10784 return true;
10785 index += 2;
10786 }
10787@@ -159,7 +160,7 @@ namespace Gendarme.Rules.Design {
10788 {
10789 // attributes are a special case where Uri cannot be used and has it's own
10790 // rule to cover this: Gendarme.Rules.Correctness.AttributeStringLiteralShouldParseCorrectlyRule
10791- if (method.IsConstructor && method.DeclaringType.Inherits ("System.Attribute"))
10792+ if (method.IsConstructor && method.DeclaringType.Inherits ("System", "Attribute"))
10793 return;
10794
10795 var methodParams = method.Parameters;
10796diff --git a/gendarme/rules/Gendarme.Rules.Design/PreferXmlAbstractionsRule.cs b/gendarme/rules/Gendarme.Rules.Design/PreferXmlAbstractionsRule.cs
10797index 32bc46f..6ce3fdc 100644
10798--- a/gendarme/rules/Gendarme.Rules.Design/PreferXmlAbstractionsRule.cs
10799+++ b/gendarme/rules/Gendarme.Rules.Design/PreferXmlAbstractionsRule.cs
10800@@ -94,10 +94,6 @@ namespace Gendarme.Rules.Design {
10801 [FxCopCompatibility ("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes")]
10802 public class PreferXmlAbstractionsRule : Rule, IMethodRule {
10803
10804- const string XmlDocumentClass = "System.Xml.XmlDocument";
10805- const string XPathDocumentClass = "System.Xml.XPath.XPathDocument";
10806- const string XmlNodeClass = "System.Xml.XmlNode";
10807-
10808 public override void Initialize (IRunner runner)
10809 {
10810 base.Initialize (runner);
10811@@ -119,7 +115,7 @@ namespace Gendarme.Rules.Design {
10812 return RuleResult.DoesNotApply;
10813
10814 MethodReturnType mrt = method.MethodReturnType;
10815- if (IsSpecificXmlType (mrt.ReturnType.FullName))
10816+ if (IsSpecificXmlType (mrt.ReturnType))
10817 Runner.Report (mrt, GetSeverity (method), Confidence.High);
10818
10819 if (method.HasParameters) {
10820@@ -127,7 +123,7 @@ namespace Gendarme.Rules.Design {
10821 if (parameter.IsOut)
10822 continue; //out params already have their rule
10823
10824- if (IsSpecificXmlType (parameter.ParameterType.FullName))
10825+ if (IsSpecificXmlType (parameter.ParameterType))
10826 Runner.Report (parameter, GetSeverity (method), Confidence.High);
10827 }
10828 }
10829@@ -135,9 +131,13 @@ namespace Gendarme.Rules.Design {
10830 return Runner.CurrentRuleResult;
10831 }
10832
10833- static bool IsSpecificXmlType (string name)
10834+ static bool IsSpecificXmlType (TypeReference type)
10835 {
10836- return name == XmlDocumentClass || name == XPathDocumentClass || name == XmlNodeClass;
10837+ if (type.Namespace == "System.Xml") {
10838+ string name = type.Name;
10839+ return ((name == "XmlDocument") || (name == "XmlNode"));
10840+ }
10841+ return type.IsNamed ("System.Xml.XPath", "XPathDocument");
10842 }
10843
10844 static Severity GetSeverity (MethodDefinition method)
10845diff --git a/gendarme/rules/Gendarme.Rules.Design/ProvideAlternativeNamesForOperatorOverloadsRule.cs b/gendarme/rules/Gendarme.Rules.Design/ProvideAlternativeNamesForOperatorOverloadsRule.cs
10846index 1e1347e..e2197c5 100644
10847--- a/gendarme/rules/Gendarme.Rules.Design/ProvideAlternativeNamesForOperatorOverloadsRule.cs
10848+++ b/gendarme/rules/Gendarme.Rules.Design/ProvideAlternativeNamesForOperatorOverloadsRule.cs
10849@@ -28,6 +28,7 @@
10850
10851 using System;
10852 using System.Collections.Generic;
10853+using System.Globalization;
10854 using Mono.Cecil;
10855
10856 using Gendarme.Framework;
10857@@ -171,7 +172,8 @@ namespace Gendarme.Rules.Design {
10858 }
10859
10860 if (!alternativeDefined) {
10861- string s = String.Format ("This type implements the '{0}' operator. Some languages do not support overloaded operators so an alternative '{1}' method should be provided.",
10862+ string s = String.Format (CultureInfo.InvariantCulture,
10863+ "This type implements the '{0}' operator. Some languages do not support overloaded operators so an alternative '{1}' method should be provided.",
10864 kv.Key.Name, kv.Value.Name);
10865 Runner.Report (op, Severity.Medium, Confidence.High, s);
10866 }
10867diff --git a/gendarme/rules/Gendarme.Rules.Design/README.md b/gendarme/rules/Gendarme.Rules.Design/README.md
10868new file mode 100644
10869index 0000000..22a4957
10870--- /dev/null
10871+++ b/gendarme/rules/Gendarme.Rules.Design/README.md
10872@@ -0,0 +1,9 @@
10873+# Gendarme.Rules.Design Rules
10874+
10875+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design(git)]] pages.
10876+
10877+
10878+## Feedback
10879+
10880+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
10881+
10882diff --git a/gendarme/rules/Gendarme.Rules.Design/StronglyTypeICollectionMembersRule.cs b/gendarme/rules/Gendarme.Rules.Design/StronglyTypeICollectionMembersRule.cs
10883index 637e9e8..75605a1 100644
10884--- a/gendarme/rules/Gendarme.Rules.Design/StronglyTypeICollectionMembersRule.cs
10885+++ b/gendarme/rules/Gendarme.Rules.Design/StronglyTypeICollectionMembersRule.cs
10886@@ -72,24 +72,30 @@ namespace Gendarme.Rules.Design {
10887 [Problem ("Types that implement ICollection interface should have strongly typed version of ICollection.CopyTo method")]
10888 [Solution ("Explicitly implement ICollection.CopyTo and add strongly typed alternative to it")]
10889 [FxCopCompatibility ("Microsoft.Design", "CA1035:ICollectionImplementationsHaveStronglyTypedMembers")]
10890- public class StronglyTypeICollectionMembersRule : StronglyTypedRule, ITypeRule
10891- {
10892+ public class StronglyTypeICollectionMembersRule : StronglyTypedRule, ITypeRule {
10893
10894- private static MethodSignature CopyTo = new MethodSignature("CopyTo", "System.Void",
10895- new string[] {"System.Array", "System.Int32"});
10896+ private static string [] Empty = new string [] { };
10897+
10898+ private static MethodSignature [] CopyTo = new MethodSignature [] {
10899+ new MethodSignature ("CopyTo", "System.Void", new string [] { "System.Array", "System.Int32" })
10900+ };
10901
10902 protected override MethodSignature [] GetMethods ()
10903 {
10904- return new MethodSignature [] { CopyTo };
10905+ return CopyTo;
10906 }
10907
10908 protected override string [] GetProperties ()
10909 {
10910- return new string [] { };
10911+ return Empty;
10912 }
10913
10914 protected override string InterfaceName {
10915- get { return "System.Collections.ICollection"; }
10916+ get { return "ICollection"; }
10917+ }
10918+
10919+ protected override string InterfaceNamespace {
10920+ get { return "System.Collections"; }
10921 }
10922 }
10923 }
10924diff --git a/gendarme/rules/Gendarme.Rules.Design/StronglyTypedRule.cs b/gendarme/rules/Gendarme.Rules.Design/StronglyTypedRule.cs
10925index f38fecc..b60feae 100644
10926--- a/gendarme/rules/Gendarme.Rules.Design/StronglyTypedRule.cs
10927+++ b/gendarme/rules/Gendarme.Rules.Design/StronglyTypedRule.cs
10928@@ -42,12 +42,7 @@ namespace Gendarme.Rules.Design {
10929 abstract protected MethodSignature [] GetMethods ();
10930 abstract protected string [] GetProperties ();
10931 abstract protected string InterfaceName { get; }
10932-
10933- HashSet<string> weakTypes = new HashSet<string> {
10934- "System.Object",
10935- "System.Array",
10936- "System.Object[]",
10937- };
10938+ abstract protected string InterfaceNamespace { get; }
10939
10940 MethodSignature [] signatures;
10941 string [] propertyNames;
10942@@ -55,7 +50,7 @@ namespace Gendarme.Rules.Design {
10943
10944 virtual public RuleResult CheckType (TypeDefinition type)
10945 {
10946- if (type.IsAbstract || type.IsGeneratedCode () || !type.Implements (InterfaceName))
10947+ if (type.IsAbstract || type.IsGeneratedCode () || !type.Implements (InterfaceNamespace, InterfaceName))
10948 return RuleResult.DoesNotApply;
10949
10950 signatures = GetMethods ();
10951@@ -106,13 +101,26 @@ namespace Gendarme.Rules.Design {
10952 ProcessProperties (baseType);
10953 }
10954
10955+ static bool IsWeak (TypeReference type)
10956+ {
10957+ if (type.Namespace != "System")
10958+ return false;
10959+ string name = type.Name;
10960+ return ((name == "Object") || (name == "Array") || (name == "Object[]"));
10961+ }
10962+
10963+ static bool IsWeak (string typeName)
10964+ {
10965+ return ((typeName == "System.Object") || (typeName == "System.Array") || (typeName == "System.Object[]"));
10966+ }
10967+
10968 private void ProcessProperties (TypeDefinition baseType)
10969 {
10970 foreach (PropertyDefinition property in baseType.Properties) {
10971 for (int i = 0; i < propertyNames.Length; i++) {
10972 if (propertyNames [i] == null || propertyNames [i] != property.Name)
10973 continue;
10974- if (!weakTypes.Contains (property.PropertyType.FullName)) {
10975+ if (!IsWeak (property.PropertyType)) {
10976 propertiesLeft--;
10977 propertyNames [i] = null;
10978 }
10979@@ -133,9 +141,9 @@ namespace Gendarme.Rules.Design {
10980
10981 bool foundStrong = true;
10982 for (int j = 0; j < methodParameters.Count; j++) {
10983- if (!weakTypes.Contains (signatures [i].Parameters [j]))
10984+ if (!IsWeak (signatures [i].Parameters [j]))
10985 continue;
10986- if (weakTypes.Contains (methodParameters [j].ParameterType.FullName))
10987+ if (IsWeak (methodParameters [j].ParameterType))
10988 foundStrong = false;
10989 }
10990
10991diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/AttributeArgumentsShouldHaveAccessorsTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/AttributeArgumentsShouldHaveAccessorsTest.cs
10992index 0640805..02c92a0 100644
10993--- a/gendarme/rules/Gendarme.Rules.Design/Test/AttributeArgumentsShouldHaveAccessorsTest.cs
10994+++ b/gendarme/rules/Gendarme.Rules.Design/Test/AttributeArgumentsShouldHaveAccessorsTest.cs
10995@@ -196,6 +196,35 @@ namespace Test.Rules.Design {
10996 }
10997 }
10998
10999+ internal abstract class FooAttribute : Attribute
11000+ {
11001+ protected FooAttribute (string foo)
11002+ {
11003+ this.Foo = foo;
11004+ }
11005+
11006+ public string Foo
11007+ {
11008+ get;
11009+ private set;
11010+ }
11011+ }
11012+
11013+ internal class FooBarAttribute : FooAttribute
11014+ {
11015+ protected FooBarAttribute (string foo, string bar) : base (foo)
11016+ {
11017+ this.Bar = bar;
11018+ }
11019+
11020+ public string Bar
11021+ {
11022+ get;
11023+ private set;
11024+ }
11025+ }
11026+
11027+
11028 [TestFixture]
11029 public class AttributeArgumentsShouldHaveAccessorsTest : TypeRuleTestFixture<AttributeArgumentsShouldHaveAccessorsRule> {
11030
11031@@ -252,5 +281,11 @@ namespace Test.Rules.Design {
11032 {
11033 AssertRuleFailure<TwoAccessorsMissingAttribute> (2);
11034 }
11035+
11036+ [Test]
11037+ public void TestInheritedPropertiesAttribute ()
11038+ {
11039+ AssertRuleSuccess<FooBarAttribute> ();
11040+ }
11041 }
11042 }
11043diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/ConsiderUsingStaticTypeTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/ConsiderUsingStaticTypeTest.cs
11044index 9e9c707..8e55722 100644
11045--- a/gendarme/rules/Gendarme.Rules.Design/Test/ConsiderUsingStaticTypeTest.cs
11046+++ b/gendarme/rules/Gendarme.Rules.Design/Test/ConsiderUsingStaticTypeTest.cs
11047@@ -4,7 +4,7 @@
11048 // Authors:
11049 // Sebastien Pouliot <sebastien@ximian.com>
11050 //
11051-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
11052+// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
11053 //
11054 // Permission is hereby granted, free of charge, to any person obtaining
11055 // a copy of this software and associated documentation files (the
11056@@ -84,9 +84,9 @@ namespace Test.Rules.Design {
11057 }
11058
11059 [Test]
11060- public void SkipOnEmptyClassTest ()
11061+ public void EmptyClassHasDefaultPublicInstanceCtor ()
11062 {
11063- AssertRuleDoesNotApply<EmptyClass> ();
11064+ AssertRuleFailure<EmptyClass> ();
11065 }
11066
11067 //You cannot do this class static
11068diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareSettersOnCollectionPropertiesTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareSettersOnCollectionPropertiesTest.cs
11069new file mode 100644
11070index 0000000..4e22ddd
11071--- /dev/null
11072+++ b/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareSettersOnCollectionPropertiesTest.cs
11073@@ -0,0 +1,137 @@
11074+//
11075+// Unit tests for DoNotDeclareSettersOnCollectionPropertiesRule
11076+//
11077+// Authors:
11078+// Sebastien Pouliot <sebastien@ximian.com>
11079+//
11080+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
11081+//
11082+// Permission is hereby granted, free of charge, to any person obtaining a copy
11083+// of this software and associated documentation files (the "Software"), to deal
11084+// in the Software without restriction, including without limitation the rights
11085+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11086+// copies of the Software, and to permit persons to whom the Software is
11087+// furnished to do so, subject to the following conditions:
11088+//
11089+// The above copyright notice and this permission notice shall be included in
11090+// all copies or substantial portions of the Software.
11091+//
11092+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11093+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
11094+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
11095+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
11096+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
11097+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
11098+// THE SOFTWARE.
11099+
11100+using System;
11101+using System.Collections;
11102+using System.Collections.Generic;
11103+using System.Security;
11104+
11105+using Gendarme.Rules.Design;
11106+
11107+using NUnit.Framework;
11108+using Test.Rules.Fixtures;
11109+using Test.Rules.Definitions;
11110+
11111+namespace Test.Rules.Design {
11112+
11113+ [TestFixture]
11114+ public class DoNotDeclareSettersOnCollectionPropertiesTest : TypeRuleTestFixture<DoNotDeclareSettersOnCollectionPropertiesRule> {
11115+
11116+ [Test]
11117+ public void DoesNotApply ()
11118+ {
11119+ AssertRuleDoesNotApply (SimpleTypes.Class);
11120+ AssertRuleDoesNotApply (SimpleTypes.Delegate);
11121+ AssertRuleDoesNotApply (SimpleTypes.Enum);
11122+ AssertRuleDoesNotApply (SimpleTypes.GeneratedType);
11123+ AssertRuleDoesNotApply (SimpleTypes.Interface);
11124+ AssertRuleDoesNotApply (SimpleTypes.Structure);
11125+ }
11126+
11127+ public interface IGoodInterface {
11128+ ICollection Collection { get; }
11129+ ICollection<string> GenericCollection { get; }
11130+ }
11131+
11132+ public class TypeImplementingGoodInterface : IGoodInterface {
11133+ public ICollection Collection { get; private set; }
11134+ public ICollection<string> GenericCollection { get; private set; }
11135+ }
11136+
11137+ public struct GoodStruct {
11138+ private ArrayList list;
11139+
11140+ public IDictionary Dictionary { get; private set; }
11141+ public ArrayList List {
11142+ get { return list; }
11143+ }
11144+ }
11145+
11146+ [Test]
11147+ public void Good ()
11148+ {
11149+ AssertRuleSuccess<IGoodInterface> ();
11150+ AssertRuleSuccess<TypeImplementingGoodInterface> ();
11151+ AssertRuleSuccess<GoodStruct> ();
11152+ }
11153+
11154+ // interface members are not "declared" as public - but they force a type to do so!
11155+ public interface IBadInterface {
11156+ ICollection Collection { get; set; }
11157+ ICollection<string> GenericCollection { get; set; }
11158+ }
11159+
11160+ public class TypeImplementingBadInterface : IBadInterface {
11161+ public ICollection Collection { get; set; }
11162+ public ICollection<string> GenericCollection { get; set; }
11163+ }
11164+
11165+ public struct BadStruct {
11166+ public IDictionary Dictionary { private get; set; }
11167+ public ArrayList List { get; set; }
11168+ }
11169+
11170+ [Test]
11171+ public void Bad ()
11172+ {
11173+ AssertRuleFailure<IBadInterface> (2);
11174+ AssertRuleFailure<TypeImplementingBadInterface> (2);
11175+ AssertRuleFailure<BadStruct> (2);
11176+ }
11177+
11178+ public class SecurityPermissions {
11179+ public PermissionSet Permissions { get; set; }
11180+ public NamedPermissionSet NamedPermissions { get; set; }
11181+ }
11182+
11183+ public class Indexers {
11184+ int [] array;
11185+
11186+ public int this [int index] {
11187+ get { return array [index]; }
11188+ set { array [index] = value; }
11189+ }
11190+
11191+ public int this [int x, int y] {
11192+ get { return array [x]; }
11193+ set { array [y] = value; }
11194+ }
11195+ }
11196+
11197+ public class Arrays {
11198+
11199+ public Array Array { get; set; }
11200+ }
11201+
11202+ [Test]
11203+ public void SpecialCases ()
11204+ {
11205+ AssertRuleSuccess<SecurityPermissions> ();
11206+ AssertRuleSuccess<Indexers> ();
11207+ AssertRuleFailure<Arrays> (1);
11208+ }
11209+ }
11210+}
11211diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareVirtualMethodsInSealedTypeTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareVirtualMethodsInSealedTypeTest.cs
11212index f495193..c5ae0ef 100644
11213--- a/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareVirtualMethodsInSealedTypeTest.cs
11214+++ b/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareVirtualMethodsInSealedTypeTest.cs
11215@@ -4,7 +4,7 @@
11216 // Authors:
11217 // Sebastien Pouliot <sebastien@ximian.com>
11218 //
11219-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
11220+// Copyright (C) 2008,2011 Novell, Inc (http://www.novell.com)
11221 //
11222 // Permission is hereby granted, free of charge, to any person obtaining a copy
11223 // of this software and associated documentation files (the "Software"), to deal
11224@@ -25,6 +25,7 @@
11225 // THE SOFTWARE.
11226
11227 using System;
11228+using System.Collections.Generic;
11229
11230 using Mono.Cecil;
11231 using Gendarme.Rules.Design;
11232@@ -103,7 +104,7 @@ namespace Test.Rules.Design {
11233 }
11234
11235 public abstract class AbstractClass {
11236- public abstract string GetIt ();
11237+ public abstract string GetZit ();
11238 }
11239
11240 public sealed class SealedClass : AbstractClass {
11241@@ -113,7 +114,7 @@ namespace Test.Rules.Design {
11242 return 42;
11243 }
11244
11245- public override string GetIt ()
11246+ public override string GetZit ()
11247 {
11248 return String.Empty;
11249 }
11250@@ -130,5 +131,34 @@ namespace Test.Rules.Design {
11251 AssertRuleDoesNotApply<AbstractClass> ();
11252 AssertRuleSuccess<SealedClass> ();
11253 }
11254+
11255+ // extracted from mono/mcs/class/corlib/System.Collections.Generic/EqualityComparer.cs
11256+ // they override 'T', not string, base methods
11257+ sealed class InternalStringComparer : EqualityComparer<string> {
11258+
11259+ public override int GetHashCode (string obj)
11260+ {
11261+ if (obj == null)
11262+ return 0;
11263+ return obj.GetHashCode ();
11264+ }
11265+
11266+ public override bool Equals (string x, string y)
11267+ {
11268+ if (x == null)
11269+ return y == null;
11270+
11271+ if ((object) x == (object) y)
11272+ return true;
11273+
11274+ return x.Equals (y);
11275+ }
11276+ }
11277+
11278+ [Test]
11279+ public void Generic ()
11280+ {
11281+ AssertRuleSuccess<InternalStringComparer> ();
11282+ }
11283 }
11284 }
11285diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/PreferUriOverStringTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/PreferUriOverStringTest.cs
11286index ed460fd..ff975fd 100644
11287--- a/gendarme/rules/Gendarme.Rules.Design/Test/PreferUriOverStringTest.cs
11288+++ b/gendarme/rules/Gendarme.Rules.Design/Test/PreferUriOverStringTest.cs
11289@@ -52,6 +52,11 @@ namespace Test.Rules.Design {
11290 get;
11291 set;
11292 }
11293+ public string CUR
11294+ {
11295+ get;
11296+ set;
11297+ }
11298
11299 public Uri GetUri ()
11300 {
11301@@ -117,6 +122,7 @@ namespace Test.Rules.Design {
11302 {
11303 AssertRuleSuccess (SimpleMethods.EmptyMethod);
11304 AssertRuleSuccess<GoodUris> ("GetUri");
11305+ AssertRuleSuccess<GoodUris>("get_CUR");
11306 AssertRuleSuccess<GoodUris> ("GetNewLink");
11307 AssertRuleSuccess<GoodUris> ("OverloadedMethod", new Type [] { typeof (string) });
11308 }
11309diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/Tests.Rules.Design.csproj b/gendarme/rules/Gendarme.Rules.Design/Test/Tests.Rules.Design.csproj
11310index cf19ae8..c59cc09 100755
11311--- a/gendarme/rules/Gendarme.Rules.Design/Test/Tests.Rules.Design.csproj
11312+++ b/gendarme/rules/Gendarme.Rules.Design/Test/Tests.Rules.Design.csproj
11313@@ -1,5 +1,5 @@
11314 <?xml version="1.0" encoding="utf-8"?>\r
11315-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
11316+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
11317 <PropertyGroup>\r
11318 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
11319 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
11320@@ -10,8 +10,28 @@
11321 <AppDesignerFolder>Properties</AppDesignerFolder>\r
11322 <RootNamespace>Test</RootNamespace>\r
11323 <AssemblyName>Tests.Rules.Design</AssemblyName>\r
11324- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
11325+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
11326 <FileAlignment>512</FileAlignment>\r
11327+ <FileUpgradeFlags>\r
11328+ </FileUpgradeFlags>\r
11329+ <OldToolsVersion>3.5</OldToolsVersion>\r
11330+ <UpgradeBackupLocation />\r
11331+ <PublishUrl>publish\</PublishUrl>\r
11332+ <Install>true</Install>\r
11333+ <InstallFrom>Disk</InstallFrom>\r
11334+ <UpdateEnabled>false</UpdateEnabled>\r
11335+ <UpdateMode>Foreground</UpdateMode>\r
11336+ <UpdateInterval>7</UpdateInterval>\r
11337+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
11338+ <UpdatePeriodically>false</UpdatePeriodically>\r
11339+ <UpdateRequired>false</UpdateRequired>\r
11340+ <MapFileExtensions>true</MapFileExtensions>\r
11341+ <ApplicationRevision>0</ApplicationRevision>\r
11342+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
11343+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
11344+ <UseApplicationTrust>false</UseApplicationTrust>\r
11345+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
11346+ <TargetFrameworkProfile />\r
11347 </PropertyGroup>\r
11348 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
11349 <DebugSymbols>true</DebugSymbols>\r
11350@@ -21,6 +41,8 @@
11351 <DefineConstants>TRACE;DEBUG;CODE_ANALYSIS</DefineConstants>\r
11352 <ErrorReport>prompt</ErrorReport>\r
11353 <WarningLevel>4</WarningLevel>\r
11354+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
11355+ <AllowUnsafeBlocks>false</AllowUnsafeBlocks>\r
11356 </PropertyGroup>\r
11357 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
11358 <DebugType>pdbonly</DebugType>\r
11359@@ -29,6 +51,7 @@
11360 <DefineConstants>TRACE</DefineConstants>\r
11361 <ErrorReport>prompt</ErrorReport>\r
11362 <WarningLevel>4</WarningLevel>\r
11363+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
11364 </PropertyGroup>\r
11365 <ItemGroup>\r
11366 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
11367@@ -85,8 +108,6 @@
11368 <Compile Include="ProvideAlternativeNamesForOperatorOverloadsTest.cs" />\r
11369 <Compile Include="ProvideTryParseAlternativeTest.cs" />\r
11370 <Compile Include="TypesShouldBeInsideNamespacesTest.cs" />\r
11371- <Compile Include="TypesWithDisposableFieldsShouldBeDisposableTest.cs" />\r
11372- <Compile Include="TypesWithNativeFieldsShouldBeDisposableTest.cs" />\r
11373 <Compile Include="UseCorrectDisposeSignaturesTest.cs" />\r
11374 <Compile Include="UseFlagsAttributeTest.cs" />\r
11375 <Compile Include="UsingCloneWithoutImplementingICloneableTest.cs" />\r
11376@@ -112,6 +133,23 @@
11377 <ItemGroup>\r
11378 <Folder Include="Properties\" />\r
11379 </ItemGroup>\r
11380+ <ItemGroup>\r
11381+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
11382+ <Visible>False</Visible>\r
11383+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
11384+ <Install>false</Install>\r
11385+ </BootstrapperPackage>\r
11386+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
11387+ <Visible>False</Visible>\r
11388+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
11389+ <Install>true</Install>\r
11390+ </BootstrapperPackage>\r
11391+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
11392+ <Visible>False</Visible>\r
11393+ <ProductName>Windows Installer 3.1</ProductName>\r
11394+ <Install>true</Install>\r
11395+ </BootstrapperPackage>\r
11396+ </ItemGroup>\r
11397 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
11398 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
11399 Other similar extension points exist, see Microsoft.Common.targets.
11400diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs
11401deleted file mode 100644
11402index 811ba7e..0000000
11403--- a/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs
11404+++ /dev/null
11405@@ -1,170 +0,0 @@
11406-//
11407-// Unit tests for TypesWithDisposableFieldsShouldBeDisposableRule
11408-//
11409-// Authors:
11410-// Andreas Noever <andreas.noever@gmail.com>
11411-// Sebastien Pouliot <sebastien@ximian.com>
11412-//
11413-// (C) 2008 Andreas Noever
11414-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
11415-//
11416-// Permission is hereby granted, free of charge, to any person obtaining
11417-// a copy of this software and associated documentation files (the
11418-// "Software"), to deal in the Software without restriction, including
11419-// without limitation the rights to use, copy, modify, merge, publish,
11420-// distribute, sublicense, and/or sell copies of the Software, and to
11421-// permit persons to whom the Software is furnished to do so, subject to
11422-// the following conditions:
11423-//
11424-// The above copyright notice and this permission notice shall be
11425-// included in all copies or substantial portions of the Software.
11426-//
11427-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11428-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11429-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
11430-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
11431-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
11432-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
11433-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11434-//
11435-
11436-using System;
11437-
11438-using Gendarme.Rules.Design;
11439-
11440-using NUnit.Framework;
11441-using Test.Rules.Definitions;
11442-using Test.Rules.Fixtures;
11443-
11444-namespace Test.Rules.Design {
11445-
11446- class Disposable : IDisposable {
11447- public void Dispose ()
11448- {
11449- throw new NotImplementedException ();
11450- }
11451- }
11452-
11453- class NoDisposeableFields {
11454- int A;
11455- object b;
11456- }
11457-
11458- class DisposeableFieldsImplementsIDisposeable : IDisposable {
11459- object A;
11460- Disposable B;
11461-
11462- public void Dispose ()
11463- {
11464- throw new NotImplementedException ();
11465- }
11466- }
11467-
11468- class DisposeableFieldsExplicit : IDisposable {
11469- object A;
11470- Disposable B;
11471-
11472- void IDisposable.Dispose ()
11473- {
11474- throw new NotImplementedException ();
11475- }
11476- }
11477-
11478- abstract class DisposeableFieldsImplementsIDisposeableAbstract : IDisposable {
11479- object A;
11480- Disposable B;
11481- public void Dispose (object asd) { B.Dispose (); }
11482- public abstract void Dispose ();
11483- }
11484-
11485- class DisposeableFields : ICloneable {
11486- object A;
11487- Disposable B;
11488-
11489- public object Clone ()
11490- {
11491- throw new NotImplementedException ();
11492- }
11493- }
11494-
11495- class DisposeableFieldsArray : ICloneable {
11496- object A;
11497- Disposable [] B;
11498-
11499- public object Clone ()
11500- {
11501- throw new NotImplementedException ();
11502- }
11503- }
11504-
11505- struct StructWithDisposeableFields {
11506- Disposable a;
11507- object b;
11508- }
11509-
11510- class DisposeableStaticFieldsArray {
11511- object A;
11512- static Disposable [] B;
11513- }
11514-
11515- [TestFixture]
11516- public class TypesWithDisposableFieldsShouldBeDisposableTest : TypeRuleTestFixture<TypesWithDisposableFieldsShouldBeDisposableRule> {
11517-
11518- [Test]
11519- public void DoesNotApply ()
11520- {
11521- AssertRuleDoesNotApply (SimpleTypes.Delegate);
11522- AssertRuleDoesNotApply (SimpleTypes.Enum);
11523- AssertRuleDoesNotApply (SimpleTypes.Interface);
11524- AssertRuleDoesNotApply (SimpleTypes.Structure);
11525- }
11526-
11527- [Test]
11528- public void TestNoDisposeableFields ()
11529- {
11530- AssertRuleSuccess<NoDisposeableFields> ();
11531- }
11532-
11533- [Test]
11534- public void TestDisposeableFieldsImplementsIDisposeable ()
11535- {
11536- AssertRuleSuccess<DisposeableFieldsImplementsIDisposeable> ();
11537- }
11538-
11539- [Test]
11540- public void TestDisposeableFieldsExplicit ()
11541- {
11542- AssertRuleSuccess<DisposeableFieldsExplicit> ();
11543- }
11544-
11545- [Test]
11546- public void TestDisposeableFieldsImplementsIDisposeableAbstract ()
11547- {
11548- AssertRuleFailure<DisposeableFieldsImplementsIDisposeableAbstract> (2);
11549- }
11550-
11551- [Test]
11552- public void TestDisposeableFields ()
11553- {
11554- AssertRuleFailure<DisposeableFields> (1);
11555- }
11556-
11557- [Test]
11558- public void TestDisposeableFieldsArray ()
11559- {
11560- AssertRuleFailure<DisposeableFieldsArray> (1);
11561- }
11562-
11563- [Test]
11564- public void TestStructWithDisposeableFields ()
11565- {
11566- AssertRuleDoesNotApply<StructWithDisposeableFields> ();
11567- }
11568-
11569- [Test]
11570- public void TestDisposeableStaticFieldsArray ()
11571- {
11572- AssertRuleSuccess<DisposeableStaticFieldsArray> ();
11573- }
11574- }
11575-}
11576diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs
11577deleted file mode 100644
11578index 75216df..0000000
11579--- a/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs
11580+++ /dev/null
11581@@ -1,217 +0,0 @@
11582-//
11583-// Unit tests for TypesWithNativeFieldsShouldBeDisposableRule
11584-//
11585-// Authors:
11586-// Andreas Noever <andreas.noever@gmail.com>
11587-// Sebastien Pouliot <sebastien@ximian.com>
11588-//
11589-// (C) 2008 Andreas Noever
11590-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
11591-//
11592-// Permission is hereby granted, free of charge, to any person obtaining
11593-// a copy of this software and associated documentation files (the
11594-// "Software"), to deal in the Software without restriction, including
11595-// without limitation the rights to use, copy, modify, merge, publish,
11596-// distribute, sublicense, and/or sell copies of the Software, and to
11597-// permit persons to whom the Software is furnished to do so, subject to
11598-// the following conditions:
11599-//
11600-// The above copyright notice and this permission notice shall be
11601-// included in all copies or substantial portions of the Software.
11602-//
11603-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11604-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11605-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
11606-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
11607-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
11608-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
11609-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11610-//
11611-
11612-using System;
11613-using System.Runtime.InteropServices;
11614-
11615-using Gendarme.Rules.Design;
11616-
11617-using NUnit.Framework;
11618-using Test.Rules.Definitions;
11619-using Test.Rules.Fixtures;
11620-
11621-namespace Test.Rules.Design {
11622-
11623- class NoNativeFields {
11624- int A;
11625- object b;
11626- }
11627-
11628- class NativeFieldsImplementsIDisposeable : IDisposable {
11629- object A;
11630- IntPtr B;
11631-
11632- public void Dispose ()
11633- {
11634- throw new NotImplementedException ();
11635- }
11636- }
11637-
11638- class NativeFieldsExplicit : IDisposable {
11639- object A;
11640- IntPtr B;
11641-
11642- void IDisposable.Dispose ()
11643- {
11644- throw new NotImplementedException ();
11645- }
11646- }
11647-
11648-
11649- class NativeFieldsIntPtr : ICloneable {
11650- object A;
11651- IntPtr B;
11652-
11653- public object Clone ()
11654- {
11655- throw new NotImplementedException ();
11656- }
11657- }
11658-
11659- class NativeFieldsUIntPtr : ICloneable {
11660- object A;
11661- UIntPtr B;
11662-
11663- public object Clone ()
11664- {
11665- throw new NotImplementedException ();
11666- }
11667- }
11668-
11669- class NativeFieldsHandleRef : ICloneable {
11670- object A;
11671- System.Runtime.InteropServices.HandleRef B;
11672-
11673- public object Clone ()
11674- {
11675- throw new NotImplementedException ();
11676- }
11677- }
11678-
11679- abstract class AbstractNativeFields : IDisposable {
11680- object A;
11681- System.Runtime.InteropServices.HandleRef B;
11682-
11683- public abstract void Dispose ();
11684- }
11685-
11686- abstract class AbstractNativeFields2 : IDisposable {
11687- object A;
11688- System.Runtime.InteropServices.HandleRef B;
11689-
11690- public abstract void Dispose ();
11691-
11692-
11693- void IDisposable.Dispose ()
11694- {
11695- throw new NotImplementedException ();
11696- }
11697- }
11698-
11699- class NativeFieldsArray : ICloneable {
11700- object A;
11701- UIntPtr [] B;
11702-
11703- public object Clone ()
11704- {
11705- throw new NotImplementedException ();
11706- }
11707- }
11708-
11709- struct StructWithNativeFields {
11710- IntPtr a;
11711- UIntPtr b;
11712- HandleRef c;
11713- }
11714-
11715- class NativeStaticFieldsArray {
11716- object A;
11717- static UIntPtr [] B;
11718- }
11719-
11720- [TestFixture]
11721- public class TypesWithNativeFieldsShouldBeDisposableTest : TypeRuleTestFixture<TypesWithNativeFieldsShouldBeDisposableRule> {
11722-
11723- [Test]
11724- public void DoesNotApply ()
11725- {
11726- AssertRuleDoesNotApply (SimpleTypes.Delegate);
11727- AssertRuleDoesNotApply (SimpleTypes.Enum);
11728- AssertRuleDoesNotApply (SimpleTypes.Interface);
11729- AssertRuleDoesNotApply (SimpleTypes.Structure);
11730- }
11731-
11732- [Test]
11733- public void TestNoNativeFields ()
11734- {
11735- AssertRuleSuccess<NoNativeFields> ();
11736- }
11737-
11738- [Test]
11739- public void TestNativeFieldsImplementsIDisposeable ()
11740- {
11741- AssertRuleSuccess<NativeFieldsImplementsIDisposeable> ();
11742- }
11743-
11744- [Test]
11745- public void TestNativeFieldsExplicit ()
11746- {
11747- AssertRuleSuccess<NativeFieldsExplicit> ();
11748- }
11749-
11750- [Test]
11751- public void TestNativeFieldsIntPtr ()
11752- {
11753- AssertRuleFailure<NativeFieldsIntPtr> (1);
11754- }
11755-
11756- [Test]
11757- public void TestNativeFieldsUIntPtr ()
11758- {
11759- AssertRuleFailure<NativeFieldsUIntPtr> (1);
11760- }
11761-
11762- [Test]
11763- public void TestNativeFieldsHandleRef ()
11764- {
11765- AssertRuleFailure<NativeFieldsHandleRef> (1);
11766- }
11767-
11768- [Test]
11769- public void TestAbstractNativeFields ()
11770- {
11771- AssertRuleFailure<AbstractNativeFields> (2);
11772- }
11773-
11774- [Test]
11775- public void TestAbstractNativeFields2 ()
11776- {
11777- AssertRuleFailure<AbstractNativeFields2> (2);
11778- }
11779-
11780- [Test]
11781- public void TestNativeFieldsArray ()
11782- {
11783- AssertRuleFailure<NativeFieldsArray> (1);
11784- }
11785-
11786- [Test]
11787- public void TestStructWithNativeFields ()
11788- {
11789- AssertRuleDoesNotApply<StructWithNativeFields> ();
11790- }
11791-
11792- [Test]
11793- public void TestNativeStaticFieldsArray ()
11794- {
11795- AssertRuleSuccess<NativeStaticFieldsArray> ();
11796- }
11797- }
11798-}
11799diff --git a/gendarme/rules/Gendarme.Rules.Design/TypesWithDisposableFieldsShouldBeDisposableRule.cs b/gendarme/rules/Gendarme.Rules.Design/TypesWithDisposableFieldsShouldBeDisposableRule.cs
11800deleted file mode 100644
11801index b1d6f85..0000000
11802--- a/gendarme/rules/Gendarme.Rules.Design/TypesWithDisposableFieldsShouldBeDisposableRule.cs
11803+++ /dev/null
11804@@ -1,136 +0,0 @@
11805-//
11806-// Gendarme.Rules.Design.TypesWithDisposableFieldsShouldBeDisposableRule
11807-//
11808-// Authors:
11809-// Andreas Noever <andreas.noever@gmail.com>
11810-//
11811-// (C) 2008 Andreas Noever
11812-//
11813-// Permission is hereby granted, free of charge, to any person obtaining
11814-// a copy of this software and associated documentation files (the
11815-// "Software"), to deal in the Software without restriction, including
11816-// without limitation the rights to use, copy, modify, merge, publish,
11817-// distribute, sublicense, and/or sell copies of the Software, and to
11818-// permit persons to whom the Software is furnished to do so, subject to
11819-// the following conditions:
11820-//
11821-// The above copyright notice and this permission notice shall be
11822-// included in all copies or substantial portions of the Software.
11823-//
11824-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11825-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11826-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
11827-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
11828-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
11829-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
11830-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11831-//
11832-
11833-using System;
11834-using System.Text;
11835-using System.Collections.Generic;
11836-using System.Diagnostics;
11837-using System.IO;
11838-
11839-using Mono.Cecil;
11840-using Mono.Cecil.Cil;
11841-using Gendarme.Framework;
11842-using Gendarme.Framework.Helpers;
11843-using Gendarme.Framework.Rocks;
11844-
11845-namespace Gendarme.Rules.Design {
11846-
11847- /// <summary>
11848- /// This rule will fire if a type contains disposable fields but does not implement
11849- /// <c>System.IDisposable</c>.
11850- /// </summary>
11851- /// <example>
11852- /// Bad examples:
11853- /// <code>
11854- /// class DoesNotImplementIDisposable {
11855- /// IDisposable field;
11856- /// }
11857- ///
11858- /// class AbstractDispose : IDisposable {
11859- /// IDisposable field;
11860- ///
11861- /// // the field should be disposed in the type that declares it
11862- /// public abstract void Dispose ();
11863- /// }
11864- /// </code>
11865- /// </example>
11866- /// <example>
11867- /// Good example:
11868- /// <code>
11869- /// class Dispose : IDisposable {
11870- /// IDisposable field;
11871- ///
11872- /// public void Dispose ()
11873- /// {
11874- /// field.Dispose ();
11875- /// }
11876- /// }
11877- /// </code>
11878- /// </example>
11879-
11880- [Problem ("This type contains disposable field(s) but doesn't implement IDisposable.")]
11881- [Solution ("Implement IDisposable and free the disposable field(s) in the Dispose method.")]
11882- [FxCopCompatibility ("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
11883- public class TypesWithDisposableFieldsShouldBeDisposableRule : Rule, ITypeRule {
11884-
11885- private const string AbstractTypeMessage = "Field implement IDisposable. Type should implement a non-abstract Dispose() method";
11886- private const string TypeMessage = "Field implement IDisposable. Type should implement a Dispose() method";
11887- private const string AbstractDisposeMessage = "Some field(s) implement IDisposable. Making this method abstract shifts the reponsability of disposing those fields to the inheritors of this class.";
11888-
11889- static bool IsAbstract (MethodDefinition method)
11890- {
11891- return ((method != null) && (method.IsAbstract));
11892- }
11893-
11894- public RuleResult CheckType (TypeDefinition type)
11895- {
11896- // rule doesn't apply to enums, interfaces, structs, delegates or generated code
11897- if (type.IsEnum || type.IsInterface || type.IsValueType || type.IsDelegate () || type.IsGeneratedCode ())
11898- return RuleResult.DoesNotApply;
11899-
11900- MethodDefinition explicitDisposeMethod = null;
11901- MethodDefinition implicitDisposeMethod = null;
11902-
11903- bool abstractWarning = false;
11904-
11905- if (type.Implements ("System.IDisposable")) {
11906- implicitDisposeMethod = type.GetMethod (MethodSignatures.Dispose);
11907- explicitDisposeMethod = type.GetMethod (MethodSignatures.DisposeExplicit);
11908-
11909- if (IsAbstract (implicitDisposeMethod) || IsAbstract (explicitDisposeMethod)) {
11910- abstractWarning = true;
11911- } else {
11912- return RuleResult.Success;
11913- }
11914- }
11915-
11916- foreach (FieldDefinition field in type.Fields) {
11917- // we can't dispose static fields in IDisposable
11918- if (field.IsStatic)
11919- continue;
11920- TypeDefinition fieldType = field.FieldType.GetElementType ().Resolve ();
11921- if (fieldType == null)
11922- continue;
11923- // enums and primitives don't implement IDisposable
11924- if (fieldType.IsEnum || fieldType.IsPrimitive)
11925- continue;
11926- if (fieldType.Implements ("System.IDisposable")) {
11927- Runner.Report (field, Severity.High, Confidence.High,
11928- abstractWarning ? AbstractTypeMessage : TypeMessage);
11929- }
11930- }
11931-
11932- // Warn about possible confusion if the Dispose methods are abstract
11933- if (IsAbstract (implicitDisposeMethod))
11934- Runner.Report (implicitDisposeMethod, Severity.Medium, Confidence.High, AbstractDisposeMessage);
11935-
11936- return Runner.CurrentRuleResult;
11937- }
11938- }
11939-}
11940-
11941diff --git a/gendarme/rules/Gendarme.Rules.Design/TypesWithNativeFieldsShouldBeDisposableRule.cs b/gendarme/rules/Gendarme.Rules.Design/TypesWithNativeFieldsShouldBeDisposableRule.cs
11942deleted file mode 100644
11943index 113a5dd..0000000
11944--- a/gendarme/rules/Gendarme.Rules.Design/TypesWithNativeFieldsShouldBeDisposableRule.cs
11945+++ /dev/null
11946@@ -1,123 +0,0 @@
11947-//
11948-// Gendarme.Rules.Design.TypesWithNativeFieldsShouldBeDisposableRule
11949-//
11950-// Authors:
11951-// Andreas Noever <andreas.noever@gmail.com>
11952-//
11953-// (C) 2008 Andreas Noever
11954-//
11955-// Permission is hereby granted, free of charge, to any person obtaining
11956-// a copy of this software and associated documentation files (the
11957-// "Software"), to deal in the Software without restriction, including
11958-// without limitation the rights to use, copy, modify, merge, publish,
11959-// distribute, sublicense, and/or sell copies of the Software, and to
11960-// permit persons to whom the Software is furnished to do so, subject to
11961-// the following conditions:
11962-//
11963-// The above copyright notice and this permission notice shall be
11964-// included in all copies or substantial portions of the Software.
11965-//
11966-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11967-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11968-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
11969-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
11970-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
11971-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
11972-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11973-//
11974-
11975-using System;
11976-using Mono.Cecil;
11977-using Gendarme.Framework;
11978-using Gendarme.Framework.Helpers;
11979-using Gendarme.Framework.Rocks;
11980-
11981-namespace Gendarme.Rules.Design {
11982-
11983- /// <summary>
11984- /// This rule will fire if a type contains <c>IntPtr</c>, <c>UIntPtr</c>, or
11985- /// <c>HandleRef</c> fields but does not implement <c>System.IDisposable</c>.
11986- /// </summary>
11987- /// <example>
11988- /// Bad examples:
11989- /// <code>
11990- /// public class DoesNotImplementIDisposable {
11991- /// IntPtr field;
11992- /// }
11993- ///
11994- /// abstract public class AbstractDispose : IDisposable {
11995- /// IntPtr field;
11996- ///
11997- /// // the field should be disposed in the type that declares it
11998- /// public abstract void Dispose ();
11999- /// }
12000- /// </code>
12001- /// </example>
12002- /// <example>
12003- /// Good example:
12004- /// <code>
12005- /// public class Dispose : IDisposable {
12006- /// IDisposable field;
12007- ///
12008- /// public void Dispose ()
12009- /// {
12010- /// UnmanagedFree (field);
12011- /// }
12012- /// }
12013- /// </code>
12014- /// </example>
12015-
12016- [Problem ("This type contains native field(s) but doesn't implement IDisposable.")]
12017- [Solution ("Implement IDisposable and free the native field(s) in the Dispose method.")]
12018- [FxCopCompatibility ("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")]
12019- public class TypesWithNativeFieldsShouldBeDisposableRule : Rule, ITypeRule {
12020-
12021- private const string AbstractTypeMessage = "Field is native. Type should implement a non-abstract Dispose() method";
12022- private const string TypeMessage = "Field is native. Type should implement a Dispose() method";
12023- private const string AbstractDisposeMessage = "Some fields are native pointers. Making this method abstract shifts the reponsability of disposing those fields to the inheritors of this class.";
12024-
12025- static bool IsAbstract (MethodDefinition method)
12026- {
12027- return ((method != null) && (method.IsAbstract));
12028- }
12029-
12030- public RuleResult CheckType (TypeDefinition type)
12031- {
12032- // rule doesn't apply to enums, interfaces, structs, delegates or generated code
12033- if (type.IsEnum || type.IsInterface || type.IsValueType || type.IsDelegate () || type.IsGeneratedCode ())
12034- return RuleResult.DoesNotApply;
12035-
12036- MethodDefinition explicitDisposeMethod = null;
12037- MethodDefinition implicitDisposeMethod = null;
12038-
12039- bool abstractWarning = false;
12040-
12041- if (type.Implements ("System.IDisposable")) {
12042- implicitDisposeMethod = type.GetMethod (MethodSignatures.Dispose);
12043- explicitDisposeMethod = type.GetMethod (MethodSignatures.DisposeExplicit);
12044-
12045- if (IsAbstract (implicitDisposeMethod) || IsAbstract (explicitDisposeMethod)) {
12046- abstractWarning = true;
12047- } else {
12048- return RuleResult.Success;
12049- }
12050- }
12051-
12052- foreach (FieldDefinition field in type.Fields) {
12053- // we can't dispose static fields in IDisposable
12054- if (field.IsStatic)
12055- continue;
12056- if (field.FieldType.GetElementType ().IsNative ()) {
12057- Runner.Report (field, Severity.High, Confidence.High,
12058- abstractWarning ? AbstractTypeMessage : TypeMessage);
12059- }
12060- }
12061-
12062- // Warn about possible confusion if the Dispose methods are abstract
12063- if (IsAbstract (implicitDisposeMethod))
12064- Runner.Report (implicitDisposeMethod, Severity.Medium, Confidence.High, AbstractDisposeMessage);
12065-
12066- return Runner.CurrentRuleResult;
12067- }
12068- }
12069-}
12070diff --git a/gendarme/rules/Gendarme.Rules.Design/UseCorrectDisposeSignaturesRule.cs b/gendarme/rules/Gendarme.Rules.Design/UseCorrectDisposeSignaturesRule.cs
12071index 6041eb4..697c61b 100644
12072--- a/gendarme/rules/Gendarme.Rules.Design/UseCorrectDisposeSignaturesRule.cs
12073+++ b/gendarme/rules/Gendarme.Rules.Design/UseCorrectDisposeSignaturesRule.cs
12074@@ -141,10 +141,10 @@ namespace Gendarme.Rules.Design {
12075 if (type.IsInterface || type.IsEnum || type.IsDelegate ())
12076 return RuleResult.DoesNotApply;
12077
12078- if (type.Implements ("System.IDisposable")) {
12079+ if (type.Implements ("System", "IDisposable")) {
12080 Log.WriteLine (this);
12081 Log.WriteLine (this, "----------------------------------");
12082- Log.WriteLine (this, type.FullName);
12083+ Log.WriteLine (this, type);
12084
12085 MethodDefinition dispose0 = null;
12086 MethodDefinition dispose1 = null;
12087@@ -236,7 +236,7 @@ namespace Gendarme.Rules.Design {
12088 {
12089 if (type.HasInterfaces) {
12090 foreach (TypeReference candidate in type.Interfaces) {
12091- if (candidate.FullName == "System.IDisposable")
12092+ if (candidate.IsNamed ("System", "IDisposable"))
12093 return true;
12094 }
12095 }
12096diff --git a/gendarme/rules/Gendarme.Rules.Design/UseFlagsAttributeRule.cs b/gendarme/rules/Gendarme.Rules.Design/UseFlagsAttributeRule.cs
12097index 79671d8..c6adf87 100644
12098--- a/gendarme/rules/Gendarme.Rules.Design/UseFlagsAttributeRule.cs
12099+++ b/gendarme/rules/Gendarme.Rules.Design/UseFlagsAttributeRule.cs
12100@@ -27,6 +27,7 @@
12101 using System;
12102 using System.Collections.Generic;
12103 using System.Diagnostics;
12104+using System.Globalization;
12105 using System.Linq;
12106
12107 using Mono.Cecil;
12108@@ -94,7 +95,7 @@ namespace Gendarme.Rules.Design {
12109 values.Add (value);
12110
12111 } else {
12112- long v = Convert.ToInt64 (o);
12113+ long v = Convert.ToInt64 (o, CultureInfo.InvariantCulture);
12114
12115 if (v > 0) {
12116 value = (ulong) v;
12117@@ -159,7 +160,7 @@ namespace Gendarme.Rules.Design {
12118 #if DEBUG
12119 Log.WriteLine (this);
12120 Log.WriteLine (this, "------------------------------------");
12121- Log.WriteLine (this, type.FullName);
12122+ Log.WriteLine (this, type);
12123 Log.WriteLine (this, "values: {0}", string.Join (" ", (from x in values select x.ToString ("X4")).ToArray ()));
12124 #endif
12125
12126diff --git a/gendarme/rules/Gendarme.Rules.Design/UsingCloneWithoutImplementingICloneableRule.cs b/gendarme/rules/Gendarme.Rules.Design/UsingCloneWithoutImplementingICloneableRule.cs
12127index f33e66f..3184afc 100644
12128--- a/gendarme/rules/Gendarme.Rules.Design/UsingCloneWithoutImplementingICloneableRule.cs
12129+++ b/gendarme/rules/Gendarme.Rules.Design/UsingCloneWithoutImplementingICloneableRule.cs
12130@@ -95,7 +95,7 @@ namespace Gendarme.Rules.Design {
12131 public RuleResult CheckType (TypeDefinition type)
12132 {
12133 // rule applies to type that doesn't implement System.IClonable
12134- if (type.Implements ("System.ICloneable"))
12135+ if (type.Implements ("System", "ICloneable"))
12136 return RuleResult.DoesNotApply;
12137
12138 foreach (MethodDefinition method in type.Methods) {
12139@@ -110,7 +110,7 @@ namespace Gendarme.Rules.Design {
12140
12141 // that return System.Object, e.g. public object Clone()
12142 // or the current type, e.g. public <type> Clone()
12143- if (method.ReturnType.FullName == "System.Object")
12144+ if (method.ReturnType.IsNamed ("System", "Object"))
12145 Runner.Report (method, Severity.Low, Confidence.High);
12146 }
12147
12148diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/AvoidArgumentExceptionDefaultConstructorRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/AvoidArgumentExceptionDefaultConstructorRule.cs
12149index 6ddab93..44b14df 100644
12150--- a/gendarme/rules/Gendarme.Rules.Exceptions/AvoidArgumentExceptionDefaultConstructorRule.cs
12151+++ b/gendarme/rules/Gendarme.Rules.Exceptions/AvoidArgumentExceptionDefaultConstructorRule.cs
12152@@ -96,21 +96,22 @@ namespace Gendarme.Rules.Exceptions {
12153 continue;
12154
12155 TypeReference type = ctor.DeclaringType;
12156- string name = type.FullName;
12157- switch (name) {
12158- // most common cases
12159- case "System.ArgumentException":
12160- case "System.ArgumentNullException":
12161- case "System.ArgumentOutOfRangeException":
12162- case "System.DuplicateWaitObjectException":
12163- Runner.Report (method, ins, Severity.Medium, Confidence.Total, name);
12164- break;
12165- default:
12166- if (!name.EndsWith ("Exception", StringComparison.Ordinal))
12167- break;
12168- if (type.Inherits ("System.ArgumentException"))
12169- Runner.Report (method, ins, Severity.Medium, Confidence.Total, name);
12170- break;
12171+ string name = type.Name;
12172+ if (type.Namespace == "System") {
12173+ // most common cases
12174+ switch (name) {
12175+ case "ArgumentException":
12176+ case "ArgumentNullException":
12177+ case "ArgumentOutOfRangeException":
12178+ case "DuplicateWaitObjectException":
12179+ Runner.Report (method, ins, Severity.Medium, Confidence.Total, type.GetFullName ());
12180+ continue;
12181+ }
12182+ }
12183+
12184+ if (name.EndsWith ("Exception", StringComparison.Ordinal)) {
12185+ if (type.Inherits ("System", "ArgumentException"))
12186+ Runner.Report (method, ins, Severity.Medium, Confidence.Total, type.GetFullName ());
12187 }
12188 }
12189 return Runner.CurrentRuleResult;
12190diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/AvoidThrowingBasicExceptionsRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/AvoidThrowingBasicExceptionsRule.cs
12191index a43d01c..0ac510d 100644
12192--- a/gendarme/rules/Gendarme.Rules.Exceptions/AvoidThrowingBasicExceptionsRule.cs
12193+++ b/gendarme/rules/Gendarme.Rules.Exceptions/AvoidThrowingBasicExceptionsRule.cs
12194@@ -26,6 +26,7 @@
12195 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
12196 // THE SOFTWARE.
12197
12198+using Mono.Cecil;
12199 using Gendarme.Framework;
12200
12201 namespace Gendarme.Rules.Exceptions {
12202@@ -67,15 +68,12 @@ namespace Gendarme.Rules.Exceptions {
12203 [FxCopCompatibility ("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
12204 public class AvoidThrowingBasicExceptionsRule : NewExceptionsRule {
12205
12206- static string [] BasicExceptions = {
12207- "System.Exception",
12208- "System.ApplicationException",
12209- "System.SystemException"
12210- };
12211-
12212- protected override string [] GetExceptionTypes ()
12213+ protected override bool CheckException (TypeReference type)
12214 {
12215- return BasicExceptions;
12216+ if ((type == null) || (type.Namespace != "System"))
12217+ return false;
12218+ string name = type.Name;
12219+ return ((name == "Exception") || (name == "ApplicationException") || (name == "SystemException"));
12220 }
12221
12222 protected override Severity Severity {
12223diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotDestroyStackTraceRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotDestroyStackTraceRule.cs
12224index b1587d7..661b53f 100644
12225--- a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotDestroyStackTraceRule.cs
12226+++ b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotDestroyStackTraceRule.cs
12227@@ -1,7 +1,7 @@
12228 //
12229 // DoNotDestroyStackTraceRule
12230 //
12231-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
12232+// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
12233 //
12234 // Permission is hereby granted, free of charge, to any person obtaining
12235 // a copy of this software and associated documentation files (the
12236@@ -23,7 +23,6 @@
12237 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12238 //
12239
12240-using System;
12241 using System.Collections.Generic;
12242
12243 using Mono.Cecil;
12244@@ -31,6 +30,7 @@ using Mono.Cecil.Cil;
12245
12246 using Gendarme.Framework;
12247 using Gendarme.Framework.Engines;
12248+using Gendarme.Framework.Helpers;
12249 using Gendarme.Framework.Rocks;
12250 using Gendarme.Rules.Exceptions.Impl;
12251
12252@@ -74,39 +74,116 @@ namespace Gendarme.Rules.Exceptions {
12253 [FxCopCompatibility ("Microsoft.Usage", "CA2200:RethrowToPreserveStackDetails")]
12254 public class DoNotDestroyStackTraceRule : Rule, IMethodRule {
12255
12256+ // all branches instructions except leave[_s]
12257+ static OpCodeBitmask branches = new OpCodeBitmask (0xFFFFFC0000000000, 0xF, 0x0, 0x0);
12258+
12259 private List<int> warned_offsets_in_method = new List<int> ();
12260
12261 public RuleResult CheckMethod (MethodDefinition method)
12262 {
12263 // rule only applies to methods with IL and exceptions handlers
12264- if (!method.HasBody)
12265- return RuleResult.DoesNotApply;
12266-
12267- MethodBody body = method.Body;
12268- if (!body.HasExceptionHandlers)
12269+ if (!method.HasBody || !method.Body.HasExceptionHandlers)
12270 return RuleResult.DoesNotApply;
12271
12272 // and when the IL contains a Throw instruction (Rethrow is fine)
12273- if (!OpCodeEngine.GetBitmask (method).Get (Code.Throw))
12274+ OpCodeBitmask mask = OpCodeEngine.GetBitmask (method);
12275+ if (!mask.Get (Code.Throw))
12276 return RuleResult.DoesNotApply;
12277
12278+ // we can use a faster code path when no branches are present in the method
12279+ if (mask.Intersect (branches)) {
12280+ Branches (method);
12281+ } else {
12282+ Branchless (method);
12283+ }
12284+
12285 warned_offsets_in_method.Clear ();
12286+
12287+ return Runner.CurrentRuleResult;
12288+ }
12289+
12290+ private void Branchless (MethodDefinition method)
12291+ {
12292+ // Current stack position: 0 = top of stack
12293+ int exStackPos = 0;
12294+ // Local variable position: -1 = not stored in local variable
12295+ int localVarPos = -1;
12296+
12297+ foreach (ExceptionHandler eh in method.Body.ExceptionHandlers) {
12298+ if (eh.HandlerType != ExceptionHandlerType.Catch)
12299+ continue;
12300+
12301+ ProcessCatchBlock (eh.HandlerStart, eh.HandlerEnd, method, ref exStackPos, ref localVarPos);
12302+ }
12303+ }
12304+
12305+ private void ProcessCatchBlock (Instruction first, Instruction last, MethodDefinition method, ref int exStackPos, ref int localVarPos)
12306+ {
12307+ Instruction cur = null;
12308+
12309+ while (cur != last) {
12310+ if (cur == null)
12311+ cur = first;
12312+ else
12313+ cur = cur.Next;
12314+
12315+ // Rethrown exception - no problem!
12316+ if (cur.Is (Code.Rethrow))
12317+ return;
12318+
12319+ if (cur.IsStoreLocal ()) {
12320+ int varIndex = cur.GetVariable (method).Index;
12321+ if (exStackPos == 0) {
12322+ // Storing argument on top of stack in local variable reference
12323+ localVarPos = varIndex;
12324+ exStackPos = -1;
12325+ } else if (localVarPos != -1 && varIndex == localVarPos)
12326+ // Writing over orignal exception...
12327+ localVarPos = -1;
12328+ } else if (localVarPos != -1 && cur.IsLoadLocal ()) {
12329+ int varIndex = cur.GetVariable (method).Index;
12330+ if (varIndex == localVarPos)
12331+ // Loading exception from local var back onto stack
12332+ exStackPos = 0;
12333+ } else if (cur.Is (Code.Throw) && exStackPos == 0) {
12334+ // If our original exception is on top of the stack,
12335+ // we're rethrowing it.This is deemed naughty...
12336+ if (!warned_offsets_in_method.Contains (cur.Offset)) {
12337+ Runner.Report (method, cur, Severity.Critical, Confidence.High);
12338+ warned_offsets_in_method.Add (cur.Offset);
12339+ }
12340+ return;
12341+ } else if (exStackPos != -1) {
12342+ // If we're still on the stack, track our position after
12343+ // this instruction
12344+ int numPops = cur.GetPopCount (method);
12345+ if (exStackPos < numPops) {
12346+ // Popped ex off of stack
12347+ exStackPos = -1;
12348+ } else {
12349+ int numPushes = cur.GetPushCount ();
12350+ exStackPos += numPushes - numPops;
12351+ }
12352+ }
12353+ }
12354+ }
12355+
12356+ private void Branches (MethodDefinition method)
12357+ {
12358 ExecutionPathFactory epf = new ExecutionPathFactory ();
12359
12360- foreach (ExceptionHandler eh in body.ExceptionHandlers) {
12361+ foreach (ExceptionHandler eh in method.Body.ExceptionHandlers) {
12362 if (eh.HandlerType != ExceptionHandlerType.Catch)
12363 continue;
12364
12365 var list = epf.CreatePaths (eh.HandlerStart, eh.HandlerEnd);
12366 if (list.Count == 0) {
12367 Runner.Report (method, eh.HandlerStart, Severity.Medium, Confidence.Normal, "Handler too complex for analysis");
12368- } else {
12369+ } else {
12370 foreach (ExecutionPathCollection catchPath in list)
12371 ProcessCatchPath (catchPath, method);
12372 }
12373 }
12374-
12375- return Runner.CurrentRuleResult;
12376 }
12377
12378 private void ProcessCatchPath (IEnumerable<ExecutionBlock> catchPath, MethodDefinition method)
12379@@ -120,54 +197,41 @@ namespace Gendarme.Rules.Exceptions {
12380 int localVarPos = -1;
12381
12382 foreach (ExecutionBlock block in catchPath) {
12383- Instruction cur = null;
12384-
12385- while (cur != block.Last) {
12386- if (cur == null)
12387- cur = block.First;
12388- else
12389- cur = cur.Next;
12390-
12391- if (cur.OpCode == OpCodes.Rethrow)
12392- // Rethrown exception - no problem!
12393- return;
12394-
12395- if (cur.IsStoreLocal ()) {
12396- int varIndex = cur.GetVariable (method).Index;
12397- if (exStackPos == 0) {
12398- // Storing argument on top of stack in local variable reference
12399- localVarPos = varIndex;
12400- exStackPos = -1;
12401- } else if (localVarPos != -1 && varIndex == localVarPos)
12402- // Writing over orignal exception...
12403- localVarPos = -1;
12404- } else if (localVarPos != -1 && cur.IsLoadLocal ()) {
12405- int varIndex = cur.GetVariable (method).Index;
12406- if (varIndex == localVarPos)
12407- // Loading exception from local var back onto stack
12408- exStackPos = 0;
12409- } else if (cur.OpCode == OpCodes.Throw && exStackPos == 0) {
12410- // If our original exception is on top of the stack,
12411- // we're rethrowing it.This is deemed naughty...
12412- if (!warned_offsets_in_method.Contains (cur.Offset)) {
12413- Runner.Report (method, cur, Severity.Critical, Confidence.High);
12414- warned_offsets_in_method.Add (cur.Offset);
12415- }
12416- return;
12417- } else if (exStackPos != -1) {
12418- // If we're still on the stack, track our position after
12419- // this instruction
12420- int numPops = cur.GetPopCount (method);
12421- if (exStackPos < numPops) {
12422- // Popped ex off of stack
12423- exStackPos = -1;
12424- } else {
12425- int numPushes = cur.GetPushCount ();
12426- exStackPos += numPushes - numPops;
12427- }
12428- }
12429- }
12430+ ProcessCatchBlock (block.First, block.Last, method, ref exStackPos, ref localVarPos);
12431 }
12432 }
12433+#if false
12434+ public void Bitmask ()
12435+ {
12436+ OpCodeBitmask branches = new OpCodeBitmask ();
12437+ branches.Set (Code.Beq);
12438+ branches.Set (Code.Beq_S);
12439+ branches.Set (Code.Bge);
12440+ branches.Set (Code.Bge_S);
12441+ branches.Set (Code.Bge_Un);
12442+ branches.Set (Code.Bge_Un_S);
12443+ branches.Set (Code.Bgt);
12444+ branches.Set (Code.Bgt_S);
12445+ branches.Set (Code.Bgt_Un);
12446+ branches.Set (Code.Bgt_Un_S);
12447+ branches.Set (Code.Ble);
12448+ branches.Set (Code.Ble_S);
12449+ branches.Set (Code.Ble_Un);
12450+ branches.Set (Code.Ble_Un_S);
12451+ branches.Set (Code.Blt);
12452+ branches.Set (Code.Blt_S);
12453+ branches.Set (Code.Blt_Un);
12454+ branches.Set (Code.Blt_Un_S);
12455+ branches.Set (Code.Bne_Un);
12456+ branches.Set (Code.Bne_Un_S);
12457+ branches.Set (Code.Br);
12458+ branches.Set (Code.Br_S);
12459+ branches.Set (Code.Brfalse);
12460+ branches.Set (Code.Brfalse_S);
12461+ branches.Set (Code.Brtrue);
12462+ branches.Set (Code.Brtrue_S);
12463+ Console.WriteLine (branches);
12464+ }
12465+#endif
12466 }
12467 }
12468diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInNonCatchClausesRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInNonCatchClausesRule.cs
12469new file mode 100644
12470index 0000000..f237349
12471--- /dev/null
12472+++ b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInNonCatchClausesRule.cs
12473@@ -0,0 +1,113 @@
12474+//
12475+// Gendarme.Rules.Exceptions.DoNotThrowInNonCatchClausesRule
12476+//
12477+// Authors:
12478+// Sebastien Pouliot <sebastien@ximian.com>
12479+//
12480+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
12481+//
12482+// Permission is hereby granted, free of charge, to any person obtaining
12483+// a copy of this software and associated documentation files (the
12484+// "Software"), to deal in the Software without restriction, including
12485+// without limitation the rights to use, copy, modify, merge, publish,
12486+// distribute, sublicense, and/or sell copies of the Software, and to
12487+// permit persons to whom the Software is furnished to do so, subject to
12488+// the following conditions:
12489+//
12490+// The above copyright notice and this permission notice shall be
12491+// included in all copies or substantial portions of the Software.
12492+//
12493+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12494+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12495+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
12496+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
12497+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
12498+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
12499+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12500+//
12501+
12502+using Mono.Cecil;
12503+using Mono.Cecil.Cil;
12504+
12505+using Gendarme.Framework;
12506+using Gendarme.Framework.Engines;
12507+using Gendarme.Framework.Rocks;
12508+
12509+namespace Gendarme.Rules.Exceptions {
12510+
12511+ /// <summary>
12512+ /// This rule detects exceptions that are throw in <c>fault</c>, <c>filter</c> or
12513+ /// <c>finally</c> clauses. Such exceptions will make it much harder to debug your
12514+ /// applications since it will hide the original exception.
12515+ /// </summary>
12516+ /// <example>
12517+ /// Bad example:
12518+ /// <code>
12519+ /// int err = 0;
12520+ /// try {
12521+ /// err = Initialize ();
12522+ /// }
12523+ /// finally {
12524+ /// Cleanup ();
12525+ /// if (err != 0)
12526+ /// throw new NotSupportedException ();
12527+ /// }
12528+ /// </code>
12529+ /// </example>
12530+ /// <example>
12531+ /// Good example:
12532+ /// <code>
12533+ /// try {
12534+ /// if (Initialize () != 0)
12535+ /// throw new NotSupportedException ();
12536+ /// }
12537+ /// finally {
12538+ /// Cleanup ();
12539+ /// }
12540+ /// </code>
12541+ /// </example>
12542+ [Problem ("An exception is thrown in a fault, filter or finally clause.")]
12543+ [Solution ("Remove the exception or move it inside the try or catch clause.")]
12544+ [FxCopCompatibility ("Microsoft.Usage", "CA2219:DoNotRaiseExceptionsInExceptionClauses")]
12545+ [EngineDependency (typeof (OpCodeEngine))]
12546+ public class DoNotThrowInNonCatchClausesRule : Rule, IMethodRule {
12547+
12548+ void CheckBlock (MethodDefinition method, Instruction start, Instruction end)
12549+ {
12550+ Instruction ins = start;
12551+ while (ins != end) {
12552+ if (ins.Is (Code.Throw))
12553+ Runner.Report (method, ins, Severity.High, Confidence.High);
12554+ ins = ins.Next;
12555+ }
12556+ }
12557+
12558+ public RuleResult CheckMethod (MethodDefinition method)
12559+ {
12560+ // rule only applies to methods with IL...
12561+ if (!method.HasBody)
12562+ return RuleResult.DoesNotApply;
12563+
12564+ // ... and exceptions handlers
12565+ MethodBody body = method.Body;
12566+ if (!body.HasExceptionHandlers)
12567+ return RuleResult.DoesNotApply;
12568+
12569+ // and when the IL contains a Throw instruction (Rethrow is fine)
12570+ if (!OpCodeEngine.GetBitmask (method).Get (Code.Throw))
12571+ return RuleResult.DoesNotApply;
12572+
12573+ foreach (ExceptionHandler eh in body.ExceptionHandlers) {
12574+ // throwing in catch handler is fine
12575+ if (eh.HandlerType == ExceptionHandlerType.Catch)
12576+ continue;
12577+
12578+ CheckBlock (method, eh.HandlerStart, eh.HandlerEnd);
12579+ if (eh.FilterStart != null)
12580+ CheckBlock (method, eh.FilterStart, eh.HandlerStart);
12581+ }
12582+
12583+ return Runner.CurrentRuleResult;
12584+ }
12585+ }
12586+}
12587diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInUnexpectedLocationRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInUnexpectedLocationRule.cs
12588index 88e4379..cd7ad5b 100644
12589--- a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInUnexpectedLocationRule.cs
12590+++ b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInUnexpectedLocationRule.cs
12591@@ -28,6 +28,9 @@
12592 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12593 //
12594
12595+using System.Globalization;
12596+using System.Text;
12597+
12598 using Mono.Cecil;
12599 using Mono.Cecil.Cil;
12600
12601@@ -160,10 +163,27 @@ namespace Gendarme.Rules.Exceptions {
12602 private static readonly OpCodeBitmask OverflowThrowers = new OpCodeBitmask (0x0, 0x8000000000000000, 0x3FC07F8000001FF, 0x0);
12603 private static readonly OpCodeBitmask Casts = new OpCodeBitmask (0x0, 0x48000000000000, 0x400000000, 0x0);
12604
12605- private static readonly string [] GetterExceptions = new string [] {"System.InvalidOperationException", "System.NotSupportedException"};
12606- private static readonly string [] IndexerExceptions = new string [] {"System.InvalidOperationException", "System.NotSupportedException", "System.ArgumentException", "System.Collections.Generic.KeyNotFoundException"};
12607- private static readonly string [] EventExceptions = new string [] {"System.InvalidOperationException", "System.NotSupportedException", "System.ArgumentException"};
12608- private static readonly string [] HashCodeExceptions = new string [] {"System.ArgumentException"};
12609+ private static readonly string [][] GetterExceptions = new string [][] {
12610+ new string [] { "System", "InvalidOperationException" },
12611+ new string [] { "System", "NotSupportedException"}
12612+ };
12613+
12614+ private static readonly string [][] IndexerExceptions = new string [][] {
12615+ new string [] { "System", "InvalidOperationException" },
12616+ new string [] { "System", "NotSupportedException" },
12617+ new string [] { "System", "ArgumentException" },
12618+ new string [] { "System.Collections.Generic", "KeyNotFoundException" }
12619+ };
12620+
12621+ private static readonly string [][] EventExceptions = new string [][] {
12622+ new string [] { "System", "InvalidOperationException" },
12623+ new string [] { "System", "NotSupportedException" },
12624+ new string [] { "System", "ArgumentException" }
12625+ };
12626+
12627+ private static readonly string [][] HashCodeExceptions = new string [][] {
12628+ new string [] { "System", "ArgumentException" }
12629+ };
12630
12631 private static bool CheckAttributes (MethodReference method, MethodAttributes attrs)
12632 {
12633@@ -180,7 +200,7 @@ namespace Gendarme.Rules.Exceptions {
12634
12635 private MethodSignature equals_signature;
12636 private MethodSignature hashcode_signature;
12637- private string [] allowedExceptions;
12638+ private string [][] allowedExceptions;
12639 private Severity severity;
12640 private bool is_equals;
12641
12642@@ -189,7 +209,7 @@ namespace Gendarme.Rules.Exceptions {
12643 base.Initialize (runner);
12644
12645 Runner.AnalyzeType += delegate (object sender, RunnerEventArgs e) {
12646- if (e.CurrentType.Implements ("System.Collections.Generic.IEqualityComparer`1")) {
12647+ if (e.CurrentType.Implements ("System.Collections.Generic", "IEqualityComparer`1")) {
12648 equals_signature = EqualityComparer_Equals;
12649 hashcode_signature = EqualityComparer_GetHashCode;
12650 } else {
12651@@ -220,7 +240,7 @@ namespace Gendarme.Rules.Exceptions {
12652 return PreflightVirtualMethod (method);
12653 } else if (method.HasParameters && (method.Name == "Dispose")) {
12654 IList<ParameterDefinition> pdc = method.Parameters;
12655- if ((pdc.Count == 1) && (pdc [0].ParameterType.FullName == "System.Boolean"))
12656+ if ((pdc.Count == 1) && pdc [0].ParameterType.IsNamed ("System", "Boolean"))
12657 return "Dispose (bool)";
12658 } else if (MethodSignatures.TryParse.Matches (method)) {
12659 return "TryParse";
12660@@ -269,7 +289,7 @@ namespace Gendarme.Rules.Exceptions {
12661 } else if (MethodSignatures.Finalize.Matches (method)) {
12662 return "Finalizers";
12663 } else if (MethodSignatures.Dispose.Matches (method) || MethodSignatures.DisposeExplicit.Matches (method)) {
12664- if (method.DeclaringType.Implements ("System.IDisposable"))
12665+ if (method.DeclaringType.Implements ("System", "IDisposable"))
12666 return "IDisposable.Dispose";
12667 } else if (equals_signature != null && equals_signature.Matches (method)) {
12668 return "IEqualityComparer<T>.Equals";
12669@@ -288,14 +308,16 @@ namespace Gendarme.Rules.Exceptions {
12670 {
12671 switch (ins.OpCode.Code) {
12672 case Code.Castclass:
12673- return string.Format (" (cast to {0})", ((TypeReference) ins.Operand).Name);
12674+ return String.Format (CultureInfo.InvariantCulture, " (cast to {0})",
12675+ ((TypeReference) ins.Operand).Name);
12676
12677 case Code.Throw: // this one is obvious
12678 return string.Empty;
12679
12680 case Code.Unbox:
12681 case Code.Unbox_Any:
12682- return string.Format (" (unbox from {0})", ((TypeReference) ins.Operand).Name);
12683+ return String.Format (CultureInfo.InvariantCulture, " (unbox from {0})",
12684+ ((TypeReference) ins.Operand).Name);
12685
12686 case Code.Ckfinite:
12687 return " (the expression will throw if the value is a NAN or an infinity)";
12688@@ -360,7 +382,7 @@ namespace Gendarme.Rules.Exceptions {
12689 if (ins.Previous.Is (Code.Newobj)) {
12690 MethodReference mr = (MethodReference) ins.Previous.Operand;
12691 TypeReference tr = mr.DeclaringType;
12692- if (tr.FullName == "System.NotImplementedException" || tr.Inherits ("System.NotImplementedException"))
12693+ if (tr.IsNamed ("System", "NotImplementedException") || tr.Inherits ("System", "NotImplementedException"))
12694 continue;
12695 }
12696
12697@@ -372,13 +394,22 @@ namespace Gendarme.Rules.Exceptions {
12698 // If the throw does not one of the enumerated exceptions (or
12699 // a subclass) then we have a problem.
12700 else if (ins.Previous.Is (Code.Newobj)) {
12701- MethodReference mr = (MethodReference) ins.Previous.Operand;
12702- string name = mr.DeclaringType.FullName;
12703- if (Array.IndexOf (allowedExceptions, name) < 0) {
12704- if (!allowedExceptions.Any (e => mr.DeclaringType.Inherits (e))) {
12705- Report (method, ins, methodLabel);
12706+ TypeReference type = (ins.Previous.Operand as MethodReference ).DeclaringType;
12707+ bool allowed = false;
12708+ foreach (string[] entry in allowedExceptions) {
12709+ if (type.IsNamed (entry [0], entry [1]))
12710+ allowed = true;
12711+ }
12712+ if (!allowed) {
12713+ foreach (string [] entry in allowedExceptions) {
12714+ if (type.Inherits (entry [0], entry [1])) {
12715+ allowed = true;
12716+ break;
12717+ }
12718 }
12719 }
12720+ if (!allowed)
12721+ Report (method, ins, methodLabel);
12722 }
12723 }
12724 }
12725@@ -388,10 +419,21 @@ namespace Gendarme.Rules.Exceptions {
12726 private void Report (MethodDefinition method, Instruction ins, string methodLabel)
12727 {
12728 string mesg;
12729- if (allowedExceptions == null)
12730- mesg = string.Format ("{0} should not throw{1}.", methodLabel, ExplainThrow (ins));
12731- else
12732- mesg = string.Format ("{0} should only throw {1} or a subclass{2}.", methodLabel, string.Join (", ", allowedExceptions), ExplainThrow (ins));
12733+ if (allowedExceptions == null) {
12734+ mesg = String.Format (CultureInfo.InvariantCulture,
12735+ "{0} should not throw{1}.", methodLabel, ExplainThrow (ins));
12736+ } else {
12737+ StringBuilder sb = new StringBuilder ();
12738+ sb.Append (methodLabel).Append (" should only throw ");
12739+ for (int i = 0; i < allowedExceptions.Length; i++) {
12740+ string [] entry = allowedExceptions [i];
12741+ sb.Append (entry [0]).Append ('.').Append (entry [1]);
12742+ if (i < allowedExceptions.Length - 1)
12743+ sb.Append (", ");
12744+ }
12745+ sb.Append (" or a subclass").Append (ExplainThrow (ins)).Append ('.');
12746+ mesg = sb.ToString ();
12747+ }
12748
12749 Log.WriteLine (this, "{0:X4}: {1}", ins.Offset, mesg);
12750 Runner.Report (method, ins, severity, Confidence.High, mesg);
12751diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowReservedExceptionRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowReservedExceptionRule.cs
12752index c69fc7c..a7d989b 100644
12753--- a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowReservedExceptionRule.cs
12754+++ b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowReservedExceptionRule.cs
12755@@ -24,6 +24,7 @@
12756 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
12757 // THE SOFTWARE.
12758
12759+using Mono.Cecil;
12760 using Gendarme.Framework;
12761
12762 namespace Gendarme.Rules.Exceptions {
12763@@ -65,16 +66,20 @@ namespace Gendarme.Rules.Exceptions {
12764 [FxCopCompatibility ("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
12765 public class DoNotThrowReservedExceptionRule : NewExceptionsRule {
12766
12767- static string [] ReservedExceptions = {
12768- "System.ExecutionEngineException",
12769- "System.IndexOutOfRangeException",
12770- "System.NullReferenceException",
12771- "System.OutOfMemoryException"
12772- };
12773-
12774- protected override string [] GetExceptionTypes ()
12775+ protected override bool CheckException (TypeReference type)
12776 {
12777- return ReservedExceptions;
12778+ if (type == null)
12779+ return false;
12780+
12781+ switch (type.Name) {
12782+ case "ExecutionEngineException":
12783+ case "IndexOutOfRangeException":
12784+ case "NullReferenceException":
12785+ case "OutOfMemoryException":
12786+ return (type.Namespace == "System");
12787+ default:
12788+ return false;
12789+ }
12790 }
12791
12792 protected override Severity Severity {
12793diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DontSwallowErrorsCatchingNonspecificExceptionsRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DontSwallowErrorsCatchingNonspecificExceptionsRule.cs
12794index fce1269..903f5a6 100644
12795--- a/gendarme/rules/Gendarme.Rules.Exceptions/DontSwallowErrorsCatchingNonspecificExceptionsRule.cs
12796+++ b/gendarme/rules/Gendarme.Rules.Exceptions/DontSwallowErrorsCatchingNonspecificExceptionsRule.cs
12797@@ -91,16 +91,13 @@ namespace Gendarme.Rules.Exceptions {
12798 //}
12799 //catch {
12800 //}
12801- private static bool IsForbiddenTypeInCatches (string typeName)
12802+ private static bool IsForbiddenTypeInCatches (TypeReference type)
12803 {
12804- switch (typeName) {
12805- case "System.Exception":
12806- case "System.SystemException":
12807- case "System.Object":
12808- return true;
12809- default:
12810+ if (type.Namespace != "System")
12811 return false;
12812- }
12813+
12814+ string name = type.Name;
12815+ return ((name == "Exception") || (name == "SystemException") || (name == "Object"));
12816 }
12817
12818 // will always return exceptionHandler.HandlerStart if there's no 'rethrow' inside the method
12819@@ -127,8 +124,7 @@ namespace Gendarme.Rules.Exceptions {
12820 bool has_rethrow = OpCodeEngine.GetBitmask (method).Get (Code.Rethrow);
12821 foreach (ExceptionHandler exceptionHandler in body.ExceptionHandlers) {
12822 if (exceptionHandler.HandlerType == ExceptionHandlerType.Catch) {
12823- string catchTypeName = exceptionHandler.CatchType.FullName;
12824- if (IsForbiddenTypeInCatches (catchTypeName)) {
12825+ if (IsForbiddenTypeInCatches (exceptionHandler.CatchType)) {
12826 // quickly find 'throw_instruction' if there's no 'rethrow' used in this method
12827 Instruction throw_instruction = has_rethrow ?
12828 ThrowsGeneralException (exceptionHandler) :
12829diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/ExceptionShouldBeVisibleRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/ExceptionShouldBeVisibleRule.cs
12830index 284e5e7..1cce0b2 100644
12831--- a/gendarme/rules/Gendarme.Rules.Exceptions/ExceptionShouldBeVisibleRule.cs
12832+++ b/gendarme/rules/Gendarme.Rules.Exceptions/ExceptionShouldBeVisibleRule.cs
12833@@ -74,18 +74,16 @@ namespace Gendarme.Rules.Exceptions {
12834
12835 public RuleResult CheckType (TypeDefinition type)
12836 {
12837- if (type.BaseType == null)
12838+ TypeReference btype = type.BaseType;
12839+ if (btype == null)
12840 return RuleResult.DoesNotApply;
12841
12842 // rule apply only to type that inherits from the base exceptions
12843- switch (type.BaseType.FullName) {
12844- case "System.Exception":
12845- case "System.SystemException":
12846- case "System.ApplicationException":
12847- break;
12848- default:
12849+ if (btype.Namespace != "System")
12850+ return RuleResult.DoesNotApply;
12851+ string name = btype.Name;
12852+ if ((name != "Exception") && (name != "SystemException") && (name != "ApplicationException"))
12853 return RuleResult.DoesNotApply;
12854- }
12855
12856 if (type.IsAbstract || type.IsVisible ())
12857 return RuleResult.Success;
12858diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Gendarme.Rules.Exceptions.csproj b/gendarme/rules/Gendarme.Rules.Exceptions/Gendarme.Rules.Exceptions.csproj
12859index 179882b..db66ede 100644
12860--- a/gendarme/rules/Gendarme.Rules.Exceptions/Gendarme.Rules.Exceptions.csproj
12861+++ b/gendarme/rules/Gendarme.Rules.Exceptions/Gendarme.Rules.Exceptions.csproj
12862@@ -1,5 +1,5 @@
12863 <?xml version="1.0" encoding="utf-8"?>\r
12864-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
12865+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
12866 <PropertyGroup>\r
12867 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
12868 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
12869@@ -12,9 +12,11 @@
12870 <AssemblyName>Gendarme.Rules.Exceptions</AssemblyName>\r
12871 <FileUpgradeFlags>\r
12872 </FileUpgradeFlags>\r
12873- <OldToolsVersion>2.0</OldToolsVersion>\r
12874+ <OldToolsVersion>3.5</OldToolsVersion>\r
12875 <UpgradeBackupLocation>\r
12876 </UpgradeBackupLocation>\r
12877+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
12878+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
12879 <PublishUrl>http://localhost/Gendarme.Rules.Exceptions/</PublishUrl>\r
12880 <Install>true</Install>\r
12881 <InstallFrom>Web</InstallFrom>\r
12882@@ -27,10 +29,9 @@
12883 <MapFileExtensions>true</MapFileExtensions>\r
12884 <ApplicationRevision>0</ApplicationRevision>\r
12885 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
12886- <IsWebBootstrapper>true</IsWebBootstrapper>\r
12887 <UseApplicationTrust>false</UseApplicationTrust>\r
12888 <BootstrapperEnabled>true</BootstrapperEnabled>\r
12889- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
12890+ <TargetFrameworkProfile />\r
12891 </PropertyGroup>\r
12892 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
12893 <DebugSymbols>true</DebugSymbols>\r
12894@@ -43,6 +44,7 @@
12895 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Exceptions.xml</DocumentationFile>\r
12896 <NoWarn>1591</NoWarn>\r
12897 <WarningsAsErrors>1570</WarningsAsErrors>\r
12898+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
12899 </PropertyGroup>\r
12900 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
12901 <DebugType>pdbonly</DebugType>\r
12902@@ -54,6 +56,7 @@
12903 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Exceptions.xml</DocumentationFile>\r
12904 <NoWarn>1591</NoWarn>\r
12905 <WarningsAsErrors>1570</WarningsAsErrors>\r
12906+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
12907 </PropertyGroup>\r
12908 <ItemGroup>\r
12909 <Reference Include="System" />\r
12910@@ -96,14 +99,33 @@
12911 <None Include="ChangeLog" />\r
12912 </ItemGroup>\r
12913 <ItemGroup>\r
12914+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
12915+ <Visible>False</Visible>\r
12916+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
12917+ <Install>false</Install>\r
12918+ </BootstrapperPackage>\r
12919 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
12920 <Visible>False</Visible>\r
12921+ <ProductName>\r
12922+ </ProductName>\r
12923+ <Install>false</Install>\r
12924 </BootstrapperPackage>\r
12925 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
12926 <Visible>False</Visible>\r
12927+ <ProductName>\r
12928+ </ProductName>\r
12929+ <Install>false</Install>\r
12930 </BootstrapperPackage>\r
12931 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
12932 <Visible>False</Visible>\r
12933+ <ProductName>\r
12934+ </ProductName>\r
12935+ <Install>false</Install>\r
12936+ </BootstrapperPackage>\r
12937+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
12938+ <Visible>False</Visible>\r
12939+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
12940+ <Install>false</Install>\r
12941 </BootstrapperPackage>\r
12942 </ItemGroup>\r
12943 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
12944diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/InstantiateArgumentExceptionCorrectlyRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/InstantiateArgumentExceptionCorrectlyRule.cs
12945index b9b5dab..b085345 100644
12946--- a/gendarme/rules/Gendarme.Rules.Exceptions/InstantiateArgumentExceptionCorrectlyRule.cs
12947+++ b/gendarme/rules/Gendarme.Rules.Exceptions/InstantiateArgumentExceptionCorrectlyRule.cs
12948@@ -130,7 +130,7 @@ namespace Gendarme.Rules.Exceptions {
12949 return;
12950
12951 // OK public ArgumentException (string message, Exception innerException)
12952- if (pdc [1].ParameterType.FullName != "System.String")
12953+ if (!pdc [1].ParameterType.IsNamed ("System", "String"))
12954 return;
12955
12956 // CHECK public ArgumentException (string message, string paramName)
12957@@ -153,12 +153,17 @@ namespace Gendarme.Rules.Exceptions {
12958 // OK protected ArgumentNullException (SerializationInfo info, StreamingContext context)
12959 // OK public ArgumentNullException (string message, Exception innerException)
12960 IList<ParameterDefinition> pdc = constructor.Parameters;
12961- if ((pdc.Count == 2) && (pdc [1].ParameterType.FullName != "System.String"))
12962+ if ((pdc.Count == 2) && !pdc [1].ParameterType.IsNamed ("System", "String"))
12963 return;
12964
12965 // CHECK public ArgumentNullException (string paramName)
12966 // CHECK public ArgumentNullException (string paramName, string message)
12967 Instruction call = ins.TraceBack (method, 0);
12968+
12969+ // call will be null if there is branching logic in the selection of a message - just fon't check in this case
12970+ if (call == null)
12971+ return;
12972+
12973 string name = call.Operand as string;
12974 if (MatchesAnyParameter (method, name))
12975 return;
12976@@ -187,18 +192,19 @@ namespace Gendarme.Rules.Exceptions {
12977 continue;
12978
12979 MethodReference ctor = (current.Operand as MethodReference);
12980+ TypeReference type = ctor.DeclaringType;
12981+ if (type.Namespace != "System")
12982+ continue;
12983
12984- switch (ctor.DeclaringType.FullName) {
12985- case "System.ArgumentException":
12986+ switch (type.Name) {
12987+ case "ArgumentException":
12988 CheckArgumentException (ctor, current, method);
12989 break;
12990- case "System.ArgumentNullException":
12991- case "System.ArgumentOutOfRangeException":
12992- case "System.DuplicateWaitObjectException":
12993+ case "ArgumentNullException":
12994+ case "ArgumentOutOfRangeException":
12995+ case "DuplicateWaitObjectException":
12996 CheckOtherExceptions (ctor, current, method);
12997 break;
12998- default:
12999- continue;
13000 }
13001 }
13002
13003diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Makefile.am b/gendarme/rules/Gendarme.Rules.Exceptions/Makefile.am
13004index 071342b..30c2b74 100644
13005--- a/gendarme/rules/Gendarme.Rules.Exceptions/Makefile.am
13006+++ b/gendarme/rules/Gendarme.Rules.Exceptions/Makefile.am
13007@@ -4,6 +4,7 @@ rules_sources = \
13008 AvoidArgumentExceptionDefaultConstructorRule.cs \
13009 AvoidThrowingBasicExceptionsRule.cs \
13010 DoNotDestroyStackTraceRule.cs \
13011+ DoNotThrowInNonCatchClausesRule.cs \
13012 DoNotThrowInUnexpectedLocationRule.cs \
13013 DoNotThrowReservedExceptionRule.cs \
13014 DontSwallowErrorsCatchingNonspecificExceptionsRule.cs \
13015@@ -19,6 +20,7 @@ rules_sources = \
13016 tests_sources = \
13017 AvoidArgumentExceptionDefaultConstructorTest.cs \
13018 AvoidThrowingBasicExceptionsTest.cs \
13019+ DoNotThrowInNonCatchClausesTest.cs \
13020 DoNotThrowInUnexpectedLocationTest.cs \
13021 DontDestroyStackTraceTest.cs \
13022 DontSwallowErrorsCatchingNonspecificExceptionsTest.cs \
13023diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/MissingExceptionConstructorsRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/MissingExceptionConstructorsRule.cs
13024index 32663e5..d4d86af 100644
13025--- a/gendarme/rules/Gendarme.Rules.Exceptions/MissingExceptionConstructorsRule.cs
13026+++ b/gendarme/rules/Gendarme.Rules.Exceptions/MissingExceptionConstructorsRule.cs
13027@@ -26,6 +26,7 @@
13028
13029 using System;
13030 using System.Collections.Generic;
13031+using System.Globalization;
13032
13033 using Mono.Cecil;
13034
13035@@ -86,9 +87,6 @@ namespace Gendarme.Rules.Exceptions {
13036 [FxCopCompatibility ("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")]
13037 public class MissingExceptionConstructorsRule : Rule, ITypeRule {
13038
13039- // non-localizable
13040- private const string Exception = "System.Exception";
13041-
13042 // localizable
13043 private const string MissingConstructor = "Exception is missing '{0} {1}{2}' constructor.";
13044
13045@@ -97,15 +95,15 @@ namespace Gendarme.Rules.Exceptions {
13046 if (!ctor.IsPublic)
13047 return false;
13048
13049- return (ctor.Parameters [0].ParameterType.FullName == "System.String");
13050+ return (ctor.Parameters [0].ParameterType.IsNamed ("System", "String"));
13051 }
13052
13053 private static bool CheckForInnerExceptionConstructor (IMethodSignature ctor)
13054 {
13055 IList<ParameterDefinition> pdc = ctor.Parameters;
13056- string first = pdc [0].ParameterType.FullName;
13057- string last = pdc [pdc.Count - 1].ParameterType.FullName;
13058- return ((first == "System.String") && (last == Exception));
13059+ if (!pdc [0].ParameterType.IsNamed ("System", "String"))
13060+ return false;
13061+ return pdc [pdc.Count - 1].ParameterType.IsNamed ("System", "Exception");
13062 }
13063
13064 private static bool CheckForSerializationConstructor (MethodDefinition ctor)
13065@@ -119,7 +117,7 @@ namespace Gendarme.Rules.Exceptions {
13066 public RuleResult CheckType (TypeDefinition type)
13067 {
13068 // rule apply only to type that inherits from System.Exception
13069- if (!type.Inherits (Exception))
13070+ if (!type.Inherits ("System", "Exception"))
13071 return RuleResult.DoesNotApply;
13072
13073 // rule applies, only Success or Failure from the point on
13074@@ -166,21 +164,24 @@ namespace Gendarme.Rules.Exceptions {
13075 }
13076
13077 if (!empty_ctor) {
13078- string s = String.Format (MissingConstructor, "public", type.Name, "()");
13079+ string s = String.Format (CultureInfo.InvariantCulture, MissingConstructor, "public",
13080+ type.Name, "()");
13081 Runner.Report (type, Severity.High, Confidence.Total, s);
13082 }
13083 if (!string_ctor) {
13084- string s = String.Format (MissingConstructor, "public", type.Name, "(string message)");
13085+ string s = String.Format (CultureInfo.InvariantCulture, MissingConstructor, "public",
13086+ type.Name, "(string message)");
13087 Runner.Report (type, Severity.High, Confidence.Total, s);
13088 }
13089 if (!inner_exception_ctor) {
13090- string s = String.Format (MissingConstructor, "public", type.Name,
13091- "(string message, Exception innerException)");
13092+ string s = String.Format (CultureInfo.InvariantCulture, MissingConstructor, "public",
13093+ type.Name, "(string message, Exception innerException)");
13094 Runner.Report (type, Severity.High, Confidence.Total, s);
13095 }
13096 if (!serialization_ctor) {
13097- string s = String.Format (MissingConstructor, (type.IsSealed) ? "private" : "protected",
13098- type.Name, "(SerializationInfo info, StreamingContext context)");
13099+ string s = String.Format (CultureInfo.InvariantCulture, MissingConstructor,
13100+ (type.IsSealed) ? "private" : "protected", type.Name,
13101+ "(SerializationInfo info, StreamingContext context)");
13102 Runner.Report (type, Severity.High, Confidence.Total, s);
13103 }
13104
13105diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/NewExceptionRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/NewExceptionRule.cs
13106index f2d3f75..22605f2 100644
13107--- a/gendarme/rules/Gendarme.Rules.Exceptions/NewExceptionRule.cs
13108+++ b/gendarme/rules/Gendarme.Rules.Exceptions/NewExceptionRule.cs
13109@@ -46,12 +46,14 @@ namespace Gendarme.Rules.Exceptions {
13110 // if the module does not reference any of these types, don't analyze it
13111 // (unless this is corlib itself since they're defined in it :-)
13112 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
13113- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
13114- e.CurrentModule.HasAnyTypeReference (GetExceptionTypes ());
13115+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
13116+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
13117+ return CheckException (tr);
13118+ }));
13119 };
13120 }
13121
13122- abstract protected string [] GetExceptionTypes ();
13123+ abstract protected bool CheckException (TypeReference type);
13124 abstract protected Severity Severity { get; }
13125
13126 public RuleResult CheckMethod (MethodDefinition method)
13127@@ -69,18 +71,12 @@ namespace Gendarme.Rules.Exceptions {
13128 if (ins.OpCode.Code != Code.Newobj)
13129 continue;
13130
13131- // obtain a reference to constructor
13132- MethodReference ctor = (ins.Operand as MethodReference);
13133+ // obtain a reference to the constructor's type
13134+ TypeReference ctype = (ins.Operand as MethodReference).DeclaringType;
13135
13136- // what type is it?
13137- string name = ctor.DeclaringType.FullName;
13138- foreach (string exception_type in GetExceptionTypes ()) {
13139- if (name == exception_type) {
13140- // report a defect including the offending exception type found
13141- Runner.Report (method, ins, Severity, Confidence.High, name);
13142- break;
13143- }
13144- }
13145+ // report a defect if an offending exception type is found
13146+ if (CheckException (ctype))
13147+ Runner.Report (method, ins, Severity, Confidence.High, ctype.Name);
13148 }
13149
13150 return Runner.CurrentRuleResult;
13151diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/README.md b/gendarme/rules/Gendarme.Rules.Exceptions/README.md
13152new file mode 100644
13153index 0000000..110e852
13154--- /dev/null
13155+++ b/gendarme/rules/Gendarme.Rules.Exceptions/README.md
13156@@ -0,0 +1,9 @@
13157+# Gendarme.Rules.Exceptions Rules
13158+
13159+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Exceptions(git)]] pages.
13160+
13161+
13162+## Feedback
13163+
13164+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
13165+
13166diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Test/DoNotThrowInNonCatchClausesTest.cs b/gendarme/rules/Gendarme.Rules.Exceptions/Test/DoNotThrowInNonCatchClausesTest.cs
13167new file mode 100644
13168index 0000000..9bb6ddd
13169--- /dev/null
13170+++ b/gendarme/rules/Gendarme.Rules.Exceptions/Test/DoNotThrowInNonCatchClausesTest.cs
13171@@ -0,0 +1,136 @@
13172+//
13173+// Unit Tests for DoNotThrowInNonCatchClausesRule
13174+//
13175+// Authors:
13176+// Sebastien Pouliot <sebastien@ximian.com>
13177+//
13178+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
13179+//
13180+// Permission is hereby granted, free of charge, to any person obtaining
13181+// a copy of this software and associated documentation files (the
13182+// "Software"), to deal in the Software without restriction, including
13183+// without limitation the rights to use, copy, modify, merge, publish,
13184+// distribute, sublicense, and/or sell copies of the Software, and to
13185+// permit persons to whom the Software is furnished to do so, subject to
13186+// the following conditions:
13187+//
13188+// The above copyright notice and this permission notice shall be
13189+// included in all copies or substantial portions of the Software.
13190+//
13191+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13192+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13193+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
13194+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
13195+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
13196+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
13197+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13198+//
13199+
13200+using System;
13201+using Gendarme.Rules.Exceptions;
13202+
13203+using NUnit.Framework;
13204+using Test.Rules.Definitions;
13205+using Test.Rules.Fixtures;
13206+
13207+namespace Test.Rules.Exceptions {
13208+
13209+ [TestFixture]
13210+ public class DoNotThrowInNonCatchClausesTest : MethodRuleTestFixture<DoNotThrowInNonCatchClausesRule> {
13211+
13212+ [Test]
13213+ public void DoesNotApply ()
13214+ {
13215+ AssertRuleDoesNotApply (SimpleMethods.ExternalMethod);
13216+ AssertRuleDoesNotApply (SimpleMethods.EmptyMethod);
13217+ }
13218+
13219+ void ThrowInTry ()
13220+ {
13221+ try {
13222+ throw new NotImplementedException ("no luck");
13223+ }
13224+ finally {
13225+ Console.WriteLine ();
13226+ }
13227+ }
13228+
13229+ void ThrowInCatch ()
13230+ {
13231+ try {
13232+ Console.WriteLine ();
13233+ }
13234+ catch (Exception e) {
13235+ throw new NotImplementedException ("no luck", e);
13236+ }
13237+ }
13238+
13239+ // copied from DontDestroyStackTraceTest since CSC compiles the HandlerEnd as past the method offset
13240+ void ThrowCatchThrowNew ()
13241+ {
13242+ try {
13243+ throw new NotImplementedException ();
13244+ }
13245+ catch (Exception) {
13246+ throw new NotImplementedException ();
13247+ }
13248+ }
13249+
13250+ [Test]
13251+ public void Success ()
13252+ {
13253+ AssertRuleSuccess<DoNotThrowInNonCatchClausesTest> ("ThrowInTry");
13254+ AssertRuleSuccess<DoNotThrowInNonCatchClausesTest> ("ThrowInCatch");
13255+ AssertRuleSuccess<DoNotThrowInNonCatchClausesTest> ("ThrowCatchThrowNew");
13256+ }
13257+
13258+ void RethrowInCatch ()
13259+ {
13260+ try {
13261+ Console.WriteLine ();
13262+ }
13263+ catch (Exception) {
13264+ throw; // rethrow in IL which is seen only in catch clauses
13265+ }
13266+ }
13267+
13268+ [Test]
13269+ public void Rethrow ()
13270+ {
13271+ AssertRuleDoesNotApply<DoNotThrowInNonCatchClausesTest> ("RethrowInCatch");
13272+ }
13273+
13274+ void ThrowInFinally ()
13275+ {
13276+ try {
13277+ Console.WriteLine ();
13278+ }
13279+ finally {
13280+ throw new NotImplementedException ("no luck");
13281+ }
13282+ }
13283+
13284+ void ThrowInFinallyToo ()
13285+ {
13286+ try {
13287+ throw new NotImplementedException ("no luck");
13288+ }
13289+ catch (Exception e) {
13290+ throw new NotImplementedException ("no more luck", e);
13291+ }
13292+ finally {
13293+ if (GetType ().IsSealed)
13294+ throw new NotImplementedException ("never any luck");
13295+ else
13296+ throw new NotSupportedException ("stop playing cards");
13297+ }
13298+ }
13299+
13300+ [Test]
13301+ public void Failure ()
13302+ {
13303+ AssertRuleFailure<DoNotThrowInNonCatchClausesTest> ("ThrowInFinally", 1);
13304+ AssertRuleFailure<DoNotThrowInNonCatchClausesTest> ("ThrowInFinallyToo", 2);
13305+ }
13306+ }
13307+}
13308diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Test/InstantiateArgumentExceptionCorrectlyTest.cs b/gendarme/rules/Gendarme.Rules.Exceptions/Test/InstantiateArgumentExceptionCorrectlyTest.cs
13309index 8727b8b..d53501d 100644
13310--- a/gendarme/rules/Gendarme.Rules.Exceptions/Test/InstantiateArgumentExceptionCorrectlyTest.cs
13311+++ b/gendarme/rules/Gendarme.Rules.Exceptions/Test/InstantiateArgumentExceptionCorrectlyTest.cs
13312@@ -777,5 +777,49 @@ namespace Test.Rules.Exceptions {
13313 AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest> ("get_Item");
13314 AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest> ("set_Item");
13315 }
13316+
13317+ public void ArgumentNullExceptionWithBranchInMessageSelectionAndIncorrectParameterName(int parameter)
13318+ {
13319+ throw new ArgumentNullException("asdf", parameter > 0 ? "little parameter " : "big parameter");
13320+ }
13321+
13322+ public void ArgumentOutOfRangeExceptionWithBranchInMessageSelectionAndIncorrectParameterName(int parameter)
13323+ {
13324+ throw new ArgumentOutOfRangeException("asdf", parameter > 0 ? "little parameter " : "big parameter");
13325+ }
13326+
13327+ public void DuplicateWaitObjectExceptionWithBranchInMessageSelectionAndIncorrectParameterName(int parameter)
13328+ {
13329+ throw new DuplicateWaitObjectException("asdf", parameter > 0 ? "little parameter " : "big parameter");
13330+ }
13331+
13332+ public void ArgumentNullExceptionWithBranchInMessageSelectionAndCorrectParameterName(int parameter)
13333+ {
13334+ throw new ArgumentNullException("parameter", parameter > 0 ? "little parameter " : "big parameter");
13335+ }
13336+
13337+ public void ArgumentOutOfRangeExceptionWithBranchInMessageSelectionAndCorrectParameterName(int parameter)
13338+ {
13339+ throw new ArgumentOutOfRangeException("parameter", parameter > 0 ? "little parameter " : "big parameter");
13340+ }
13341+
13342+ public void DuplicateWaitObjectExceptionWithBranchInMessageSelectionAndCorrectParameterName(int parameter)
13343+ {
13344+ throw new DuplicateWaitObjectException("parameter", parameter > 0 ? "little parameter " : "big parameter");
13345+ }
13346+
13347+ [Test]
13348+ public void ArgumentExceptionsWithBranchInMessageSelectionDoesNotThrow()
13349+ {
13350+ AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest>("ArgumentNullExceptionWithBranchInMessageSelectionAndCorrectParameterName");
13351+ AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest>("ArgumentOutOfRangeExceptionWithBranchInMessageSelectionAndCorrectParameterName");
13352+ AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest>("DuplicateWaitObjectExceptionWithBranchInMessageSelectionAndCorrectParameterName");
13353+
13354+ //Ideally the rules below would be AssertRuleFailure - but better to incorrectly pass than to throw an unhandled exception
13355+ // If the handling code is changed a better resolution here may be possible
13356+ AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest>("ArgumentNullExceptionWithBranchInMessageSelectionAndIncorrectParameterName");
13357+ AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest>("ArgumentOutOfRangeExceptionWithBranchInMessageSelectionAndIncorrectParameterName");
13358+ AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest>("DuplicateWaitObjectExceptionWithBranchInMessageSelectionAndIncorrectParameterName");
13359+ }
13360 }
13361 }
13362diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Test/Tests.Rules.Exceptions.csproj b/gendarme/rules/Gendarme.Rules.Exceptions/Test/Tests.Rules.Exceptions.csproj
13363index d37db89..2e31f25 100644
13364--- a/gendarme/rules/Gendarme.Rules.Exceptions/Test/Tests.Rules.Exceptions.csproj
13365+++ b/gendarme/rules/Gendarme.Rules.Exceptions/Test/Tests.Rules.Exceptions.csproj
13366@@ -1,5 +1,5 @@
13367 <?xml version="1.0" encoding="utf-8"?>\r
13368-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
13369+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
13370 <PropertyGroup>\r
13371 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
13372 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
13373@@ -12,9 +12,11 @@
13374 <AssemblyName>Tests.Rules.Exceptions</AssemblyName>\r
13375 <FileUpgradeFlags>\r
13376 </FileUpgradeFlags>\r
13377- <OldToolsVersion>2.0</OldToolsVersion>\r
13378+ <OldToolsVersion>3.5</OldToolsVersion>\r
13379 <UpgradeBackupLocation>\r
13380 </UpgradeBackupLocation>\r
13381+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
13382+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
13383 <PublishUrl>http://localhost/Tests.Rules.Exceptions/</PublishUrl>\r
13384 <Install>true</Install>\r
13385 <InstallFrom>Web</InstallFrom>\r
13386@@ -27,10 +29,9 @@
13387 <MapFileExtensions>true</MapFileExtensions>\r
13388 <ApplicationRevision>0</ApplicationRevision>\r
13389 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
13390- <IsWebBootstrapper>true</IsWebBootstrapper>\r
13391 <UseApplicationTrust>false</UseApplicationTrust>\r
13392 <BootstrapperEnabled>true</BootstrapperEnabled>\r
13393- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
13394+ <TargetFrameworkProfile />\r
13395 </PropertyGroup>\r
13396 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
13397 <DebugSymbols>true</DebugSymbols>\r
13398@@ -40,6 +41,7 @@
13399 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
13400 <ErrorReport>prompt</ErrorReport>\r
13401 <WarningLevel>4</WarningLevel>\r
13402+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
13403 </PropertyGroup>\r
13404 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
13405 <DebugType>pdbonly</DebugType>\r
13406@@ -48,6 +50,7 @@
13407 <DefineConstants>TRACE</DefineConstants>\r
13408 <ErrorReport>prompt</ErrorReport>\r
13409 <WarningLevel>4</WarningLevel>\r
13410+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
13411 </PropertyGroup>\r
13412 <ItemGroup>\r
13413 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
13414@@ -95,14 +98,33 @@
13415 <None Include="ChangeLog" />\r
13416 </ItemGroup>\r
13417 <ItemGroup>\r
13418+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
13419+ <Visible>False</Visible>\r
13420+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
13421+ <Install>false</Install>\r
13422+ </BootstrapperPackage>\r
13423 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
13424 <Visible>False</Visible>\r
13425+ <ProductName>\r
13426+ </ProductName>\r
13427+ <Install>false</Install>\r
13428 </BootstrapperPackage>\r
13429 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
13430 <Visible>False</Visible>\r
13431+ <ProductName>\r
13432+ </ProductName>\r
13433+ <Install>false</Install>\r
13434 </BootstrapperPackage>\r
13435 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
13436 <Visible>False</Visible>\r
13437+ <ProductName>\r
13438+ </ProductName>\r
13439+ <Install>false</Install>\r
13440+ </BootstrapperPackage>\r
13441+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
13442+ <Visible>False</Visible>\r
13443+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
13444+ <Install>false</Install>\r
13445 </BootstrapperPackage>\r
13446 </ItemGroup>\r
13447 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
13448diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/UseObjectDisposedExceptionRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/UseObjectDisposedExceptionRule.cs
13449index fbb1f0f..8636091 100644
13450--- a/gendarme/rules/Gendarme.Rules.Exceptions/UseObjectDisposedExceptionRule.cs
13451+++ b/gendarme/rules/Gendarme.Rules.Exceptions/UseObjectDisposedExceptionRule.cs
13452@@ -150,7 +150,9 @@ namespace Gendarme.Rules.Exceptions {
13453
13454 private void CheckBody (MethodDefinition method)
13455 {
13456- string fullname = method.DeclaringType.FullName;
13457+ TypeReference type = method.DeclaringType;
13458+ string nspace = type.Namespace;
13459+ string name = type.Name;
13460 foreach (Instruction ins in method.Body.Instructions) {
13461 switch (ins.OpCode.Code) {
13462 case Code.Call:
13463@@ -160,7 +162,7 @@ namespace Gendarme.Rules.Exceptions {
13464 MethodDefinition callee = target.Resolve ();
13465 if (callee != null) {
13466 if (!callee.IsPublic && !callee.IsStatic) {
13467- if (callee.DeclaringType.FullName == fullname) {
13468+ if (callee.DeclaringType.IsNamed (nspace, name)) {
13469 Instruction instance = ins.TraceBack (method);
13470 if (instance != null && instance.OpCode.Code == Code.Ldarg_0) {
13471 Log.WriteLine (this, "found non-public this call at {0:X4}", ins.Offset);
13472@@ -187,7 +189,7 @@ namespace Gendarme.Rules.Exceptions {
13473 case Code.Ldflda:
13474 if (!field_access_using_this) {
13475 FieldReference field = (FieldReference) ins.Operand;
13476- if (field.DeclaringType.FullName == fullname) {
13477+ if (field.DeclaringType.IsNamed (nspace, name)) {
13478 Instruction instance = ins.TraceBack (method);
13479 if (instance != null && instance.OpCode.Code == Code.Ldarg_0) {
13480 Log.WriteLine (this, "found field access at {0:X4}", ins.Offset);
13481@@ -200,7 +202,7 @@ namespace Gendarme.Rules.Exceptions {
13482 case Code.Newobj:
13483 if (!creates_exception) {
13484 MethodReference ctor = (MethodReference) ins.Operand;
13485- if (ctor.DeclaringType.FullName == "System.ObjectDisposedException") {
13486+ if (ctor.DeclaringType.IsNamed ("System", "ObjectDisposedException")) {
13487 Log.WriteLine (this, "creates exception at {0:X4}", ins.Offset);
13488 creates_exception = true;
13489 }
13490@@ -220,7 +222,7 @@ namespace Gendarme.Rules.Exceptions {
13491
13492 if (method.IsPublic) {
13493 if (OpCodeEngine.GetBitmask (method).Intersect (CallsAndFields)) {
13494- if (method.DeclaringType.Implements ("System.IDisposable")) {
13495+ if (method.DeclaringType.Implements ("System", "IDisposable")) {
13496 if (AllowedToThrow (method)) {
13497 needs = true;
13498 }
13499diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/DefectsMustBeReportedRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/DefectsMustBeReportedRule.cs
13500index ab02b90..9376fc6 100644
13501--- a/gendarme/rules/Gendarme.Rules.Gendarme/DefectsMustBeReportedRule.cs
13502+++ b/gendarme/rules/Gendarme.Rules.Gendarme/DefectsMustBeReportedRule.cs
13503@@ -75,11 +75,11 @@ namespace Gendarme.Rules.Gendarme {
13504 public class DefectsMustBeReportedRule : GendarmeRule, ITypeRule {
13505 public RuleResult CheckType (TypeDefinition type)
13506 {
13507- if (type.IsAbstract || !type.Implements ("Gendarme.Framework.IRule") || !type.HasMethods)
13508+ if (type.IsAbstract || !type.HasMethods || !type.Implements ("Gendarme.Framework", "IRule"))
13509 return RuleResult.DoesNotApply;
13510
13511 foreach (MethodDefinition method in type.Methods) {
13512- if (!method.HasBody || !OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)) || method.IsConstructor)
13513+ if (method.IsConstructor || !method.HasBody || !OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)))
13514 continue;
13515
13516 foreach (Instruction instruction in method.Body.Instructions) {
13517@@ -87,9 +87,9 @@ namespace Gendarme.Rules.Gendarme {
13518 continue;
13519
13520 MethodReference m = (instruction.Operand as MethodReference);
13521- if (m == null || m.DeclaringType.FullName != "Gendarme.Framework.IRunner")
13522+ if (m == null || (m.Name != "Report"))
13523 continue;
13524- if (m.Name == "Report")
13525+ if (m.DeclaringType.IsNamed ("Gendarme.Framework", "IRunner"))
13526 return RuleResult.Success;
13527 }
13528
13529diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/DoNotThrowExceptionRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/DoNotThrowExceptionRule.cs
13530index 271e793..78ae7a7 100644
13531--- a/gendarme/rules/Gendarme.Rules.Gendarme/DoNotThrowExceptionRule.cs
13532+++ b/gendarme/rules/Gendarme.Rules.Gendarme/DoNotThrowExceptionRule.cs
13533@@ -74,7 +74,7 @@ namespace Gendarme.Rules.Gendarme {
13534
13535 Runner.AnalyzeType += (object sender, RunnerEventArgs e) =>
13536 {
13537- Active = e.CurrentType.Implements ("Gendarme.Framework.IRule");
13538+ Active = e.CurrentType.Implements ("Gendarme.Framework", "IRule");
13539 };
13540 }
13541
13542@@ -89,7 +89,7 @@ namespace Gendarme.Rules.Gendarme {
13543
13544 if (method.IsSetter && method.IsPublic) {
13545 PropertyDefinition property = method.GetPropertyByAccessor ();
13546- if (property != null && property.HasCustomAttributes && property.HasAttribute ("System.ComponentModel.DescriptionAttribute"))
13547+ if (property.HasAttribute ("System.ComponentModel", "DescriptionAttribute"))
13548 return RuleResult.Success;
13549 }
13550
13551@@ -105,7 +105,7 @@ namespace Gendarme.Rules.Gendarme {
13552 continue;
13553
13554 TypeReference type = m.DeclaringType;
13555- if (type.FullName != "System.NotImplementedException" && !type.Inherits ("System.NotImplementedException"))
13556+ if (type.Inherits ("System", "Exception"))
13557 Runner.Report (method, instruction, Severity.Medium, Confidence.High);
13558 }
13559
13560diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/Gendarme.Rules.Gendarme.csproj b/gendarme/rules/Gendarme.Rules.Gendarme/Gendarme.Rules.Gendarme.csproj
13561index 0201472..77396b1 100755
13562--- a/gendarme/rules/Gendarme.Rules.Gendarme/Gendarme.Rules.Gendarme.csproj
13563+++ b/gendarme/rules/Gendarme.Rules.Gendarme/Gendarme.Rules.Gendarme.csproj
13564@@ -1,73 +1,112 @@
13565-<?xml version="1.0" encoding="utf-8"?>
13566-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
13567- <PropertyGroup>
13568- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
13569- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
13570- <ProductVersion>9.0.30729</ProductVersion>
13571- <SchemaVersion>2.0</SchemaVersion>
13572- <ProjectGuid>{619CDBD4-D89E-47E1-9A82-0F194A665D48}</ProjectGuid>
13573- <OutputType>Library</OutputType>
13574- <AppDesignerFolder>Properties</AppDesignerFolder>
13575- <RootNamespace>Gendarme.Rules.Gendarme</RootNamespace>
13576- <AssemblyName>Gendarme.Rules.Gendarme</AssemblyName>
13577- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
13578- <FileAlignment>512</FileAlignment>
13579- </PropertyGroup>
13580- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
13581- <DebugSymbols>true</DebugSymbols>
13582- <DebugType>full</DebugType>
13583- <Optimize>false</Optimize>
13584- <OutputPath>..\..\console\bin\Debug\</OutputPath>
13585- <DefineConstants>DEBUG;TRACE</DefineConstants>
13586- <ErrorReport>prompt</ErrorReport>
13587- <WarningLevel>4</WarningLevel>
13588- <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Gendarme.xml</DocumentationFile>
13589- </PropertyGroup>
13590- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
13591- <DebugType>pdbonly</DebugType>
13592- <Optimize>true</Optimize>
13593- <OutputPath>..\..\console\bin\Release\</OutputPath>
13594- <DefineConstants>TRACE;RELEASE</DefineConstants>
13595- <ErrorReport>prompt</ErrorReport>
13596- <WarningLevel>4</WarningLevel>
13597- <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Gendarme.xml</DocumentationFile>
13598- </PropertyGroup>
13599- <ItemGroup>
13600- <Reference Include="System" />
13601- <Reference Include="System.Core">
13602- <RequiredTargetFramework>3.5</RequiredTargetFramework>
13603- </Reference>
13604- </ItemGroup>
13605- <ItemGroup>
13606- <Compile Include="..\..\AssemblyStaticInfo.cs">
13607- <Link>AssemblyStaticInfo.cs</Link>
13608- </Compile>
13609- <Compile Include="DefectsMustBeReportedRule.cs" />
13610- <Compile Include="DoNotThrowExceptionRule.cs" />
13611- <Compile Include="GendarmeRule.cs" />
13612- <Compile Include="MissingEngineDependencyRule.cs" />
13613- <Compile Include="ReviewAttributesOnRulesRule.cs" />
13614- <Compile Include="UseCorrectSuffixRule.cs" />
13615- </ItemGroup>
13616- <ItemGroup>
13617- <ProjectReference Include="..\..\..\..\cecil\Mono.Cecil.csproj">
13618- <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>
13619- <Name>Mono.Cecil</Name>
13620- </ProjectReference>
13621- <ProjectReference Include="..\..\framework\Gendarme.Framework.csproj">
13622- <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>
13623- <Name>Gendarme.Framework</Name>
13624- </ProjectReference>
13625- </ItemGroup>
13626- <ItemGroup>
13627- <Folder Include="Properties\" />
13628- </ItemGroup>
13629- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
13630+<?xml version="1.0" encoding="utf-8"?>\r
13631+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
13632+ <PropertyGroup>\r
13633+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
13634+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
13635+ <ProductVersion>9.0.30729</ProductVersion>\r
13636+ <SchemaVersion>2.0</SchemaVersion>\r
13637+ <ProjectGuid>{619CDBD4-D89E-47E1-9A82-0F194A665D48}</ProjectGuid>\r
13638+ <OutputType>Library</OutputType>\r
13639+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
13640+ <RootNamespace>Gendarme.Rules.Gendarme</RootNamespace>\r
13641+ <AssemblyName>Gendarme.Rules.Gendarme</AssemblyName>\r
13642+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
13643+ <FileAlignment>512</FileAlignment>\r
13644+ <FileUpgradeFlags>\r
13645+ </FileUpgradeFlags>\r
13646+ <OldToolsVersion>3.5</OldToolsVersion>\r
13647+ <UpgradeBackupLocation />\r
13648+ <PublishUrl>publish\</PublishUrl>\r
13649+ <Install>true</Install>\r
13650+ <InstallFrom>Disk</InstallFrom>\r
13651+ <UpdateEnabled>false</UpdateEnabled>\r
13652+ <UpdateMode>Foreground</UpdateMode>\r
13653+ <UpdateInterval>7</UpdateInterval>\r
13654+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
13655+ <UpdatePeriodically>false</UpdatePeriodically>\r
13656+ <UpdateRequired>false</UpdateRequired>\r
13657+ <MapFileExtensions>true</MapFileExtensions>\r
13658+ <ApplicationRevision>0</ApplicationRevision>\r
13659+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
13660+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
13661+ <UseApplicationTrust>false</UseApplicationTrust>\r
13662+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
13663+ <TargetFrameworkProfile />\r
13664+ </PropertyGroup>\r
13665+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
13666+ <DebugSymbols>true</DebugSymbols>\r
13667+ <DebugType>full</DebugType>\r
13668+ <Optimize>false</Optimize>\r
13669+ <OutputPath>..\..\console\bin\Debug\</OutputPath>\r
13670+ <DefineConstants>DEBUG;TRACE</DefineConstants>\r
13671+ <ErrorReport>prompt</ErrorReport>\r
13672+ <WarningLevel>4</WarningLevel>\r
13673+ <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Gendarme.xml</DocumentationFile>\r
13674+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
13675+ </PropertyGroup>\r
13676+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
13677+ <DebugType>pdbonly</DebugType>\r
13678+ <Optimize>true</Optimize>\r
13679+ <OutputPath>..\..\console\bin\Release\</OutputPath>\r
13680+ <DefineConstants>TRACE;RELEASE</DefineConstants>\r
13681+ <ErrorReport>prompt</ErrorReport>\r
13682+ <WarningLevel>4</WarningLevel>\r
13683+ <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Gendarme.xml</DocumentationFile>\r
13684+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
13685+ </PropertyGroup>\r
13686+ <ItemGroup>\r
13687+ <Reference Include="System" />\r
13688+ <Reference Include="System.Core">\r
13689+ <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
13690+ </Reference>\r
13691+ </ItemGroup>\r
13692+ <ItemGroup>\r
13693+ <Compile Include="..\..\AssemblyStaticInfo.cs">\r
13694+ <Link>AssemblyStaticInfo.cs</Link>\r
13695+ </Compile>\r
13696+ <Compile Include="DefectsMustBeReportedRule.cs" />\r
13697+ <Compile Include="DoNotThrowExceptionRule.cs" />\r
13698+ <Compile Include="GendarmeRule.cs" />\r
13699+ <Compile Include="MissingEngineDependencyRule.cs" />\r
13700+ <Compile Include="ReviewAttributesOnRulesRule.cs" />\r
13701+ <Compile Include="UseCorrectSuffixRule.cs" />\r
13702+ </ItemGroup>\r
13703+ <ItemGroup>\r
13704+ <ProjectReference Include="..\..\..\..\cecil\Mono.Cecil.csproj">\r
13705+ <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
13706+ <Name>Mono.Cecil</Name>\r
13707+ </ProjectReference>\r
13708+ <ProjectReference Include="..\..\framework\Gendarme.Framework.csproj">\r
13709+ <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>\r
13710+ <Name>Gendarme.Framework</Name>\r
13711+ </ProjectReference>\r
13712+ </ItemGroup>\r
13713+ <ItemGroup>\r
13714+ <Folder Include="Properties\" />\r
13715+ </ItemGroup>\r
13716+ <ItemGroup>\r
13717+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
13718+ <Visible>False</Visible>\r
13719+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
13720+ <Install>false</Install>\r
13721+ </BootstrapperPackage>\r
13722+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
13723+ <Visible>False</Visible>\r
13724+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
13725+ <Install>true</Install>\r
13726+ </BootstrapperPackage>\r
13727+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
13728+ <Visible>False</Visible>\r
13729+ <ProductName>Windows Installer 3.1</ProductName>\r
13730+ <Install>true</Install>\r
13731+ </BootstrapperPackage>\r
13732+ </ItemGroup>\r
13733+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
13734 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
13735 Other similar extension points exist, see Microsoft.Common.targets.
13736 <Target Name="BeforeBuild">
13737 </Target>
13738 <Target Name="AfterBuild">
13739 </Target>
13740- -->
13741+ -->\r
13742 </Project>
13743\ No newline at end of file
13744diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/MissingEngineDependencyRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/MissingEngineDependencyRule.cs
13745index 7024d4f..07fb46a 100644
13746--- a/gendarme/rules/Gendarme.Rules.Gendarme/MissingEngineDependencyRule.cs
13747+++ b/gendarme/rules/Gendarme.Rules.Gendarme/MissingEngineDependencyRule.cs
13748@@ -80,12 +80,14 @@ namespace Gendarme.Rules.Gendarme {
13749 "Gendarme.Framework.Engines.NamespaceEngine"
13750 };
13751
13752+ private HashSet<string> declaredEngines = new HashSet<string> ();
13753+
13754 public RuleResult CheckType (TypeDefinition type)
13755 {
13756 if (!type.HasMethods)
13757 return RuleResult.DoesNotApply;
13758
13759- HashSet<string> declaredEngines = GetEngineDependencyValue (type);
13760+ GetEngineDependencyValue (type);
13761
13762 foreach (MethodDefinition method in type.Methods) {
13763 if (!method.HasBody || !OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)))
13764@@ -95,8 +97,14 @@ namespace Gendarme.Rules.Gendarme {
13765 MethodReference m = (instruction.Operand as MethodReference);
13766 if (m == null)
13767 continue;
13768- string declaringType = m.DeclaringType.FullName;
13769- if (!engines.Contains (declaringType) || declaredEngines.Contains(declaringType))
13770+
13771+ TypeReference dtype = m.DeclaringType;
13772+ // short-cut to avoid FullName - will work as long as all Engines comes from the same namespace (otherwise remove it)
13773+ if (dtype.Namespace != "Gendarme.Framework.Engines")
13774+ continue;
13775+
13776+ string declaringType = dtype.GetFullName ();
13777+ if (!engines.Contains (declaringType) || declaredEngines.Contains (declaringType))
13778 continue;
13779 Runner.Report (method, instruction, Severity.High, Confidence.High,
13780 "An engine " + declaringType + " is being used without type being subscribed to it with EngineDependency attribute.");
13781@@ -107,27 +115,28 @@ namespace Gendarme.Rules.Gendarme {
13782 return Runner.CurrentRuleResult;
13783 }
13784
13785- private HashSet<string> GetEngineDependencyValue (TypeDefinition type)
13786+ private void GetEngineDependencyValue (TypeDefinition type)
13787 {
13788- HashSet<string> retval = new HashSet<string> ();
13789+ declaredEngines.Clear ();
13790 TypeDefinition td = type;
13791- while (retval.Count < engines.Count) {
13792+ while (declaredEngines.Count < engines.Count) {
13793 if (td.HasCustomAttributes)
13794 foreach (CustomAttribute attribute in td.CustomAttributes) {
13795 if (!attribute.HasConstructorArguments ||
13796- attribute.AttributeType.FullName != "Gendarme.Framework.EngineDependencyAttribute")
13797+ !attribute.AttributeType.IsNamed ("Gendarme.Framework", "EngineDependencyAttribute"))
13798 continue;
13799- // ToString for both constuctors (Type and String) will return the type name we need
13800- retval.Add (attribute.ConstructorArguments [0].Value.ToString ());
13801+
13802+ object value = attribute.ConstructorArguments [0].Value;
13803+ MemberReference mr = (value as MemberReference);
13804+ declaredEngines.Add (mr == null ? value.ToString () : mr.GetFullName ());
13805 }
13806 if (td.BaseType == null)
13807 break;
13808- TypeDefinition baseType = td.BaseType.Resolve();
13809+ TypeDefinition baseType = td.BaseType.Resolve ();
13810 if (baseType == null)
13811 break;
13812 td = baseType;
13813 }
13814- return retval;
13815 }
13816 }
13817 }
13818diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/README.md b/gendarme/rules/Gendarme.Rules.Gendarme/README.md
13819new file mode 100644
13820index 0000000..fe4ec4e
13821--- /dev/null
13822+++ b/gendarme/rules/Gendarme.Rules.Gendarme/README.md
13823@@ -0,0 +1,9 @@
13824+# Gendarme.Rules.Gendarme Rules
13825+
13826+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Gendarme(git)]] pages.
13827+
13828+
13829+## Feedback
13830+
13831+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
13832+
13833diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/ReviewAttributesOnRulesRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/ReviewAttributesOnRulesRule.cs
13834index 7bb8b35..3a15245 100644
13835--- a/gendarme/rules/Gendarme.Rules.Gendarme/ReviewAttributesOnRulesRule.cs
13836+++ b/gendarme/rules/Gendarme.Rules.Gendarme/ReviewAttributesOnRulesRule.cs
13837@@ -122,10 +122,14 @@ namespace Gendarme.Rules.Gendarme {
13838 while (!foundSolution || !foundProblem) {
13839 if (td.HasCustomAttributes)
13840 foreach (CustomAttribute attribute in td.CustomAttributes) {
13841- var attributeTypeName = attribute.AttributeType.FullName;
13842- if (attributeTypeName == "Gendarme.Framework.SolutionAttribute")
13843+ TypeReference atype = attribute.AttributeType;
13844+ if (atype.Namespace != "Gendarme.Framework")
13845+ continue;
13846+
13847+ string name = atype.Name;
13848+ if (name == "SolutionAttribute")
13849 foundSolution = true;
13850- if (attributeTypeName == "Gendarme.Framework.ProblemAttribute")
13851+ else if (name == "ProblemAttribute")
13852 foundProblem = true;
13853 }
13854
13855@@ -149,19 +153,19 @@ namespace Gendarme.Rules.Gendarme {
13856 return;
13857
13858 foreach (CustomAttribute attribute in provider.CustomAttributes) {
13859- var attributeTypeName = attribute.AttributeType.FullName;
13860+ var attributeTypeName = attribute.AttributeType.GetFullName ();
13861 Action<CustomAttribute, ICustomAttributeProvider> f;
13862- if (attributes.TryGetValue(attributeTypeName, out f))
13863+ if (attributes.TryGetValue (attributeTypeName, out f))
13864 f (attribute, provider);
13865 }
13866 }
13867
13868 private bool IsRule (TypeReference type)
13869 {
13870- var typeName = type.FullName;
13871+ var typeName = type.GetFullName ();
13872 bool result;
13873 if (!typeIsRule.TryGetValue (typeName, out result)) {
13874- result = type.Implements ("Gendarme.Framework.IRule");
13875+ result = type.Implements ("Gendarme.Framework", "IRule");
13876 typeIsRule [typeName] = result;
13877 }
13878 return result;
13879@@ -182,7 +186,7 @@ namespace Gendarme.Rules.Gendarme {
13880 // check if second argument has correct format
13881 if (!attribute.HasConstructorArguments)
13882 return;
13883- var attributeTypeName = attribute.AttributeType.FullName;
13884+ var attributeTypeName = attribute.AttributeType.GetFullName ();
13885 var argumentValue = attribute.ConstructorArguments [1].Value.ToString ();
13886 var length = argumentValue.Length;
13887 if (!((length == 6 || (length > 8 && argumentValue [6] == ':')) &&
13888@@ -199,7 +203,7 @@ namespace Gendarme.Rules.Gendarme {
13889 private void CheckEngineDependencyAttribute (CustomAttribute attribute, ICustomAttributeProvider provider)
13890 {
13891 TypeDefinition td = (provider as TypeDefinition);
13892- if (td == null || !(IsRule (td) || td.Implements ("Gendarme.Framework.IRunner")))
13893+ if (td == null || !(IsRule (td) || td.Implements ("Gendarme.Framework", "IRunner")))
13894 Runner.Report (td, Severity.Medium, Confidence.High, "[EngineDependency] can only be used on rules and runners");
13895
13896 CheckIfStringArgumentsAreNotNullOrEmpty (attribute, provider);
13897@@ -209,9 +213,9 @@ namespace Gendarme.Rules.Gendarme {
13898 var argument = attribute.ConstructorArguments [0];
13899
13900 // if possible, check if argument type implements IEngine
13901- if (argument.Type.FullName == "System.Type") {
13902+ if (argument.Type.IsNamed ("System", "Type")) {
13903 TypeReference tr = (argument.Value as TypeReference);
13904- if (tr == null || !tr.Inherits ("Gendarme.Framework.Engine")) // IEngine does not exist yet
13905+ if (tr == null || !tr.Inherits ("Gendarme.Framework", "Engine")) // IEngine does not exist yet
13906 Runner.Report (provider, Severity.Medium, Confidence.High,
13907 "EngineDependency attribute argument should implement IEngine interface");
13908
13909@@ -229,7 +233,7 @@ namespace Gendarme.Rules.Gendarme {
13910 TypeDefinition td = (provider as TypeDefinition);
13911 if (td == null || !IsRule (td))
13912 Runner.Report (td, Severity.Medium, Confidence.High,
13913- attribute.AttributeType.FullName + " can be used on rules only");
13914+ attribute.AttributeType.GetFullName () + " can be used on rules only");
13915 }
13916
13917 private void CheckIfAttributeUsedOnRulesProperty (ICustomAttribute attribute, ICustomAttributeProvider provider)
13918@@ -238,7 +242,7 @@ namespace Gendarme.Rules.Gendarme {
13919 if (property == null || !IsRule (property.DeclaringType) ||
13920 !property.GetMethod.IsPublic || !property.SetMethod.IsPublic)
13921 Runner.Report (provider, Severity.High, Confidence.High,
13922- attribute.AttributeType.FullName + " should be used only on rules' public properties");
13923+ attribute.AttributeType.GetFullName () + " should be used only on rules' public properties");
13924 }
13925
13926 // returns true when all arguments are fine, false otherwise
13927@@ -247,11 +251,11 @@ namespace Gendarme.Rules.Gendarme {
13928 if (!attribute.HasConstructorArguments)
13929 return true;
13930 foreach (CustomAttributeArgument argument in attribute.ConstructorArguments) {
13931- if (argument.Type.FullName != "System.String")
13932+ if (!argument.Type.IsNamed ("System", "String"))
13933 continue;
13934 if (String.IsNullOrEmpty ((string) argument.Value)) {
13935 Runner.Report (provider, Severity.Medium, Confidence.High,
13936- attribute.AttributeType.FullName + " argument cannot be null or empty");
13937+ attribute.AttributeType.GetFullName () + " argument cannot be null or empty");
13938 return false;
13939 }
13940 }
13941diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/Test/Tests.Rules.Gendarme.csproj b/gendarme/rules/Gendarme.Rules.Gendarme/Test/Tests.Rules.Gendarme.csproj
13942index fd9873f..877d2b7 100755
13943--- a/gendarme/rules/Gendarme.Rules.Gendarme/Test/Tests.Rules.Gendarme.csproj
13944+++ b/gendarme/rules/Gendarme.Rules.Gendarme/Test/Tests.Rules.Gendarme.csproj
13945@@ -1,79 +1,118 @@
13946-<?xml version="1.0" encoding="utf-8"?>
13947-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
13948- <PropertyGroup>
13949- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
13950- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
13951- <ProductVersion>9.0.30729</ProductVersion>
13952- <SchemaVersion>2.0</SchemaVersion>
13953- <ProjectGuid>{C329FF89-4C07-4D72-AF5B-70B10670CB36}</ProjectGuid>
13954- <OutputType>Library</OutputType>
13955- <AppDesignerFolder>Properties</AppDesignerFolder>
13956- <RootNamespace>Tests.Rules.Gendarme</RootNamespace>
13957- <AssemblyName>Tests.Rules.Gendarme</AssemblyName>
13958- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
13959- <FileAlignment>512</FileAlignment>
13960- </PropertyGroup>
13961- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
13962- <DebugSymbols>true</DebugSymbols>
13963- <DebugType>full</DebugType>
13964- <Optimize>false</Optimize>
13965- <OutputPath>bin\Debug\</OutputPath>
13966- <DefineConstants>DEBUG;TRACE</DefineConstants>
13967- <ErrorReport>prompt</ErrorReport>
13968- <WarningLevel>4</WarningLevel>
13969- </PropertyGroup>
13970- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
13971- <DebugType>pdbonly</DebugType>
13972- <Optimize>true</Optimize>
13973- <OutputPath>bin\Release\</OutputPath>
13974- <DefineConstants>TRACE</DefineConstants>
13975- <ErrorReport>prompt</ErrorReport>
13976- <WarningLevel>4</WarningLevel>
13977- </PropertyGroup>
13978- <ItemGroup>
13979- <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
13980- <SpecificVersion>False</SpecificVersion>
13981- <HintPath>..\..\..\..\..\cecil\Test\libs\nunit-2.4.8\nunit.framework.dll</HintPath>
13982- </Reference>
13983- <Reference Include="System" />
13984- <Reference Include="System.Core">
13985- <RequiredTargetFramework>3.5</RequiredTargetFramework>
13986- </Reference>
13987- </ItemGroup>
13988- <ItemGroup>
13989- <Compile Include="DefectsMustBeReportedTest.cs" />
13990- <Compile Include="DoNotThrowExceptionTest.cs" />
13991- <Compile Include="MissingEngineDependencyTest.cs" />
13992- <Compile Include="ReviewAttributesOnRulesTest.cs" />
13993- <Compile Include="UseCorrectSuffixTest.cs" />
13994- </ItemGroup>
13995- <ItemGroup>
13996- <ProjectReference Include="..\..\..\..\..\cecil\Mono.Cecil.csproj">
13997- <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>
13998- <Name>Mono.Cecil</Name>
13999- </ProjectReference>
14000- <ProjectReference Include="..\..\..\framework\Gendarme.Framework.csproj">
14001- <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>
14002- <Name>Gendarme.Framework</Name>
14003- </ProjectReference>
14004- <ProjectReference Include="..\..\Test.Rules\Test.Rules.csproj">
14005- <Project>{069148AF-86AB-4EE3-BFB9-429AE722461F}</Project>
14006- <Name>Test.Rules</Name>
14007- </ProjectReference>
14008- <ProjectReference Include="..\Gendarme.Rules.Gendarme.csproj">
14009- <Project>{619CDBD4-D89E-47E1-9A82-0F194A665D48}</Project>
14010- <Name>Gendarme.Rules.Gendarme</Name>
14011- </ProjectReference>
14012- </ItemGroup>
14013- <ItemGroup>
14014- <Folder Include="Properties\" />
14015- </ItemGroup>
14016- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
14017+<?xml version="1.0" encoding="utf-8"?>\r
14018+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
14019+ <PropertyGroup>\r
14020+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
14021+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
14022+ <ProductVersion>9.0.30729</ProductVersion>\r
14023+ <SchemaVersion>2.0</SchemaVersion>\r
14024+ <ProjectGuid>{C329FF89-4C07-4D72-AF5B-70B10670CB36}</ProjectGuid>\r
14025+ <OutputType>Library</OutputType>\r
14026+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
14027+ <RootNamespace>Tests.Rules.Gendarme</RootNamespace>\r
14028+ <AssemblyName>Tests.Rules.Gendarme</AssemblyName>\r
14029+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
14030+ <FileAlignment>512</FileAlignment>\r
14031+ <FileUpgradeFlags>\r
14032+ </FileUpgradeFlags>\r
14033+ <OldToolsVersion>3.5</OldToolsVersion>\r
14034+ <UpgradeBackupLocation />\r
14035+ <PublishUrl>publish\</PublishUrl>\r
14036+ <Install>true</Install>\r
14037+ <InstallFrom>Disk</InstallFrom>\r
14038+ <UpdateEnabled>false</UpdateEnabled>\r
14039+ <UpdateMode>Foreground</UpdateMode>\r
14040+ <UpdateInterval>7</UpdateInterval>\r
14041+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
14042+ <UpdatePeriodically>false</UpdatePeriodically>\r
14043+ <UpdateRequired>false</UpdateRequired>\r
14044+ <MapFileExtensions>true</MapFileExtensions>\r
14045+ <ApplicationRevision>0</ApplicationRevision>\r
14046+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
14047+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
14048+ <UseApplicationTrust>false</UseApplicationTrust>\r
14049+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
14050+ <TargetFrameworkProfile />\r
14051+ </PropertyGroup>\r
14052+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
14053+ <DebugSymbols>true</DebugSymbols>\r
14054+ <DebugType>full</DebugType>\r
14055+ <Optimize>false</Optimize>\r
14056+ <OutputPath>bin\Debug\</OutputPath>\r
14057+ <DefineConstants>DEBUG;TRACE</DefineConstants>\r
14058+ <ErrorReport>prompt</ErrorReport>\r
14059+ <WarningLevel>4</WarningLevel>\r
14060+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
14061+ </PropertyGroup>\r
14062+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
14063+ <DebugType>pdbonly</DebugType>\r
14064+ <Optimize>true</Optimize>\r
14065+ <OutputPath>bin\Release\</OutputPath>\r
14066+ <DefineConstants>TRACE</DefineConstants>\r
14067+ <ErrorReport>prompt</ErrorReport>\r
14068+ <WarningLevel>4</WarningLevel>\r
14069+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
14070+ </PropertyGroup>\r
14071+ <ItemGroup>\r
14072+ <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
14073+ <SpecificVersion>False</SpecificVersion>\r
14074+ <HintPath>..\..\..\..\..\cecil\Test\libs\nunit-2.4.8\nunit.framework.dll</HintPath>\r
14075+ </Reference>\r
14076+ <Reference Include="System" />\r
14077+ <Reference Include="System.Core">\r
14078+ <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
14079+ </Reference>\r
14080+ </ItemGroup>\r
14081+ <ItemGroup>\r
14082+ <Compile Include="DefectsMustBeReportedTest.cs" />\r
14083+ <Compile Include="DoNotThrowExceptionTest.cs" />\r
14084+ <Compile Include="MissingEngineDependencyTest.cs" />\r
14085+ <Compile Include="ReviewAttributesOnRulesTest.cs" />\r
14086+ <Compile Include="UseCorrectSuffixTest.cs" />\r
14087+ </ItemGroup>\r
14088+ <ItemGroup>\r
14089+ <ProjectReference Include="..\..\..\..\..\cecil\Mono.Cecil.csproj">\r
14090+ <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
14091+ <Name>Mono.Cecil</Name>\r
14092+ </ProjectReference>\r
14093+ <ProjectReference Include="..\..\..\framework\Gendarme.Framework.csproj">\r
14094+ <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>\r
14095+ <Name>Gendarme.Framework</Name>\r
14096+ </ProjectReference>\r
14097+ <ProjectReference Include="..\..\Test.Rules\Test.Rules.csproj">\r
14098+ <Project>{069148AF-86AB-4EE3-BFB9-429AE722461F}</Project>\r
14099+ <Name>Test.Rules</Name>\r
14100+ </ProjectReference>\r
14101+ <ProjectReference Include="..\Gendarme.Rules.Gendarme.csproj">\r
14102+ <Project>{619CDBD4-D89E-47E1-9A82-0F194A665D48}</Project>\r
14103+ <Name>Gendarme.Rules.Gendarme</Name>\r
14104+ </ProjectReference>\r
14105+ </ItemGroup>\r
14106+ <ItemGroup>\r
14107+ <Folder Include="Properties\" />\r
14108+ </ItemGroup>\r
14109+ <ItemGroup>\r
14110+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
14111+ <Visible>False</Visible>\r
14112+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
14113+ <Install>false</Install>\r
14114+ </BootstrapperPackage>\r
14115+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
14116+ <Visible>False</Visible>\r
14117+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
14118+ <Install>true</Install>\r
14119+ </BootstrapperPackage>\r
14120+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
14121+ <Visible>False</Visible>\r
14122+ <ProductName>Windows Installer 3.1</ProductName>\r
14123+ <Install>true</Install>\r
14124+ </BootstrapperPackage>\r
14125+ </ItemGroup>\r
14126+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
14127 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
14128 Other similar extension points exist, see Microsoft.Common.targets.
14129 <Target Name="BeforeBuild">
14130 </Target>
14131 <Target Name="AfterBuild">
14132 </Target>
14133- -->
14134+ -->\r
14135 </Project>
14136\ No newline at end of file
14137diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/UseCorrectSuffixRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/UseCorrectSuffixRule.cs
14138index 18da8c3..5c4bf7d 100644
14139--- a/gendarme/rules/Gendarme.Rules.Gendarme/UseCorrectSuffixRule.cs
14140+++ b/gendarme/rules/Gendarme.Rules.Gendarme/UseCorrectSuffixRule.cs
14141@@ -71,7 +71,7 @@ namespace Gendarme.Rules.Gendarme {
14142 public RuleResult CheckType (TypeDefinition type)
14143 {
14144 bool endsWithRule = type.Name.EndsWith ("Rule", StringComparison.Ordinal);
14145- bool implementsIRule = type.Implements ("Gendarme.Framework.IRule");
14146+ bool implementsIRule = type.Implements ("Gendarme.Framework", "IRule");
14147
14148 if (implementsIRule && !endsWithRule)
14149 Runner.Report (type, Severity.Medium, Confidence.High, "Type implements IRule but does not end with the 'Rule'");
14150diff --git a/gendarme/rules/Gendarme.Rules.Globalization/AvoidUnusedInternalResourceRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/AvoidUnusedInternalResourceRule.cs
14151index 937be0b..b29cbdc 100644
14152--- a/gendarme/rules/Gendarme.Rules.Globalization/AvoidUnusedInternalResourceRule.cs
14153+++ b/gendarme/rules/Gendarme.Rules.Globalization/AvoidUnusedInternalResourceRule.cs
14154@@ -44,12 +44,6 @@ namespace Gendarme.Rules.Globalization {
14155 [Solution ("Remove the unused resource or add code to call it.")]
14156 public class AvoidUnusedInternalResourceRule : Rule, IMethodRule {
14157
14158- private static readonly string [] resXAttributes = {
14159- "System.CodeDom.Compiler.GeneratedCodeAttribute",
14160- "System.Diagnostics.DebuggerNonUserCodeAttribute",
14161- "System.Runtime.CompilerServices.CompilerGeneratedAttribute"
14162- };
14163-
14164 static private bool Applicable (MethodDefinition method)
14165 {
14166 // only internal resources
14167@@ -71,11 +65,14 @@ namespace Gendarme.Rules.Globalization {
14168 if (!typeDefinition.HasCustomAttributes)
14169 return false;
14170
14171- var attributes = typeDefinition.CustomAttributes;
14172- if (!resXAttributes.All (a => attributes.ContainsType (a)))
14173- return false;
14174+ if (typeDefinition.HasAttribute ("System.CodeDom.Compiler", "GeneratedCodeAttribute"))
14175+ return true;
14176+ if (typeDefinition.HasAttribute ("System.Diagnostics", "DebuggerNonUserCodeAttribute"))
14177+ return true;
14178+ if (typeDefinition.HasAttribute ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute"))
14179+ return true;
14180
14181- return true;
14182+ return false;
14183 }
14184
14185 public RuleResult CheckMethod (MethodDefinition method)
14186@@ -167,7 +164,7 @@ namespace Gendarme.Rules.Globalization {
14187 continue;
14188
14189 TypeReference type = mr.DeclaringType;
14190- if (!(type is ArrayType)) {
14191+ if (!type.IsArray) {
14192 // if (type.GetElementType ().HasGenericParameters)
14193 // the simpler ^^^ does not work under Mono but works on MS
14194 type = type.Resolve ();
14195diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Gendarme.Rules.Globalization.csproj b/gendarme/rules/Gendarme.Rules.Globalization/Gendarme.Rules.Globalization.csproj
14196index 55a74d3..f99c3b8 100644
14197--- a/gendarme/rules/Gendarme.Rules.Globalization/Gendarme.Rules.Globalization.csproj
14198+++ b/gendarme/rules/Gendarme.Rules.Globalization/Gendarme.Rules.Globalization.csproj
14199@@ -1,5 +1,5 @@
14200 <?xml version="1.0" encoding="utf-8"?>\r
14201-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
14202+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
14203 <PropertyGroup>\r
14204 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
14205 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
14206@@ -10,8 +10,28 @@
14207 <AppDesignerFolder>Properties</AppDesignerFolder>\r
14208 <RootNamespace>Gendarme.Rules.Globalization</RootNamespace>\r
14209 <AssemblyName>Gendarme.Rules.Globalization</AssemblyName>\r
14210- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
14211+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
14212 <FileAlignment>512</FileAlignment>\r
14213+ <FileUpgradeFlags>\r
14214+ </FileUpgradeFlags>\r
14215+ <OldToolsVersion>3.5</OldToolsVersion>\r
14216+ <UpgradeBackupLocation />\r
14217+ <PublishUrl>publish\</PublishUrl>\r
14218+ <Install>true</Install>\r
14219+ <InstallFrom>Disk</InstallFrom>\r
14220+ <UpdateEnabled>false</UpdateEnabled>\r
14221+ <UpdateMode>Foreground</UpdateMode>\r
14222+ <UpdateInterval>7</UpdateInterval>\r
14223+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
14224+ <UpdatePeriodically>false</UpdatePeriodically>\r
14225+ <UpdateRequired>false</UpdateRequired>\r
14226+ <MapFileExtensions>true</MapFileExtensions>\r
14227+ <ApplicationRevision>0</ApplicationRevision>\r
14228+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
14229+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
14230+ <UseApplicationTrust>false</UseApplicationTrust>\r
14231+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
14232+ <TargetFrameworkProfile />\r
14233 </PropertyGroup>\r
14234 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
14235 <DebugSymbols>true</DebugSymbols>\r
14236@@ -22,6 +42,7 @@
14237 <ErrorReport>prompt</ErrorReport>\r
14238 <WarningLevel>4</WarningLevel>\r
14239 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Globalization.xml</DocumentationFile>\r
14240+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
14241 </PropertyGroup>\r
14242 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
14243 <DebugType>pdbonly</DebugType>\r
14244@@ -31,6 +52,7 @@
14245 <ErrorReport>prompt</ErrorReport>\r
14246 <WarningLevel>4</WarningLevel>\r
14247 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Globalization.xml</DocumentationFile>\r
14248+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
14249 </PropertyGroup>\r
14250 <ItemGroup>\r
14251 <Reference Include="System" />\r
14252@@ -58,6 +80,23 @@
14253 <ItemGroup>\r
14254 <Folder Include="Properties\" />\r
14255 </ItemGroup>\r
14256+ <ItemGroup>\r
14257+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
14258+ <Visible>False</Visible>\r
14259+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
14260+ <Install>false</Install>\r
14261+ </BootstrapperPackage>\r
14262+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
14263+ <Visible>False</Visible>\r
14264+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
14265+ <Install>true</Install>\r
14266+ </BootstrapperPackage>\r
14267+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
14268+ <Visible>False</Visible>\r
14269+ <ProductName>Windows Installer 3.1</ProductName>\r
14270+ <Install>true</Install>\r
14271+ </BootstrapperPackage>\r
14272+ </ItemGroup>\r
14273 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
14274 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
14275 Other similar extension points exist, see Microsoft.Common.targets.\r
14276diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Makefile.am b/gendarme/rules/Gendarme.Rules.Globalization/Makefile.am
14277index 18c47d0..d1c1daa 100644
14278--- a/gendarme/rules/Gendarme.Rules.Globalization/Makefile.am
14279+++ b/gendarme/rules/Gendarme.Rules.Globalization/Makefile.am
14280@@ -2,6 +2,9 @@ include ../common.make
14281
14282 rules_sources = \
14283 AvoidUnusedInternalResourceRule.cs \
14284+ PreferIFormatProviderOverrideRule.cs \
14285+ PreferOverrideBaseRule.cs \
14286+ PreferStringComparisonOverrideRule.cs \
14287 SatelliteResourceMismatchRule.cs
14288
14289 EXTRA_TESTS_OPTIONS += -r:System.Drawing -d:DEBUG -resource:Test/Resource.resources -resource:Test/InternalResource.resources \
14290@@ -50,6 +53,8 @@ EXTRA_TESTS_DEPS = Test/Resource.resources Test/InternalResource.resources Test/
14291
14292 tests_sources = \
14293 AvoidUnusedInternalResourceTest.cs \
14294+ PreferIFormatProviderOverrideTest.cs \
14295+ PreferStringComparisonOverrideTest.cs \
14296 SatelliteResourceMismatchTest.cs \
14297 Resource.Designer.cs \
14298 InternalResource.Designer.cs \
14299diff --git a/gendarme/rules/Gendarme.Rules.Globalization/PreferIFormatProviderOverrideRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/PreferIFormatProviderOverrideRule.cs
14300new file mode 100644
14301index 0000000..6a63c4f
14302--- /dev/null
14303+++ b/gendarme/rules/Gendarme.Rules.Globalization/PreferIFormatProviderOverrideRule.cs
14304@@ -0,0 +1,111 @@
14305+//
14306+// Gendarme.Rules.Globalization.PreferIFormatProviderOverrideRule
14307+//
14308+// Authors:
14309+// Sebastien Pouliot <sebastien@ximian.com>
14310+//
14311+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
14312+//
14313+// Permission is hereby granted, free of charge, to any person obtaining
14314+// a copy of this software and associated documentation files (the
14315+// "Software"), to deal in the Software without restriction, including
14316+// without limitation the rights to use, copy, modify, merge, publish,
14317+// distribute, sublicense, and/or sell copies of the Software, and to
14318+// permit persons to whom the Software is furnished to do so, subject to
14319+// the following conditions:
14320+//
14321+// The above copyright notice and this permission notice shall be
14322+// included in all copies or substantial portions of the Software.
14323+//
14324+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14325+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14326+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14327+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
14328+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
14329+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
14330+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14331+//
14332+
14333+using System;
14334+using System.Globalization;
14335+
14336+using Mono.Cecil;
14337+using Mono.Cecil.Cil;
14338+using Gendarme.Framework;
14339+using Gendarme.Framework.Rocks;
14340+
14341+namespace Gendarme.Rules.Globalization {
14342+
14343+ /// <summary>
14344+ /// This rule detects calls to method that could be changed to call an <c>override</c> accepting an
14345+ /// extra <c>System.IFormatProvider</c> or <c>System.Globalization.CultureInfo</c> parameter (the
14346+ /// later implements <c>System.IFormatProvider</c>).
14347+ /// Generally data displayed to the end user should be using
14348+ /// <c>System.Globalization.CultureInfo.CurrentCulture</c> while other data (e.g. used internally,
14349+ /// stored in files/databases) should use <c>System.Globalization.CultureInfo.InvariantCulture</c>.
14350+ /// The rule will ignore the following special methods:
14351+ /// <list>
14352+ /// <item><c>System.Activator.CreateInstance</c></item>
14353+ /// <item><c>System.Resources.ResourceManager.GetObject</c></item>
14354+ /// <item><c>System.Resources.ResourceManager.GetString</c></item>
14355+ /// </list>
14356+ /// </summary>
14357+ /// <example>
14358+ /// Bad example:
14359+ /// <code>
14360+ /// public bool Confirm (double amount)
14361+ /// {
14362+ /// string msg = String.Format ("Accept payment of {0} ?", amount);
14363+ /// Transaction.Log ("{0} {1}", DateTime.Now, amount);
14364+ /// return Prompt (msg);
14365+ /// }
14366+ /// </code>
14367+ /// </example>
14368+ /// <example>
14369+ /// Good example:
14370+ /// <code>
14371+ /// public bool Confirm (double amount)
14372+ /// {
14373+ /// string msg = String.Format (CultureInfo.CurrentCulture, "Accept payment of {0} ?", amount);
14374+ /// Transaction.Log (CultureInfo.InvariantCulture, "{0} {1}", DateTime.Now, amount);
14375+ /// return Prompt (msg);
14376+ /// }
14377+ /// </code>
14378+ /// </example>
14379+ [Problem ("A call is made to a method for which an override, accepting an extra IFormatProvider or CultureInfo, is available")]
14380+ [Solution ("Specify how the string should be compared by adding the right IFormatProvider/CultureInfo value to the call")]
14381+ [FxCopCompatibility ("Microsoft.Globalization", "CA1304:SpecifyCultureInfo")]
14382+ [FxCopCompatibility ("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
14383+ public class PreferIFormatProviderOverrideRule : PreferOverrideBaseRule {
14384+
14385+ protected override bool CheckFirstParameter
14386+ {
14387+ get { return true; }
14388+ }
14389+
14390+ protected override bool IsPrefered (TypeReference type)
14391+ {
14392+ return (type.IsNamed ("System", "IFormatProvider") || type.IsNamed ("System.Globalization", "CultureInfo"));
14393+ }
14394+
14395+ protected override bool IsSpecialCase (MethodReference method)
14396+ {
14397+ if ((method == null) || method.IsNamed ("System", "Activator", "CreateInstance"))
14398+ return true;
14399+
14400+ TypeReference type = method.DeclaringType;
14401+ if (!type.IsNamed ("System.Resources", "ResourceManager"))
14402+ return false;
14403+
14404+ string name = method.Name;
14405+ return (name == "GetObject" || name == "GetString");
14406+ }
14407+
14408+ protected override void Report (MethodDefinition method, Instruction instruction, MethodReference prefered)
14409+ {
14410+ string msg = String.Format (CultureInfo.InvariantCulture,
14411+ "Consider using the perfered '{0}' override.", prefered.GetFullName ());
14412+ Runner.Report (method, instruction, Severity.Medium, Confidence.High, msg);
14413+ }
14414+ }
14415+}
14416diff --git a/gendarme/rules/Gendarme.Rules.Globalization/PreferOverrideBaseRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/PreferOverrideBaseRule.cs
14417new file mode 100644
14418index 0000000..020e0e4
14419--- /dev/null
14420+++ b/gendarme/rules/Gendarme.Rules.Globalization/PreferOverrideBaseRule.cs
14421@@ -0,0 +1,170 @@
14422+//
14423+// Gendarme.Rules.Globalization.PreferOverrideBaseRule
14424+//
14425+// Authors:
14426+// Sebastien Pouliot <sebastien@ximian.com>
14427+//
14428+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
14429+//
14430+// Permission is hereby granted, free of charge, to any person obtaining
14431+// a copy of this software and associated documentation files (the
14432+// "Software"), to deal in the Software without restriction, including
14433+// without limitation the rights to use, copy, modify, merge, publish,
14434+// distribute, sublicense, and/or sell copies of the Software, and to
14435+// permit persons to whom the Software is furnished to do so, subject to
14436+// the following conditions:
14437+//
14438+// The above copyright notice and this permission notice shall be
14439+// included in all copies or substantial portions of the Software.
14440+//
14441+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14442+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14443+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14444+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
14445+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
14446+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
14447+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14448+//
14449+
14450+using System;
14451+using System.Collections.Generic;
14452+
14453+using Mono.Cecil;
14454+using Mono.Cecil.Cil;
14455+using Mono.Collections.Generic;
14456+
14457+using Gendarme.Framework;
14458+using Gendarme.Framework.Engines;
14459+using Gendarme.Framework.Helpers;
14460+using Gendarme.Framework.Rocks;
14461+
14462+namespace Gendarme.Rules.Globalization {
14463+
14464+ [EngineDependency (typeof (OpCodeEngine))]
14465+ public abstract class PreferOverrideBaseRule : Rule, IMethodRule {
14466+
14467+ protected virtual bool CheckFirstParameter {
14468+ get { return false; }
14469+ }
14470+
14471+ protected abstract bool IsPrefered (TypeReference type);
14472+
14473+ protected virtual bool IsSpecialCase (MethodReference method)
14474+ {
14475+ return (method == null);
14476+ }
14477+
14478+ protected abstract void Report (MethodDefinition method, Instruction instruction, MethodReference prefered);
14479+
14480+ static bool MatchParameters (Collection<ParameterDefinition> pmethod, Collection<ParameterDefinition> candidate, int offset)
14481+ {
14482+ int ccount = candidate.Count - offset;
14483+ int count = Math.Min (pmethod.Count, ccount - offset);
14484+ for (int i = 0; i < count; i++) {
14485+ ParameterDefinition pd = candidate [i + offset];
14486+ if (pd.IsParams ())
14487+ return true;
14488+ TypeReference ptype = pd.ParameterType;
14489+ if (!pmethod [i].ParameterType.IsNamed (ptype.Namespace, ptype.Name))
14490+ return false;
14491+ }
14492+ return (ccount - count <= 1);
14493+ }
14494+
14495+ // look for a signature identical to ours but that accept an extra parameter
14496+ MethodReference LookForPreferredOverride (MethodReference method)
14497+ {
14498+ TypeDefinition type = method.DeclaringType.Resolve ();
14499+ if (type == null)
14500+ return null;
14501+
14502+ var methods = type.Methods;
14503+ // we already know that, if resolved, there's at least one method (the caller)
14504+ // so there's no need to call HasMethods
14505+ if (methods.Count == 1)
14506+ return null;
14507+
14508+ string name = method.Name;
14509+ int pcount = 0;
14510+ Collection<ParameterDefinition> mparams = null;
14511+ if (method.HasParameters) {
14512+ mparams = method.Parameters;
14513+ pcount = mparams.Count;
14514+ }
14515+
14516+ foreach (MethodDefinition md in methods) {
14517+ // has one more parameter, so non-zero
14518+ if (!md.HasParameters)
14519+ continue;
14520+
14521+ Collection<ParameterDefinition> pdc = md.Parameters;
14522+ if (name != md.Name)
14523+ continue;
14524+
14525+ // compare parameters and return value
14526+ TypeReference rtype = md.ReturnType;
14527+ if (!method.ReturnType.IsNamed (rtype.Namespace, rtype.Name))
14528+ continue;
14529+
14530+ // last parameter could be our "prefered" type
14531+ if (IsPrefered (pdc [pdc.Count - 1].ParameterType)) {
14532+ // special case where the method has no parameter, override has only one (the prefered)
14533+ if ((pcount == 0) && (mparams == null))
14534+ return md;
14535+ if (MatchParameters (mparams, pdc, 0))
14536+ return md;
14537+ } else if (CheckFirstParameter && IsPrefered (pdc [0].ParameterType)) {
14538+ if (MatchParameters (mparams, pdc, 1))
14539+ return md;
14540+ }
14541+ }
14542+ return null;
14543+ }
14544+
14545+ Dictionary<MethodReference, MethodReference> prefered_overloads = new Dictionary<MethodReference, MethodReference> ();
14546+
14547+ MethodReference GetPreferedOverride (MethodReference method)
14548+ {
14549+ MethodReference prefered = null;
14550+ if (!prefered_overloads.TryGetValue (method, out prefered)) {
14551+ prefered = LookForPreferredOverride (method);
14552+ prefered_overloads.Add (method, prefered);
14553+ }
14554+ return prefered;
14555+ }
14556+
14557+ public RuleResult CheckMethod (MethodDefinition method)
14558+ {
14559+ if (!method.HasBody)
14560+ return RuleResult.DoesNotApply;
14561+
14562+ // exclude methods that don't have calls
14563+ if (!OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)))
14564+ return RuleResult.DoesNotApply;
14565+
14566+ foreach (Instruction ins in method.Body.Instructions) {
14567+ MethodReference mr = ins.GetMethod ();
14568+ // some inheritors have special cases to deal with
14569+ if (IsSpecialCase (mr))
14570+ continue;
14571+
14572+ // check if the call starts or ends with our 'prefered' override
14573+ if (mr.HasParameters) {
14574+ Collection<ParameterDefinition> pdc = mr.Parameters;
14575+ if (CheckFirstParameter && IsPrefered (pdc [0].ParameterType))
14576+ continue;
14577+ if (IsPrefered (pdc [pdc.Count - 1].ParameterType))
14578+ continue;
14579+ }
14580+
14581+ // if not check if such a 'prefered' override exists to replace the called method
14582+ MethodReference prefered = GetPreferedOverride (mr);
14583+ if (prefered != null)
14584+ Report (method, ins, prefered);
14585+ }
14586+
14587+ return Runner.CurrentRuleResult;
14588+ }
14589+ }
14590+}
14591+
14592diff --git a/gendarme/rules/Gendarme.Rules.Globalization/PreferStringComparisonOverrideRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/PreferStringComparisonOverrideRule.cs
14593new file mode 100644
14594index 0000000..3ed3dfa
14595--- /dev/null
14596+++ b/gendarme/rules/Gendarme.Rules.Globalization/PreferStringComparisonOverrideRule.cs
14597@@ -0,0 +1,82 @@
14598+//
14599+// Gendarme.Rules.Globalization.PreferStringComparisonOverrideRule
14600+//
14601+// Authors:
14602+// Sebastien Pouliot <sebastien@ximian.com>
14603+//
14604+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
14605+//
14606+// Permission is hereby granted, free of charge, to any person obtaining
14607+// a copy of this software and associated documentation files (the
14608+// "Software"), to deal in the Software without restriction, including
14609+// without limitation the rights to use, copy, modify, merge, publish,
14610+// distribute, sublicense, and/or sell copies of the Software, and to
14611+// permit persons to whom the Software is furnished to do so, subject to
14612+// the following conditions:
14613+//
14614+// The above copyright notice and this permission notice shall be
14615+// included in all copies or substantial portions of the Software.
14616+//
14617+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14618+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14619+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14620+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
14621+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
14622+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
14623+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14624+//
14625+
14626+using System;
14627+using System.Globalization;
14628+
14629+using Mono.Cecil;
14630+using Mono.Cecil.Cil;
14631+using Gendarme.Framework;
14632+using Gendarme.Framework.Rocks;
14633+
14634+namespace Gendarme.Rules.Globalization {
14635+
14636+ /// <summary>
14637+ /// This rule detects calls to method that could be changed to call an <c>override</c> accepting an
14638+ /// extra <c>System.StringComparison</c> parameter. Using the <c>override</c> makes the code easier
14639+ /// to maintain since it makes the intent clear on how the string needs to be compared.
14640+ /// It is even more important since the default string comparison rules have changed between
14641+ /// .NET 2.0 and .NET 4.0.
14642+ /// </summary>
14643+ /// <example>
14644+ /// Bad example:
14645+ /// <code>
14646+ /// public bool Check (string name)
14647+ /// {
14648+ /// // it's not clear if the string comparison should be culture sensitive or not
14649+ /// return (String.Compare (name, "Software") == 0);
14650+ /// }
14651+ /// </code>
14652+ /// </example>
14653+ /// <example>
14654+ /// Good example:
14655+ /// <code>
14656+ /// public bool Check (string name)
14657+ /// {
14658+ /// return (String.Compare (name, "Software", StringComparison.CurrentCulture) == 0);
14659+ /// }
14660+ /// </code>
14661+ /// </example>
14662+ [Problem ("A call is made to a method for which an override, accepting an extra StringComparison, is available")]
14663+ [Solution ("Specify how the string should be compared by adding the right StringComparison value to the call")]
14664+ [FxCopCompatibility ("Microsoft.Globalization", "CA1307:SpecifyStringComparison")]
14665+ public class PreferStringComparisonOverrideRule : PreferOverrideBaseRule {
14666+
14667+ protected override bool IsPrefered (TypeReference type)
14668+ {
14669+ return type.IsNamed ("System", "StringComparison");
14670+ }
14671+
14672+ protected override void Report (MethodDefinition method, Instruction instruction, MethodReference prefered)
14673+ {
14674+ string msg = String.Format (CultureInfo.InvariantCulture,
14675+ "Consider using the perfered '{0}' override.", prefered.GetFullName ());
14676+ Runner.Report (method, instruction, Severity.Medium, Confidence.High, msg);
14677+ }
14678+ }
14679+}
14680diff --git a/gendarme/rules/Gendarme.Rules.Globalization/README.md b/gendarme/rules/Gendarme.Rules.Globalization/README.md
14681new file mode 100644
14682index 0000000..9c08b48
14683--- /dev/null
14684+++ b/gendarme/rules/Gendarme.Rules.Globalization/README.md
14685@@ -0,0 +1,9 @@
14686+# Gendarme.Rules.Globalization Rules
14687+
14688+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Globalization(git)]] pages.
14689+
14690+
14691+## Feedback
14692+
14693+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
14694+
14695diff --git a/gendarme/rules/Gendarme.Rules.Globalization/SatelliteResourceMismatchRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/SatelliteResourceMismatchRule.cs
14696index 86af3a4..5829b97 100644
14697--- a/gendarme/rules/Gendarme.Rules.Globalization/SatelliteResourceMismatchRule.cs
14698+++ b/gendarme/rules/Gendarme.Rules.Globalization/SatelliteResourceMismatchRule.cs
14699@@ -27,6 +27,7 @@
14700 //
14701
14702 using System;
14703+using System.Globalization;
14704 using System.IO;
14705 using System.Text;
14706 using System.Resources;
14707@@ -81,8 +82,10 @@ namespace Gendarme.Rules.Globalization {
14708 EmbeddedResource mainResource;
14709 string resourceName = GetNameInSatellite (resource, culture);
14710 if (!mainAssemblyResourceCache.TryGetMainResourceFile (resourceName, out mainResource)) {
14711- Runner.Report (satellite, Severity.Low, Confidence.High,
14712- String.Format ("The resource file {0} exist in the satellite assembly but not in the main assembly", resource.Name));
14713+ string msg = String.Format (CultureInfo.InvariantCulture,
14714+ "The resource file {0} exist in the satellite assembly but not in the main assembly",
14715+ resource.Name);
14716+ Runner.Report (satellite, Severity.Low, Confidence.High, msg);
14717 continue;
14718 }
14719
14720@@ -102,16 +105,20 @@ namespace Gendarme.Rules.Globalization {
14721 object satelliteValue = entry.Value;
14722 object mainValue;
14723 if (!mainAssemblyResourceCache.TryGetMainResource (mainResource, resourceName, out mainValue)) {
14724- Runner.Report (satelliteAssembly, Severity.Low, Confidence.High,
14725- String.Format ("The resource {0} in the file {1} exist in the satellite assembly but not in the main assembly", resourceName, satelliteResource.Name));
14726+ string msg = String.Format (CultureInfo.InvariantCulture,
14727+ "The resource {0} in the file {1} exist in the satellite assembly but not in the main assembly",
14728+ resourceName, satelliteResource.Name);
14729+ Runner.Report (satelliteAssembly, Severity.Low, Confidence.High, msg);
14730 continue;
14731 }
14732
14733 Type satelliteType = satelliteValue.GetType ();
14734 Type mainType = mainValue.GetType ();
14735 if (!satelliteType.Equals (mainType)) {
14736- Runner.Report (satelliteAssembly, Severity.High, Confidence.High,
14737- String.Format ("The resource {0} in the file {1} is of type {2} in the satellite assembly but of type {3} in the main assembly", resourceName, satelliteResource.Name, satelliteType, mainType));
14738+ string msg = String.Format (CultureInfo.InvariantCulture,
14739+ "The resource {0} in the file {1} is of type {2} in the satellite assembly but of type {3} in the main assembly",
14740+ resourceName, satelliteResource.Name, satelliteType, mainType);
14741+ Runner.Report (satelliteAssembly, Severity.High, Confidence.High, msg);
14742 continue;
14743 }
14744
14745@@ -119,9 +126,12 @@ namespace Gendarme.Rules.Globalization {
14746 Bitmask<int> mainParameters = GetStringFormatExpectedParameters ((string) mainValue);
14747 Bitmask<int> satelliteParameters = GetStringFormatExpectedParameters ((string) satelliteValue);
14748
14749- if (!mainParameters.Equals (satelliteParameters))
14750- Runner.Report (satelliteAssembly, Severity.High, Confidence.Normal,
14751- String.Format ("The string resource {0} in the file {1} does not use the same string format parameters in the satellite and main assemblies", resourceName, satelliteResource.Name));
14752+ if (!mainParameters.Equals (satelliteParameters)) {
14753+ string msg = String.Format (CultureInfo.InvariantCulture,
14754+ "The string resource {0} in the file {1} does not use the same string format parameters in the satellite and main assemblies",
14755+ resourceName, satelliteResource.Name);
14756+ Runner.Report (satelliteAssembly, Severity.High, Confidence.Normal, msg);
14757+ }
14758 }
14759 }
14760 }
14761@@ -203,7 +213,7 @@ namespace Gendarme.Rules.Globalization {
14762
14763 string cultureExtension = "." + culture;
14764
14765- if (!nameWithoutExtension.EndsWith (cultureExtension))
14766+ if (!nameWithoutExtension.EndsWith (cultureExtension, StringComparison.Ordinal))
14767 return name;
14768
14769 string nameWithoutCulture = Path.GetFileNameWithoutExtension (nameWithoutExtension);
14770@@ -212,7 +222,7 @@ namespace Gendarme.Rules.Globalization {
14771
14772 private static bool IsResXResources (Resource resource)
14773 {
14774- return resource.Name.EndsWith (resXResourcesExtension);
14775+ return resource.Name.EndsWith (resXResourcesExtension, StringComparison.Ordinal);
14776 }
14777
14778 private sealed class AssemblyResourceCache {
14779diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/InternalResource.Designer.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/InternalResource.Designer.cs
14780index d99d5fe..fb95375 100644
14781--- a/gendarme/rules/Gendarme.Rules.Globalization/Test/InternalResource.Designer.cs
14782+++ b/gendarme/rules/Gendarme.Rules.Globalization/Test/InternalResource.Designer.cs
14783@@ -1,7 +1,7 @@
14784-//------------------------------------------------------------------------------
14785+//------------------------------------------------------------------------------
14786 // <auto-generated>
14787 // This code was generated by a tool.
14788-// Runtime Version:2.0.50727.4952
14789+// Runtime Version:4.0.30319.1
14790 //
14791 // Changes to this file may cause incorrect behavior and will be lost if
14792 // the code is regenerated.
14793@@ -19,7 +19,7 @@ namespace Tests.Rules.Globalization {
14794 // class via a tool like ResGen or Visual Studio.
14795 // To add or remove a member, edit your .ResX file then rerun ResGen
14796 // with the /str option, or rebuild your VS project.
14797- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
14798+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
14799 [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
14800 [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
14801 internal class InternalResource {
14802diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferIFormatProviderOverrideTest.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferIFormatProviderOverrideTest.cs
14803new file mode 100644
14804index 0000000..83fa855
14805--- /dev/null
14806+++ b/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferIFormatProviderOverrideTest.cs
14807@@ -0,0 +1,219 @@
14808+//
14809+// Unit tests for PreferIFormatProviderOverrideRule
14810+//
14811+// Authors:
14812+// Sebastien Pouliot <sebastien@ximian.com>
14813+//
14814+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
14815+//
14816+// Permission is hereby granted, free of charge, to any person obtaining
14817+// a copy of this software and associated documentation files (the
14818+// "Software"), to deal in the Software without restriction, including
14819+// without limitation the rights to use, copy, modify, merge, publish,
14820+// distribute, sublicense, and/or sell copies of the Software, and to
14821+// permit persons to whom the Software is furnished to do so, subject to
14822+// the following conditions:
14823+//
14824+// The above copyright notice and this permission notice shall be
14825+// included in all copies or substantial portions of the Software.
14826+//
14827+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14828+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14829+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14830+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
14831+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
14832+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
14833+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14834+//
14835+
14836+using System;
14837+using System.Globalization;
14838+using System.Reflection;
14839+using System.Resources;
14840+
14841+using Gendarme.Rules.Globalization;
14842+using NUnit.Framework;
14843+
14844+using Test.Rules.Definitions;
14845+using Test.Rules.Fixtures;
14846+
14847+namespace Tests.Rules.Globalization {
14848+
14849+ class IFormatProviderTestCases {
14850+
14851+ public void Empty ()
14852+ {
14853+ }
14854+
14855+ public void Empty (IFormatProvider format)
14856+ {
14857+ }
14858+
14859+ public void BadEmpty ()
14860+ {
14861+ Empty ();
14862+ }
14863+
14864+ public void CorrectEmpty ()
14865+ {
14866+ Empty (null);
14867+ }
14868+
14869+ public void First (object obj)
14870+ {
14871+ }
14872+
14873+ public void First (IFormatProvider format, object obj)
14874+ {
14875+ }
14876+
14877+ public void BadFirst ()
14878+ {
14879+ First (null);
14880+ }
14881+
14882+ public void CorrectFirst ()
14883+ {
14884+ First (null, null);
14885+ }
14886+
14887+ public void Last (object obj)
14888+ {
14889+ }
14890+
14891+ public void Last (object obj, IFormatProvider format)
14892+ {
14893+ }
14894+
14895+ public void BadLast ()
14896+ {
14897+ Last (null);
14898+ }
14899+
14900+ public void CorrectLast ()
14901+ {
14902+ Last (null, null);
14903+ }
14904+ }
14905+
14906+ class CultureInfoTestCases {
14907+
14908+ public void Empty ()
14909+ {
14910+ }
14911+
14912+ public void Empty (CultureInfo info)
14913+ {
14914+ }
14915+
14916+ public void BadEmpty ()
14917+ {
14918+ Empty ();
14919+ }
14920+
14921+ public void CorrectEmpty ()
14922+ {
14923+ Empty (null);
14924+ }
14925+
14926+ public void First (object obj)
14927+ {
14928+ }
14929+
14930+ public void First (CultureInfo info, object obj)
14931+ {
14932+ }
14933+
14934+ public void BadFirst ()
14935+ {
14936+ First (null);
14937+ }
14938+
14939+ public void CorrectFirst ()
14940+ {
14941+ First (null, null);
14942+ }
14943+
14944+ public void Last (object obj)
14945+ {
14946+ }
14947+
14948+ public void Last (object obj, CultureInfo info)
14949+ {
14950+ }
14951+
14952+ public void BadLast ()
14953+ {
14954+ Last (null);
14955+ }
14956+
14957+ public void CorrectLast ()
14958+ {
14959+ Last (null, null);
14960+ }
14961+ }
14962+
14963+ [TestFixture]
14964+ public class PreferIFormatProviderOverrideTest : MethodRuleTestFixture<PreferIFormatProviderOverrideRule> {
14965+
14966+ [Test]
14967+ public void DoesNotApply ()
14968+ {
14969+ AssertRuleDoesNotApply (SimpleMethods.EmptyMethod);
14970+ AssertRuleDoesNotApply (SimpleMethods.ExternalMethod);
14971+ }
14972+
14973+ [Test]
14974+ public void Success ()
14975+ {
14976+ AssertRuleSuccess<IFormatProviderTestCases> ("CorrectEmpty");
14977+ AssertRuleSuccess<IFormatProviderTestCases> ("CorrectFirst");
14978+ AssertRuleSuccess<IFormatProviderTestCases> ("CorrectLast");
14979+
14980+ AssertRuleSuccess<CultureInfoTestCases> ("CorrectEmpty");
14981+ AssertRuleSuccess<CultureInfoTestCases> ("CorrectFirst");
14982+ AssertRuleSuccess<CultureInfoTestCases> ("CorrectLast");
14983+ }
14984+
14985+ [Test]
14986+ public void Failure ()
14987+ {
14988+ AssertRuleFailure<IFormatProviderTestCases> ("BadEmpty", 1);
14989+ AssertRuleFailure<IFormatProviderTestCases> ("BadFirst", 1);
14990+ AssertRuleFailure<IFormatProviderTestCases> ("BadLast", 1);
14991+
14992+ AssertRuleFailure<CultureInfoTestCases> ("BadEmpty", 1);
14993+ AssertRuleFailure<CultureInfoTestCases> ("BadFirst", 1);
14994+ AssertRuleFailure<CultureInfoTestCases> ("BadLast", 1);
14995+ }
14996+
14997+ void Ignored (ResourceManager rm)
14998+ {
14999+ rm.GetObject ("a");
15000+ rm.GetObject ("a", CultureInfo.CurrentCulture);
15001+ rm.GetString ("b");
15002+ rm.GetString ("b", CultureInfo.InvariantCulture);
15003+ }
15004+
15005+ string Params ()
15006+ {
15007+ // the overload to use is: Format(IFormatProvider, string, params object []);
15008+ return String.Format ("{0} {1} {2}", 1, 2, 3);
15009+ }
15010+
15011+ void NoSimpleOverload (FieldInfo fi)
15012+ {
15013+ // the overload with a CultureInfo is SetValue (object, object, BindingFlags, Binder, CultureInfo);
15014+ // and is not simply an "extra" parameter
15015+ fi.SetValue (new object (), 1);
15016+ }
15017+
15018+ [Test]
15019+ public void SpecialCases ()
15020+ {
15021+ AssertRuleSuccess<PreferIFormatProviderOverrideTest> ("Ignored");
15022+ AssertRuleFailure<PreferIFormatProviderOverrideTest> ("Params", 1);
15023+ AssertRuleSuccess<PreferIFormatProviderOverrideTest> ("NoSimpleOverload");
15024+ }
15025+ }
15026+}
15027diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferStringComparisonOverrideTest.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferStringComparisonOverrideTest.cs
15028new file mode 100644
15029index 0000000..722ff32
15030--- /dev/null
15031+++ b/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferStringComparisonOverrideTest.cs
15032@@ -0,0 +1,366 @@
15033+//
15034+// Unit tests for PreferStringComparisonOverrideRule
15035+//
15036+// Authors:
15037+// Sebastien Pouliot <sebastien@ximian.com>
15038+//
15039+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
15040+//
15041+// Permission is hereby granted, free of charge, to any person obtaining
15042+// a copy of this software and associated documentation files (the
15043+// "Software"), to deal in the Software without restriction, including
15044+// without limitation the rights to use, copy, modify, merge, publish,
15045+// distribute, sublicense, and/or sell copies of the Software, and to
15046+// permit persons to whom the Software is furnished to do so, subject to
15047+// the following conditions:
15048+//
15049+// The above copyright notice and this permission notice shall be
15050+// included in all copies or substantial portions of the Software.
15051+//
15052+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15053+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15054+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15055+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
15056+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
15057+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
15058+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
15059+//
15060+
15061+using System;
15062+
15063+using Gendarme.Rules.Globalization;
15064+using NUnit.Framework;
15065+
15066+using Test.Rules.Definitions;
15067+using Test.Rules.Fixtures;
15068+
15069+namespace Tests.Rules.Globalization {
15070+
15071+ [TestFixture]
15072+ public class PreferStringComparisonOverrideTest : MethodRuleTestFixture<PreferStringComparisonOverrideRule> {
15073+
15074+ [Test]
15075+ public void DoesNotApply ()
15076+ {
15077+ AssertRuleDoesNotApply (SimpleMethods.EmptyMethod);
15078+ AssertRuleDoesNotApply (SimpleMethods.ExternalMethod);
15079+ }
15080+
15081+ public class InstanceWithoutOverride {
15082+
15083+ public bool Compare (string s1, string s2)
15084+ {
15085+ return false;
15086+ }
15087+
15088+ public void Test ()
15089+ {
15090+ if (Compare ("a", "b"))
15091+ Console.WriteLine ();
15092+ }
15093+ }
15094+
15095+ public class Base {
15096+
15097+ public bool Compare (string s1, string s2)
15098+ {
15099+ return false;
15100+ }
15101+
15102+ public void TestBase ()
15103+ {
15104+ if (Compare ("a", "b"))
15105+ Console.WriteLine ();
15106+ }
15107+ }
15108+
15109+ public class Inherited : Base {
15110+ public bool Compare (string s1, string s2, StringComparison comparison)
15111+ {
15112+ return true;
15113+ }
15114+
15115+ public void TestInherited ()
15116+ {
15117+ // from IL this is a call to Base.Compare so the override is not seen
15118+ // note: fxcop also miss this one
15119+ if (Compare ("a", "b"))
15120+ Console.WriteLine ();
15121+ }
15122+ }
15123+
15124+ public class StaticHelperWithoutOverride {
15125+
15126+ // no alternative
15127+ public static bool StaticCompare (string s1, string s2)
15128+ {
15129+ return false;
15130+ }
15131+
15132+ public void Test ()
15133+ {
15134+ if (StaticCompare ("a", "b"))
15135+ Console.WriteLine ();
15136+ }
15137+ }
15138+
15139+ public class StaticHelperWithExtraParameterInOverride {
15140+
15141+ public static bool StaticCompare (string s1, string s2)
15142+ {
15143+ return false;
15144+ }
15145+
15146+ // the extra parameter disqualify the override
15147+ public static bool StaticCompare (string s1, string s2, bool value, StringComparison comparison)
15148+ {
15149+ return value;
15150+ }
15151+
15152+ // the extra parameter disqualify the override
15153+ public static bool StaticCompare (string s1, string s2, StringComparison comparison, bool value)
15154+ {
15155+ return value;
15156+ }
15157+
15158+ public void Test ()
15159+ {
15160+ if (StaticCompare ("a", "b"))
15161+ Console.WriteLine ();
15162+ }
15163+ }
15164+
15165+ public class Weird {
15166+ public bool Compare (StringComparison a, StringComparison b)
15167+ {
15168+ return (a == b);
15169+ }
15170+
15171+ public void Test ()
15172+ {
15173+ if (Compare (StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase))
15174+ Console.WriteLine ();
15175+ }
15176+ }
15177+
15178+ [Test]
15179+ public void Success ()
15180+ {
15181+ AssertRuleSuccess<InstanceWithoutOverride> ("Test");
15182+
15183+ AssertRuleSuccess<Base> ("TestBase");
15184+ AssertRuleSuccess<Inherited> ("TestInherited");
15185+
15186+ AssertRuleSuccess<StaticHelperWithoutOverride> ("Test");
15187+ AssertRuleSuccess<StaticHelperWithExtraParameterInOverride> ("Test");
15188+
15189+ AssertRuleSuccess<Weird> ("Test");
15190+ }
15191+
15192+ public class InstanceWithOverride {
15193+
15194+ public bool Compare (string s1, string s2)
15195+ {
15196+ return false;
15197+ }
15198+
15199+ public bool Compare (string s1, string s2, StringComparison comparison)
15200+ {
15201+ return true;
15202+ }
15203+
15204+ // bad
15205+ public void Test ()
15206+ {
15207+ if (Compare ("a", "b"))
15208+ Console.WriteLine ();
15209+ }
15210+ }
15211+
15212+ public class StaticHelper {
15213+
15214+ public static bool StaticCompare (string s1, string s2)
15215+ {
15216+ return false;
15217+ }
15218+
15219+ // we have an alternative
15220+ public static bool StaticCompare (string s1, string s2, StringComparison comparison)
15221+ {
15222+ return true;
15223+ }
15224+
15225+ // bad
15226+ public void Test ()
15227+ {
15228+ if (StaticHelper.StaticCompare ("a", "b"))
15229+ Console.WriteLine ();
15230+ }
15231+ }
15232+
15233+ public class NonString {
15234+
15235+ public bool Kompare (char [] s1, char [] s2)
15236+ {
15237+ return false;
15238+ }
15239+
15240+ public bool Kompare (char [] s1, char [] s2, StringComparison comparison)
15241+ {
15242+ return true;
15243+ }
15244+
15245+ // bad
15246+ public void TestCharArray ()
15247+ {
15248+ if (Kompare (new char [] { }, new char [] { }))
15249+ Console.WriteLine ();
15250+ }
15251+
15252+ public bool KomparInt (int a, int b)
15253+ {
15254+ return false;
15255+ }
15256+
15257+ public bool KomparInt (int a, int b, StringComparison comparison)
15258+ {
15259+ return true;
15260+ }
15261+
15262+ // bad
15263+ public void TestInt ()
15264+ {
15265+ if (KomparInt (0, 0))
15266+ Console.WriteLine ();
15267+ }
15268+ }
15269+
15270+ public class ExtraParameters {
15271+
15272+ public bool Kompare (int level, string s1, string s2)
15273+ {
15274+ return false;
15275+ }
15276+
15277+ public bool Kompare (int level, string s1, string s2, StringComparison comparison)
15278+ {
15279+ return true;
15280+ }
15281+
15282+ // bad
15283+ public void TestExtraFirst ()
15284+ {
15285+ if (Kompare (0, "a", "B"))
15286+ Console.WriteLine ();
15287+ }
15288+
15289+ public bool Kompar (string s1, int start, string s2)
15290+ {
15291+ return false;
15292+ }
15293+
15294+ public bool Kompar (string s1, int start, string s2, StringComparison comparison)
15295+ {
15296+ return true;
15297+ }
15298+
15299+ // bad
15300+ public void TestExtraMid ()
15301+ {
15302+ if (Kompar ("a", 0, "B"))
15303+ Console.WriteLine ();
15304+ }
15305+
15306+ public bool Komparz (string s1, string s2, int end)
15307+ {
15308+ return false;
15309+ }
15310+
15311+ // note: parameter name mismatch
15312+ public bool Komparz (string s1, string s2, int start, StringComparison comparison)
15313+ {
15314+ return true;
15315+ }
15316+
15317+ // bad
15318+ public void TestExtraEnd ()
15319+ {
15320+ if (Komparz ("a", "B", 0))
15321+ Console.WriteLine ();
15322+ }
15323+ }
15324+
15325+ public class FewParameters {
15326+
15327+ public bool Compare ()
15328+ {
15329+ return false;
15330+ }
15331+
15332+ public bool Compare (StringComparison comparison)
15333+ {
15334+ return true;
15335+ }
15336+
15337+ // bad
15338+ public void TestNone ()
15339+ {
15340+ if (Compare ())
15341+ Console.WriteLine ();
15342+ }
15343+
15344+ public bool Compare (object o)
15345+ {
15346+ return (o == null);
15347+ }
15348+
15349+ public bool Compare (object o, StringComparison comparison)
15350+ {
15351+ return true;
15352+ }
15353+
15354+ // bad
15355+ public void TestSingle ()
15356+ {
15357+ if (Compare (null))
15358+ Console.WriteLine ();
15359+ }
15360+
15361+ public bool Compare (short a, long b)
15362+ {
15363+ return (a == b);
15364+ }
15365+
15366+ public bool Compare (short a, long b, StringComparison comparison)
15367+ {
15368+ return true;
15369+ }
15370+
15371+ // bad
15372+ public void TestDifferent ()
15373+ {
15374+ if (Compare (1, 1))
15375+ Console.WriteLine ();
15376+ }
15377+ }
15378+
15379+ [Test]
15380+ public void Failure ()
15381+ {
15382+ AssertRuleFailure<InstanceWithOverride> ("Test");
15383+
15384+ AssertRuleFailure<StaticHelper> ("Test");
15385+
15386+ AssertRuleFailure<NonString> ("TestCharArray");
15387+ AssertRuleFailure<NonString> ("TestInt");
15388+
15389+ AssertRuleFailure<ExtraParameters> ("TestExtraFirst");
15390+ AssertRuleFailure<ExtraParameters> ("TestExtraMid");
15391+ AssertRuleFailure<ExtraParameters> ("TestExtraEnd");
15392+
15393+ AssertRuleFailure<FewParameters> ("TestNone");
15394+ AssertRuleFailure<FewParameters> ("TestSingle");
15395+ AssertRuleFailure<FewParameters> ("TestDifferent");
15396+ }
15397+ }
15398+}
15399diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/PublicResource.Designer.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/PublicResource.Designer.cs
15400index 435893c..369bf20 100644
15401--- a/gendarme/rules/Gendarme.Rules.Globalization/Test/PublicResource.Designer.cs
15402+++ b/gendarme/rules/Gendarme.Rules.Globalization/Test/PublicResource.Designer.cs
15403@@ -1,7 +1,7 @@
15404-//------------------------------------------------------------------------------
15405+//------------------------------------------------------------------------------
15406 // <auto-generated>
15407 // This code was generated by a tool.
15408-// Runtime Version:2.0.50727.4952
15409+// Runtime Version:4.0.30319.1
15410 //
15411 // Changes to this file may cause incorrect behavior and will be lost if
15412 // the code is regenerated.
15413@@ -19,7 +19,7 @@ namespace Tests.Rules.Globalization {
15414 // class via a tool like ResGen or Visual Studio.
15415 // To add or remove a member, edit your .ResX file then rerun ResGen
15416 // with the /str option, or rebuild your VS project.
15417- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
15418+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
15419 [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
15420 [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15421 public class PublicResource {
15422diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/Resource.Designer.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/Resource.Designer.cs
15423index 2edd1e0..8847e59 100644
15424--- a/gendarme/rules/Gendarme.Rules.Globalization/Test/Resource.Designer.cs
15425+++ b/gendarme/rules/Gendarme.Rules.Globalization/Test/Resource.Designer.cs
15426@@ -1,7 +1,7 @@
15427-//------------------------------------------------------------------------------
15428+//------------------------------------------------------------------------------
15429 // <auto-generated>
15430 // This code was generated by a tool.
15431-// Runtime Version:2.0.50727.4952
15432+// Runtime Version:4.0.30319.1
15433 //
15434 // Changes to this file may cause incorrect behavior and will be lost if
15435 // the code is regenerated.
15436@@ -19,7 +19,7 @@ namespace Tests.Rules.Globalization {
15437 // class via a tool like ResGen or Visual Studio.
15438 // To add or remove a member, edit your .ResX file then rerun ResGen
15439 // with the /str option, or rebuild your VS project.
15440- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
15441+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
15442 [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
15443 [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15444 internal class Resource {
15445diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/Tests.Rules.Globalization.csproj b/gendarme/rules/Gendarme.Rules.Globalization/Test/Tests.Rules.Globalization.csproj
15446index 063810d..d1c6107 100644
15447--- a/gendarme/rules/Gendarme.Rules.Globalization/Test/Tests.Rules.Globalization.csproj
15448+++ b/gendarme/rules/Gendarme.Rules.Globalization/Test/Tests.Rules.Globalization.csproj
15449@@ -1,5 +1,5 @@
15450 <?xml version="1.0" encoding="utf-8"?>\r
15451-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
15452+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
15453 <PropertyGroup>\r
15454 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
15455 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
15456@@ -10,8 +10,28 @@
15457 <AppDesignerFolder>Properties</AppDesignerFolder>\r
15458 <RootNamespace>Tests.Rules.Globalization</RootNamespace>\r
15459 <AssemblyName>Tests.Rules.Globalization</AssemblyName>\r
15460- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
15461+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
15462 <FileAlignment>512</FileAlignment>\r
15463+ <FileUpgradeFlags>\r
15464+ </FileUpgradeFlags>\r
15465+ <OldToolsVersion>3.5</OldToolsVersion>\r
15466+ <UpgradeBackupLocation />\r
15467+ <PublishUrl>publish\</PublishUrl>\r
15468+ <Install>true</Install>\r
15469+ <InstallFrom>Disk</InstallFrom>\r
15470+ <UpdateEnabled>false</UpdateEnabled>\r
15471+ <UpdateMode>Foreground</UpdateMode>\r
15472+ <UpdateInterval>7</UpdateInterval>\r
15473+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
15474+ <UpdatePeriodically>false</UpdatePeriodically>\r
15475+ <UpdateRequired>false</UpdateRequired>\r
15476+ <MapFileExtensions>true</MapFileExtensions>\r
15477+ <ApplicationRevision>0</ApplicationRevision>\r
15478+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
15479+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
15480+ <UseApplicationTrust>false</UseApplicationTrust>\r
15481+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
15482+ <TargetFrameworkProfile />\r
15483 </PropertyGroup>\r
15484 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
15485 <DebugSymbols>true</DebugSymbols>\r
15486@@ -21,6 +41,7 @@
15487 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
15488 <ErrorReport>prompt</ErrorReport>\r
15489 <WarningLevel>4</WarningLevel>\r
15490+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
15491 </PropertyGroup>\r
15492 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
15493 <DebugType>pdbonly</DebugType>\r
15494@@ -29,6 +50,7 @@
15495 <DefineConstants>TRACE</DefineConstants>\r
15496 <ErrorReport>prompt</ErrorReport>\r
15497 <WarningLevel>4</WarningLevel>\r
15498+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
15499 </PropertyGroup>\r
15500 <ItemGroup>\r
15501 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
15502@@ -128,6 +150,23 @@
15503 <ItemGroup>\r
15504 <Folder Include="Properties\" />\r
15505 </ItemGroup>\r
15506+ <ItemGroup>\r
15507+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
15508+ <Visible>False</Visible>\r
15509+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
15510+ <Install>false</Install>\r
15511+ </BootstrapperPackage>\r
15512+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
15513+ <Visible>False</Visible>\r
15514+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
15515+ <Install>true</Install>\r
15516+ </BootstrapperPackage>\r
15517+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
15518+ <Visible>False</Visible>\r
15519+ <ProductName>Windows Installer 3.1</ProductName>\r
15520+ <Install>true</Install>\r
15521+ </BootstrapperPackage>\r
15522+ </ItemGroup>\r
15523 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
15524 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
15525 Other similar extension points exist, see Microsoft.Common.targets.\r
15526diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/AutoLayoutTypesShouldNotBeComVisibleRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/AutoLayoutTypesShouldNotBeComVisibleRule.cs
15527index 5de0801..e6ae04b 100644
15528--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/AutoLayoutTypesShouldNotBeComVisibleRule.cs
15529+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/AutoLayoutTypesShouldNotBeComVisibleRule.cs
15530@@ -37,9 +37,11 @@ using Gendarme.Framework.Rocks;
15531 namespace Gendarme.Rules.Interoperability.Com {
15532
15533 /// <summary>
15534- /// This rule checks for ComVisible value types which have StructLayout
15535- /// attribute set to LayoutKind.Auto because auto layout can change
15536- /// between Mono and .NET or even between releases of the .NET/Mono frameworks
15537+ /// This rule checks for <c>[System.Runtime.InteropServices.ComVisible]</c> decorated value
15538+ /// types which have <c>[System.Runtime.InteropServices.StructLayout]</c> attribute set to
15539+ /// <c>System.Runtime.InteropServices.LayoutKind</c>.<c>Auto</c> because auto layout can
15540+ /// change between Mono and .NET or even between releases of the .NET/Mono frameworks.
15541+ /// Note that this does not affect <c>System.Enum</c>-based types.
15542 /// </summary>
15543 /// <example>
15544 /// Bad example:
15545@@ -80,7 +82,7 @@ namespace Gendarme.Rules.Interoperability.Com {
15546
15547 public RuleResult CheckType (TypeDefinition type)
15548 {
15549- if (!type.IsValueType || !type.HasCustomAttributes ||
15550+ if (type.IsEnum || !type.IsValueType || !type.HasCustomAttributes ||
15551 (!type.IsPublic && !type.IsNestedPublic) || type.HasGenericParameters)
15552 return RuleResult.DoesNotApply;
15553
15554diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidInt64ArgumentsInComVisibleMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidInt64ArgumentsInComVisibleMethodsRule.cs
15555index 5c13b94..5ef8900 100644
15556--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidInt64ArgumentsInComVisibleMethodsRule.cs
15557+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidInt64ArgumentsInComVisibleMethodsRule.cs
15558@@ -106,7 +106,7 @@ namespace Gendarme.Rules.Interoperability.Com {
15559 return RuleResult.DoesNotApply;
15560
15561 foreach (ParameterDefinition parameter in method.Parameters) {
15562- if (parameter.ParameterType.FullName == "System.Int64")
15563+ if (parameter.ParameterType.IsNamed ("System", "Int64"))
15564 Runner.Report (parameter, Severity.Medium, Confidence.Total);
15565 }
15566
15567diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidStaticMembersInComVisibleTypesRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidStaticMembersInComVisibleTypesRule.cs
15568index 9a22d1b..be412d2 100644
15569--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidStaticMembersInComVisibleTypesRule.cs
15570+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidStaticMembersInComVisibleTypesRule.cs
15571@@ -118,7 +118,7 @@ namespace Gendarme.Rules.Interoperability.Com {
15572 {
15573 return !(!method.IsStatic || !method.IsPublic || method.HasGenericParameters ||
15574 method.IsAddOn || method.IsRemoveOn || method.IsGetter || method.IsSetter ||
15575- ((method.Attributes & MethodAttributes.SpecialName) != 0 && method.Name.StartsWith ("op_")) ||
15576+ ((method.Attributes & MethodAttributes.SpecialName) != 0 && method.Name.StartsWith ("op_", StringComparison.Ordinal)) ||
15577 method.DeclaringType.HasGenericParameters || method.DeclaringType.IsEnum ||
15578 method.DeclaringType.IsInterface);
15579 }
15580diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComRocks.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComRocks.cs
15581index e25404c..5c1de40 100644
15582--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComRocks.cs
15583+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComRocks.cs
15584@@ -32,6 +32,8 @@
15585
15586 using Mono.Cecil;
15587
15588+using Gendarme.Framework.Rocks;
15589+
15590 namespace Gendarme.Rules.Interoperability.Com {
15591
15592 /// <summary>
15593@@ -56,7 +58,7 @@ namespace Gendarme.Rules.Interoperability.Com {
15594 // any attribute without arguments can be skipped
15595 if (!attribute.HasConstructorArguments)
15596 continue;
15597- if (attribute.Constructor.DeclaringType.FullName != "System.Runtime.InteropServices.ComVisibleAttribute")
15598+ if (!attribute.Constructor.DeclaringType.IsNamed ("System.Runtime.InteropServices", "ComVisibleAttribute"))
15599 continue;
15600 return (bool) attribute.ConstructorArguments[0].Value;
15601 }
15602@@ -74,6 +76,10 @@ namespace Gendarme.Rules.Interoperability.Com {
15603 // considering nested types, assemblies attributes and default values
15604 public static bool IsTypeComVisible (this TypeDefinition self)
15605 {
15606+ // [ComVisible] attribute will be ignored on non-visible types
15607+ if (!self.IsVisible ())
15608+ return false;
15609+
15610 return (self.IsComVisible () ?? self.Module.Assembly.IsComVisible () ?? true);
15611 }
15612 }
15613diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComVisibleShouldInheritFromComVisibleRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComVisibleShouldInheritFromComVisibleRule.cs
15614index 8e46c99..46291d5 100644
15615--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComVisibleShouldInheritFromComVisibleRule.cs
15616+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComVisibleShouldInheritFromComVisibleRule.cs
15617@@ -27,6 +27,7 @@
15618 //
15619
15620 using System;
15621+using System.Globalization;
15622 using System.Runtime.InteropServices;
15623
15624 using Mono.Cecil;
15625@@ -101,9 +102,9 @@ namespace Gendarme.Rules.Interoperability.Com {
15626
15627 TypeDefinition baseType = type.BaseType.Resolve ();
15628 if ((baseType != null) && !baseType.IsTypeComVisible ()) {
15629- Runner.Report (type, Severity.High, Confidence.Total,
15630- String.Format ("Type is derived from invisible from COM type {0}",
15631- baseType.FullName));
15632+ string msg = String.Format (CultureInfo.InvariantCulture,
15633+ "Type is derived from invisible from COM type {0}", baseType.GetFullName ());
15634+ Runner.Report (type, Severity.High, Confidence.Total, msg);
15635 }
15636 return Runner.CurrentRuleResult;
15637 }
15638diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/DoNotUseAutoDualClassInterfaceTypeRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/DoNotUseAutoDualClassInterfaceTypeRule.cs
15639index 2272ad1..31e43a0 100644
15640--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/DoNotUseAutoDualClassInterfaceTypeRule.cs
15641+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/DoNotUseAutoDualClassInterfaceTypeRule.cs
15642@@ -111,15 +111,14 @@ namespace Gendarme.Rules.Interoperability.Com {
15643 private static ClassInterfaceType? GetClassInterfaceAttributeValue (ICustomAttributeProvider obj)
15644 {
15645 foreach (CustomAttribute attribute in obj.CustomAttributes) {
15646- // ClassInterfaceAttribute has a two ctors each taking an argument (ClassInterfaceType or short)
15647 // http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.classinterfaceattribute.aspx
15648 // any attribute without arguments can be skipped
15649 if (!attribute.HasConstructorArguments)
15650 continue;
15651- if (attribute.AttributeType.FullName != "System.Runtime.InteropServices.ClassInterfaceAttribute")
15652+ if (!attribute.AttributeType.IsNamed ("System.Runtime.InteropServices", "ClassInterfaceAttribute"))
15653 continue;
15654 var ctorArgs = attribute.ConstructorArguments;
15655- if (ctorArgs [0].Type.FullName == "System.Int16")
15656+ if (ctorArgs [0].Type.IsNamed ("System", "Int16"))
15657 return (ClassInterfaceType)(short)ctorArgs [0].Value;
15658 return (ClassInterfaceType)(int)ctorArgs [0].Value;
15659 }
15660diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Gendarme.Rules.Interoperability.Com.csproj b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Gendarme.Rules.Interoperability.Com.csproj
15661index d39ca71..b0fbc53 100755
15662--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Gendarme.Rules.Interoperability.Com.csproj
15663+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Gendarme.Rules.Interoperability.Com.csproj
15664@@ -1,78 +1,117 @@
15665-<?xml version="1.0" encoding="utf-8"?>
15666-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
15667- <PropertyGroup>
15668- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
15669- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
15670- <ProductVersion>9.0.30729</ProductVersion>
15671- <SchemaVersion>2.0</SchemaVersion>
15672- <ProjectGuid>{468F7043-C0D5-480F-88A1-A262EC324E5E}</ProjectGuid>
15673- <OutputType>Library</OutputType>
15674- <AppDesignerFolder>Properties</AppDesignerFolder>
15675- <RootNamespace>Gendarme.Rules.Interoperability.Com</RootNamespace>
15676- <AssemblyName>Gendarme.Rules.Interoperability.Com</AssemblyName>
15677- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
15678- <FileAlignment>512</FileAlignment>
15679- </PropertyGroup>
15680- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
15681- <DebugSymbols>true</DebugSymbols>
15682- <DebugType>full</DebugType>
15683- <Optimize>false</Optimize>
15684- <OutputPath>..\..\console\bin\Debug\</OutputPath>
15685- <DefineConstants>DEBUG;TRACE</DefineConstants>
15686- <ErrorReport>prompt</ErrorReport>
15687- <WarningLevel>4</WarningLevel>
15688- <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Interoperability.Com.xml</DocumentationFile>
15689- </PropertyGroup>
15690- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
15691- <DebugType>pdbonly</DebugType>
15692- <Optimize>true</Optimize>
15693- <OutputPath>..\..\console\bin\Release\</OutputPath>
15694- <DefineConstants>TRACE;RELEASE</DefineConstants>
15695- <ErrorReport>prompt</ErrorReport>
15696- <WarningLevel>4</WarningLevel>
15697- <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Interoperability.Com.xml</DocumentationFile>
15698- </PropertyGroup>
15699- <ItemGroup>
15700- <Reference Include="System" />
15701- <Reference Include="System.Core">
15702- <RequiredTargetFramework>3.5</RequiredTargetFramework>
15703- </Reference>
15704- </ItemGroup>
15705- <ItemGroup>
15706- <ProjectReference Include="..\..\..\..\cecil\Mono.Cecil.csproj">
15707- <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>
15708- <Name>Mono.Cecil</Name>
15709- </ProjectReference>
15710- <ProjectReference Include="..\..\framework\Gendarme.Framework.csproj">
15711- <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>
15712- <Name>Gendarme.Framework</Name>
15713- </ProjectReference>
15714- </ItemGroup>
15715- <ItemGroup>
15716- <Compile Include="..\..\AssemblyStaticInfo.cs">
15717- <Link>AssemblyStaticInfo.cs</Link>
15718- </Compile>
15719- <Compile Include="AutoLayoutTypesShouldNotBeComVisibleRule.cs" />
15720- <Compile Include="AvoidInt64ArgumentsInComVisibleMethodsRule.cs" />
15721- <Compile Include="AvoidNonPublicFieldsInComVisibleValueTypesRule.cs" />
15722- <Compile Include="AvoidOverloadsInComVisibleInterfacesRule.cs" />
15723- <Compile Include="AvoidStaticMembersInComVisibleTypesRule.cs" />
15724- <Compile Include="ComRocks.cs" />
15725- <Compile Include="ComVisibleShouldInheritFromComVisibleRule.cs" />
15726- <Compile Include="ComVisibleTypesShouldBeCreatableRule.cs" />
15727- <Compile Include="DoNotUseAutoDualClassInterfaceTypeRule.cs" />
15728- <Compile Include="MarkComSourceInterfacesAsIDispatchRule.cs" />
15729- <Compile Include="ReviewComRegistrationMethodsRule.cs" />
15730- </ItemGroup>
15731- <ItemGroup>
15732- <Folder Include="Properties\" />
15733- </ItemGroup>
15734- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
15735+<?xml version="1.0" encoding="utf-8"?>\r
15736+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
15737+ <PropertyGroup>\r
15738+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
15739+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
15740+ <ProductVersion>9.0.30729</ProductVersion>\r
15741+ <SchemaVersion>2.0</SchemaVersion>\r
15742+ <ProjectGuid>{468F7043-C0D5-480F-88A1-A262EC324E5E}</ProjectGuid>\r
15743+ <OutputType>Library</OutputType>\r
15744+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
15745+ <RootNamespace>Gendarme.Rules.Interoperability.Com</RootNamespace>\r
15746+ <AssemblyName>Gendarme.Rules.Interoperability.Com</AssemblyName>\r
15747+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
15748+ <FileAlignment>512</FileAlignment>\r
15749+ <FileUpgradeFlags>\r
15750+ </FileUpgradeFlags>\r
15751+ <OldToolsVersion>3.5</OldToolsVersion>\r
15752+ <UpgradeBackupLocation />\r
15753+ <PublishUrl>publish\</PublishUrl>\r
15754+ <Install>true</Install>\r
15755+ <InstallFrom>Disk</InstallFrom>\r
15756+ <UpdateEnabled>false</UpdateEnabled>\r
15757+ <UpdateMode>Foreground</UpdateMode>\r
15758+ <UpdateInterval>7</UpdateInterval>\r
15759+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
15760+ <UpdatePeriodically>false</UpdatePeriodically>\r
15761+ <UpdateRequired>false</UpdateRequired>\r
15762+ <MapFileExtensions>true</MapFileExtensions>\r
15763+ <ApplicationRevision>0</ApplicationRevision>\r
15764+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
15765+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
15766+ <UseApplicationTrust>false</UseApplicationTrust>\r
15767+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
15768+ <TargetFrameworkProfile />\r
15769+ </PropertyGroup>\r
15770+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
15771+ <DebugSymbols>true</DebugSymbols>\r
15772+ <DebugType>full</DebugType>\r
15773+ <Optimize>false</Optimize>\r
15774+ <OutputPath>..\..\console\bin\Debug\</OutputPath>\r
15775+ <DefineConstants>DEBUG;TRACE</DefineConstants>\r
15776+ <ErrorReport>prompt</ErrorReport>\r
15777+ <WarningLevel>4</WarningLevel>\r
15778+ <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Interoperability.Com.xml</DocumentationFile>\r
15779+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
15780+ </PropertyGroup>\r
15781+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
15782+ <DebugType>pdbonly</DebugType>\r
15783+ <Optimize>true</Optimize>\r
15784+ <OutputPath>..\..\console\bin\Release\</OutputPath>\r
15785+ <DefineConstants>TRACE;RELEASE</DefineConstants>\r
15786+ <ErrorReport>prompt</ErrorReport>\r
15787+ <WarningLevel>4</WarningLevel>\r
15788+ <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Interoperability.Com.xml</DocumentationFile>\r
15789+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
15790+ </PropertyGroup>\r
15791+ <ItemGroup>\r
15792+ <Reference Include="System" />\r
15793+ <Reference Include="System.Core">\r
15794+ <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
15795+ </Reference>\r
15796+ </ItemGroup>\r
15797+ <ItemGroup>\r
15798+ <ProjectReference Include="..\..\..\..\cecil\Mono.Cecil.csproj">\r
15799+ <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
15800+ <Name>Mono.Cecil</Name>\r
15801+ </ProjectReference>\r
15802+ <ProjectReference Include="..\..\framework\Gendarme.Framework.csproj">\r
15803+ <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>\r
15804+ <Name>Gendarme.Framework</Name>\r
15805+ </ProjectReference>\r
15806+ </ItemGroup>\r
15807+ <ItemGroup>\r
15808+ <Compile Include="..\..\AssemblyStaticInfo.cs">\r
15809+ <Link>AssemblyStaticInfo.cs</Link>\r
15810+ </Compile>\r
15811+ <Compile Include="AutoLayoutTypesShouldNotBeComVisibleRule.cs" />\r
15812+ <Compile Include="AvoidInt64ArgumentsInComVisibleMethodsRule.cs" />\r
15813+ <Compile Include="AvoidNonPublicFieldsInComVisibleValueTypesRule.cs" />\r
15814+ <Compile Include="AvoidOverloadsInComVisibleInterfacesRule.cs" />\r
15815+ <Compile Include="AvoidStaticMembersInComVisibleTypesRule.cs" />\r
15816+ <Compile Include="ComRocks.cs" />\r
15817+ <Compile Include="ComVisibleShouldInheritFromComVisibleRule.cs" />\r
15818+ <Compile Include="ComVisibleTypesShouldBeCreatableRule.cs" />\r
15819+ <Compile Include="DoNotUseAutoDualClassInterfaceTypeRule.cs" />\r
15820+ <Compile Include="MarkComSourceInterfacesAsIDispatchRule.cs" />\r
15821+ <Compile Include="ReviewComRegistrationMethodsRule.cs" />\r
15822+ </ItemGroup>\r
15823+ <ItemGroup>\r
15824+ <Folder Include="Properties\" />\r
15825+ </ItemGroup>\r
15826+ <ItemGroup>\r
15827+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
15828+ <Visible>False</Visible>\r
15829+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
15830+ <Install>false</Install>\r
15831+ </BootstrapperPackage>\r
15832+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
15833+ <Visible>False</Visible>\r
15834+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
15835+ <Install>true</Install>\r
15836+ </BootstrapperPackage>\r
15837+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
15838+ <Visible>False</Visible>\r
15839+ <ProductName>Windows Installer 3.1</ProductName>\r
15840+ <Install>true</Install>\r
15841+ </BootstrapperPackage>\r
15842+ </ItemGroup>\r
15843+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
15844 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
15845 Other similar extension points exist, see Microsoft.Common.targets.
15846 <Target Name="BeforeBuild">
15847 </Target>
15848 <Target Name="AfterBuild">
15849 </Target>
15850- -->
15851+ -->\r
15852 </Project>
15853\ No newline at end of file
15854diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/MarkComSourceInterfacesAsIDispatchRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/MarkComSourceInterfacesAsIDispatchRule.cs
15855index 8bfc88f..46d932a 100644
15856--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/MarkComSourceInterfacesAsIDispatchRule.cs
15857+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/MarkComSourceInterfacesAsIDispatchRule.cs
15858@@ -63,7 +63,7 @@ namespace Gendarme.Rules.Interoperability.Com {
15859 [Solution ("Add an InterfaceTypeAttribute set to InterfaceIsIDispatch for all specified interfaces.")]
15860 [FxCopCompatibility ("Microsoft.Interoperability", "CA1412:MarkComSourceInterfacesAsIDispatch")]
15861 public class MarkComSourceInterfacesAsIDispatchRule : Rule, ITypeRule {
15862- private List<TypeDefinition> interfaces = new List<TypeDefinition> ();
15863+ private SortedDictionary<string, TypeDefinition> interfaces = new SortedDictionary<string, TypeDefinition> ();
15864
15865 // Iterate through all assemblies and add the interfaces found to a list.
15866 private void FindInterfaces ()
15867@@ -73,33 +73,17 @@ namespace Gendarme.Rules.Interoperability.Com {
15868 foreach (TypeDefinition type in module.GetAllTypes ()) {
15869 if (!type.IsInterface)
15870 continue;
15871- interfaces.Add (type);
15872+ interfaces.Add (type.GetFullName (), type);
15873 }
15874 }
15875 }
15876 }
15877
15878- // Find a TypeDefinition for an interface with the given name.
15879- private TypeDefinition FindInterfaceDefinition (string fullName)
15880- {
15881- foreach (var def in interfaces)
15882- if (fullName == def.FullName)
15883- return def;
15884- return null;
15885- }
15886-
15887 // Finds a CustomAttribute on a type from the given name.
15888- private static CustomAttribute FindComAttribute (ICustomAttributeProvider type, string name)
15889+ private static CustomAttribute FindCustomAttribute (ICustomAttributeProvider type, string nameSpace, string name)
15890 {
15891 foreach (var attribute in type.CustomAttributes) {
15892- if (!attribute.HasConstructorArguments)
15893- continue;
15894-
15895- TypeReference atype = attribute.AttributeType;
15896- if (atype.Namespace != "System.Runtime.InteropServices")
15897- continue;
15898-
15899- if (atype.Name == name)
15900+ if (attribute.AttributeType.IsNamed (nameSpace, name))
15901 return attribute;
15902 }
15903 return null;
15904@@ -115,7 +99,8 @@ namespace Gendarme.Rules.Interoperability.Com {
15905 Runner.Report (def, Severity.High, Confidence.Total, "No attributes are present on a specified interface");
15906 return;
15907 }
15908- var attribute = FindComAttribute (def, "InterfaceTypeAttribute");
15909+
15910+ var attribute = FindCustomAttribute (def, "System.Runtime.InteropServices", "InterfaceTypeAttribute");
15911 if (attribute == null) {
15912 Runner.Report (def, Severity.High, Confidence.Total, "No [InterfaceType] attribute is present on a specified interface");
15913 return;
15914@@ -129,7 +114,9 @@ namespace Gendarme.Rules.Interoperability.Com {
15915
15916 private void CheckInterface (string interface_name)
15917 {
15918- CheckInterface (FindInterfaceDefinition (interface_name));
15919+ TypeDefinition td;
15920+ if (interfaces.TryGetValue (interface_name, out td))
15921+ CheckInterface (td);
15922 }
15923
15924 public override void Initialize (IRunner runner)
15925@@ -145,7 +132,7 @@ namespace Gendarme.Rules.Interoperability.Com {
15926 if (!type.IsClass || !type.HasCustomAttributes)
15927 return RuleResult.DoesNotApply;
15928
15929- var attribute = FindComAttribute (type, "ComSourceInterfacesAttribute");
15930+ var attribute = FindCustomAttribute (type, "System.Runtime.InteropServices", "ComSourceInterfacesAttribute");
15931 if (attribute == null)
15932 return RuleResult.DoesNotApply;
15933 // The attribute's paramemters may be a single null-delimited string, or up to four System.Types.
15934diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/README.md b/gendarme/rules/Gendarme.Rules.Interoperability.Com/README.md
15935new file mode 100644
15936index 0000000..af988cb
15937--- /dev/null
15938+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/README.md
15939@@ -0,0 +1,9 @@
15940+# Gendarme.Rules.Interoperability.Com Rules
15941+
15942+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Interoperability.Com(git)]] pages.
15943+
15944+
15945+## Feedback
15946+
15947+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
15948+
15949diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ReviewComRegistrationMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ReviewComRegistrationMethodsRule.cs
15950index b46b390..2a5679d 100644
15951--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ReviewComRegistrationMethodsRule.cs
15952+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ReviewComRegistrationMethodsRule.cs
15953@@ -94,9 +94,6 @@ namespace Gendarme.Rules.Interoperability.Com {
15954 [FxCopCompatibility ("Microsoft.Interoperability", "CA1411:ComRegistrationMethodsShouldNotBeVisible")]
15955 public class ReviewComRegistrationMethodsRule : Rule, ITypeRule {
15956
15957- const string comRegister = "System.Runtime.InteropServices.ComRegisterFunctionAttribute";
15958- const string comUnregister = "System.Runtime.InteropServices.ComUnregisterFunctionAttribute";
15959-
15960 public RuleResult CheckType (TypeDefinition type)
15961 {
15962 if (type.HasGenericParameters || !type.IsVisible () || !type.IsTypeComVisible ())
15963@@ -111,12 +108,12 @@ namespace Gendarme.Rules.Interoperability.Com {
15964
15965 bool foundRegisterUnregisterMethod = false; // method level variable
15966 foreach (CustomAttribute attribute in method.CustomAttributes) {
15967- var name = attribute.AttributeType.FullName;
15968- if (!foundRegister && name == comRegister) {
15969+ TypeReference atype = attribute.AttributeType;
15970+ if (!foundRegister && atype.IsNamed ("System.Runtime.InteropServices", "ComRegisterFunctionAttribute")) {
15971 foundRegister = true;
15972 foundRegisterUnregisterMethod = true;
15973 }
15974- if (!foundUnregister && name == comUnregister) {
15975+ if (!foundUnregister && atype.IsNamed ("System.Runtime.InteropServices", "ComUnregisterFunctionAttribute")) {
15976 foundUnregister = true;
15977 foundRegisterUnregisterMethod = true;
15978 }
15979diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AutoLayoutTypesShouldNotBeComVisibleTest.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AutoLayoutTypesShouldNotBeComVisibleTest.cs
15980index 5cf9e05..3e8e282 100644
15981--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AutoLayoutTypesShouldNotBeComVisibleTest.cs
15982+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AutoLayoutTypesShouldNotBeComVisibleTest.cs
15983@@ -137,5 +137,23 @@ namespace Test.Rules.Interoperability.Com {
15984 AssertRuleDoesNotApply (SimpleTypes.Structure);
15985
15986 }
15987+
15988+ [ComVisible (true)]
15989+ public enum Enum {
15990+ Zero = 0
15991+ }
15992+
15993+ [Flags]
15994+ [ComVisible (true)]
15995+ public enum Flags {
15996+ One = 1
15997+ }
15998+
15999+ [Test]
16000+ public void SpecialCases ()
16001+ {
16002+ AssertRuleDoesNotApply<Enum> ();
16003+ AssertRuleDoesNotApply<Flags> ();
16004+ }
16005 }
16006 }
16007diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AvoidStaticMembersInComVisibleTypesTest.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AvoidStaticMembersInComVisibleTypesTest.cs
16008index 191eb2a..a4dbbc2 100644
16009--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AvoidStaticMembersInComVisibleTypesTest.cs
16010+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AvoidStaticMembersInComVisibleTypesTest.cs
16011@@ -42,7 +42,7 @@ namespace Test.Rules.Interoperability.Com {
16012 public class AvoidStaticMembersInComVisibleTypesTest : MethodRuleTestFixture<AvoidStaticMembersInComVisibleTypesRule> {
16013
16014 [ComVisible (true)]
16015- class ComVisibleClass {
16016+ public class ComVisibleClass {
16017 public static void Bad ()
16018 {
16019 }
16020@@ -103,20 +103,20 @@ namespace Test.Rules.Interoperability.Com {
16021 }
16022
16023 [ComVisible (false)]
16024- class ComInvisibleClass {
16025+ public class ComInvisibleClass {
16026 public static void DoesNotApply ()
16027 {
16028 }
16029 }
16030
16031- class NoAttributesClass {
16032+ public class NoAttributesClass {
16033 public static void DoesNotApply ()
16034 {
16035 }
16036 }
16037
16038 [ComVisible (true)]
16039- interface Interface {
16040+ public interface Interface {
16041 void DoesNotApply ();
16042 }
16043
16044diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/ComVisibleShouldInheritFromComVisibleTest.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/ComVisibleShouldInheritFromComVisibleTest.cs
16045index 4613f87..ec721ad 100644
16046--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/ComVisibleShouldInheritFromComVisibleTest.cs
16047+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/ComVisibleShouldInheritFromComVisibleTest.cs
16048@@ -27,6 +27,7 @@
16049 //
16050
16051 using System;
16052+using System.Collections;
16053 using System.Runtime.InteropServices;
16054
16055 using Mono.Cecil;
16056@@ -57,6 +58,10 @@ namespace Test.Rules.Interoperability.Com {
16057 public class ComVisibleInheritsFromInvisibleClass : ComInvisibleClass {
16058 }
16059
16060+ [ComVisible (true)]
16061+ class NotReallyComVisibleInheritsFromInvisibleClass : ComInvisibleClass {
16062+ }
16063+
16064 [ComVisible (false)]
16065 public class ComInvisibleInheritsFromVisibleClass : ComVisibleClass {
16066 }
16067@@ -64,9 +69,6 @@ namespace Test.Rules.Interoperability.Com {
16068 [Test]
16069 public void Good ()
16070 {
16071- // no ComVisible attributes in inheritance chain
16072- AssertRuleSuccess (SimpleTypes.Class);
16073-
16074 AssertRuleSuccess<ComVisibleClass> ();
16075 }
16076
16077@@ -79,8 +81,15 @@ namespace Test.Rules.Interoperability.Com {
16078 [Test]
16079 public void DoesNotApply ()
16080 {
16081+ // BaseType is null
16082+ AssertRuleDoesNotApply<ICollection> ();
16083+
16084+ // not visible / no ComVisible attributes in inheritance chain
16085+ AssertRuleDoesNotApply (SimpleTypes.Class);
16086+
16087 AssertRuleDoesNotApply<ComInvisibleClass> ();
16088 AssertRuleDoesNotApply<ComInvisibleInheritsFromVisibleClass> ();
16089+ AssertRuleDoesNotApply<NotReallyComVisibleInheritsFromInvisibleClass> ();
16090 }
16091 }
16092 }
16093diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/DoNotUseAutoDualClassInterfaceTypeTest.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/DoNotUseAutoDualClassInterfaceTypeTest.cs
16094index ad6b8f3..b68c36a 100644
16095--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/DoNotUseAutoDualClassInterfaceTypeTest.cs
16096+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/DoNotUseAutoDualClassInterfaceTypeTest.cs
16097@@ -43,30 +43,30 @@ namespace Test.Rules.Interoperability.Com {
16098
16099 [ComVisible (true)]
16100 [ClassInterface (ClassInterfaceType.AutoDual)]
16101- class BadClass {
16102+ public class BadClass {
16103 // do something
16104 }
16105
16106 [ComVisible (true)]
16107 [ClassInterface (2)]
16108- class BadClassShortConstuctor {
16109+ public class BadClassShortConstuctor {
16110 // do something
16111 }
16112
16113 [ComVisible (false)]
16114 [ClassInterface (ClassInterfaceType.AutoDual)]
16115- class DoesNotApplyInvisible {
16116+ public class DoesNotApplyInvisible {
16117 // do something
16118 }
16119
16120 [ComVisible (true)]
16121- class GoodNoInterfaceAttribute {
16122+ public class GoodNoInterfaceAttribute {
16123 // do something
16124 }
16125
16126 [ComVisible (true)]
16127 [ClassInterface (ClassInterfaceType.None)]
16128- class GoodClassNone : ICloneable {
16129+ public class GoodClassNone : ICloneable {
16130 public object Clone ()
16131 {
16132 return new object ();
16133@@ -75,7 +75,7 @@ namespace Test.Rules.Interoperability.Com {
16134
16135 [ComVisible (true)]
16136 [ClassInterface ((short)0)]
16137- class GoodClassNoneShortConstructor : ICloneable {
16138+ public class GoodClassNoneShortConstructor : ICloneable {
16139 public object Clone ()
16140 {
16141 return new object ();
16142diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/Tests.Rules.Interoperability.Com.csproj b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/Tests.Rules.Interoperability.Com.csproj
16143index 0b77953..7f21629 100755
16144--- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/Tests.Rules.Interoperability.Com.csproj
16145+++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/Tests.Rules.Interoperability.Com.csproj
16146@@ -1,85 +1,124 @@
16147-<?xml version="1.0" encoding="utf-8"?>
16148-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
16149- <PropertyGroup>
16150- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
16151- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
16152- <ProductVersion>9.0.30729</ProductVersion>
16153- <SchemaVersion>2.0</SchemaVersion>
16154- <ProjectGuid>{393FCDDA-6AAF-4DBA-BB75-6BD85DAC84EE}</ProjectGuid>
16155- <OutputType>Library</OutputType>
16156- <AppDesignerFolder>Properties</AppDesignerFolder>
16157- <RootNamespace>Tests.Rules.Interoperability.Com</RootNamespace>
16158- <AssemblyName>Tests.Rules.Interoperability.Com</AssemblyName>
16159- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
16160- <FileAlignment>512</FileAlignment>
16161- </PropertyGroup>
16162- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
16163- <DebugSymbols>true</DebugSymbols>
16164- <DebugType>full</DebugType>
16165- <Optimize>false</Optimize>
16166- <OutputPath>bin\Debug\</OutputPath>
16167- <DefineConstants>DEBUG;TRACE</DefineConstants>
16168- <ErrorReport>prompt</ErrorReport>
16169- <WarningLevel>4</WarningLevel>
16170- </PropertyGroup>
16171- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
16172- <DebugType>pdbonly</DebugType>
16173- <Optimize>true</Optimize>
16174- <OutputPath>bin\Release\</OutputPath>
16175- <DefineConstants>TRACE</DefineConstants>
16176- <ErrorReport>prompt</ErrorReport>
16177- <WarningLevel>4</WarningLevel>
16178- </PropertyGroup>
16179- <ItemGroup>
16180- <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
16181- <SpecificVersion>False</SpecificVersion>
16182- <HintPath>..\..\..\..\..\cecil\Test\libs\nunit-2.4.8\nunit.framework.dll</HintPath>
16183- </Reference>
16184- <Reference Include="System" />
16185- <Reference Include="System.Core">
16186- <RequiredTargetFramework>3.5</RequiredTargetFramework>
16187- </Reference>
16188- </ItemGroup>
16189- <ItemGroup>
16190- <ProjectReference Include="..\..\..\..\..\cecil\Mono.Cecil.csproj">
16191- <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>
16192- <Name>Mono.Cecil</Name>
16193- </ProjectReference>
16194- <ProjectReference Include="..\..\..\framework\Gendarme.Framework.csproj">
16195- <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>
16196- <Name>Gendarme.Framework</Name>
16197- </ProjectReference>
16198- <ProjectReference Include="..\..\Test.Rules\Test.Rules.csproj">
16199- <Project>{069148AF-86AB-4EE3-BFB9-429AE722461F}</Project>
16200- <Name>Test.Rules</Name>
16201- </ProjectReference>
16202- <ProjectReference Include="..\Gendarme.Rules.Interoperability.Com.csproj">
16203- <Project>{468F7043-C0D5-480F-88A1-A262EC324E5E}</Project>
16204- <Name>Gendarme.Rules.Interoperability.Com</Name>
16205- </ProjectReference>
16206- </ItemGroup>
16207- <ItemGroup>
16208- <Compile Include="AutoLayoutTypesShouldNotBeComVisibleTest.cs" />
16209- <Compile Include="AvoidInt64ArgumentsInComVisibleMethodsTest.cs" />
16210- <Compile Include="AvoidNonPublicFieldsInComVisibleValueTypesTest.cs" />
16211- <Compile Include="AvoidOverloadsInComVisibleInterfacesTest.cs" />
16212- <Compile Include="AvoidStaticMembersInComVisibleTypesTest.cs" />
16213- <Compile Include="ComRocksTest.cs" />
16214- <Compile Include="ComVisibleShouldInheritFromComVisibleTest.cs" />
16215- <Compile Include="ComVisibleTypesShouldBeCreatableTest.cs" />
16216- <Compile Include="DoNotUseAutoDualClassInterfaceTypeTest.cs" />
16217- <Compile Include="MarkComSourceInterfacesAsIDispatchTest.cs" />
16218- <Compile Include="ReviewComRegistrationMethodsTest.cs" />
16219- </ItemGroup>
16220- <ItemGroup>
16221- <Folder Include="Properties\" />
16222- </ItemGroup>
16223- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
16224+<?xml version="1.0" encoding="utf-8"?>\r
16225+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
16226+ <PropertyGroup>\r
16227+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
16228+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
16229+ <ProductVersion>9.0.30729</ProductVersion>\r
16230+ <SchemaVersion>2.0</SchemaVersion>\r
16231+ <ProjectGuid>{393FCDDA-6AAF-4DBA-BB75-6BD85DAC84EE}</ProjectGuid>\r
16232+ <OutputType>Library</OutputType>\r
16233+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
16234+ <RootNamespace>Tests.Rules.Interoperability.Com</RootNamespace>\r
16235+ <AssemblyName>Tests.Rules.Interoperability.Com</AssemblyName>\r
16236+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
16237+ <FileAlignment>512</FileAlignment>\r
16238+ <FileUpgradeFlags>\r
16239+ </FileUpgradeFlags>\r
16240+ <OldToolsVersion>3.5</OldToolsVersion>\r
16241+ <UpgradeBackupLocation />\r
16242+ <PublishUrl>publish\</PublishUrl>\r
16243+ <Install>true</Install>\r
16244+ <InstallFrom>Disk</InstallFrom>\r
16245+ <UpdateEnabled>false</UpdateEnabled>\r
16246+ <UpdateMode>Foreground</UpdateMode>\r
16247+ <UpdateInterval>7</UpdateInterval>\r
16248+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
16249+ <UpdatePeriodically>false</UpdatePeriodically>\r
16250+ <UpdateRequired>false</UpdateRequired>\r
16251+ <MapFileExtensions>true</MapFileExtensions>\r
16252+ <ApplicationRevision>0</ApplicationRevision>\r
16253+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
16254+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
16255+ <UseApplicationTrust>false</UseApplicationTrust>\r
16256+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
16257+ <TargetFrameworkProfile />\r
16258+ </PropertyGroup>\r
16259+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
16260+ <DebugSymbols>true</DebugSymbols>\r
16261+ <DebugType>full</DebugType>\r
16262+ <Optimize>false</Optimize>\r
16263+ <OutputPath>bin\Debug\</OutputPath>\r
16264+ <DefineConstants>DEBUG;TRACE</DefineConstants>\r
16265+ <ErrorReport>prompt</ErrorReport>\r
16266+ <WarningLevel>4</WarningLevel>\r
16267+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
16268+ </PropertyGroup>\r
16269+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
16270+ <DebugType>pdbonly</DebugType>\r
16271+ <Optimize>true</Optimize>\r
16272+ <OutputPath>bin\Release\</OutputPath>\r
16273+ <DefineConstants>TRACE</DefineConstants>\r
16274+ <ErrorReport>prompt</ErrorReport>\r
16275+ <WarningLevel>4</WarningLevel>\r
16276+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
16277+ </PropertyGroup>\r
16278+ <ItemGroup>\r
16279+ <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
16280+ <SpecificVersion>False</SpecificVersion>\r
16281+ <HintPath>..\..\..\..\..\cecil\Test\libs\nunit-2.4.8\nunit.framework.dll</HintPath>\r
16282+ </Reference>\r
16283+ <Reference Include="System" />\r
16284+ <Reference Include="System.Core">\r
16285+ <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
16286+ </Reference>\r
16287+ </ItemGroup>\r
16288+ <ItemGroup>\r
16289+ <ProjectReference Include="..\..\..\..\..\cecil\Mono.Cecil.csproj">\r
16290+ <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
16291+ <Name>Mono.Cecil</Name>\r
16292+ </ProjectReference>\r
16293+ <ProjectReference Include="..\..\..\framework\Gendarme.Framework.csproj">\r
16294+ <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>\r
16295+ <Name>Gendarme.Framework</Name>\r
16296+ </ProjectReference>\r
16297+ <ProjectReference Include="..\..\Test.Rules\Test.Rules.csproj">\r
16298+ <Project>{069148AF-86AB-4EE3-BFB9-429AE722461F}</Project>\r
16299+ <Name>Test.Rules</Name>\r
16300+ </ProjectReference>\r
16301+ <ProjectReference Include="..\Gendarme.Rules.Interoperability.Com.csproj">\r
16302+ <Project>{468F7043-C0D5-480F-88A1-A262EC324E5E}</Project>\r
16303+ <Name>Gendarme.Rules.Interoperability.Com</Name>\r
16304+ </ProjectReference>\r
16305+ </ItemGroup>\r
16306+ <ItemGroup>\r
16307+ <Compile Include="AutoLayoutTypesShouldNotBeComVisibleTest.cs" />\r
16308+ <Compile Include="AvoidInt64ArgumentsInComVisibleMethodsTest.cs" />\r
16309+ <Compile Include="AvoidNonPublicFieldsInComVisibleValueTypesTest.cs" />\r
16310+ <Compile Include="AvoidOverloadsInComVisibleInterfacesTest.cs" />\r
16311+ <Compile Include="AvoidStaticMembersInComVisibleTypesTest.cs" />\r
16312+ <Compile Include="ComRocksTest.cs" />\r
16313+ <Compile Include="ComVisibleShouldInheritFromComVisibleTest.cs" />\r
16314+ <Compile Include="ComVisibleTypesShouldBeCreatableTest.cs" />\r
16315+ <Compile Include="DoNotUseAutoDualClassInterfaceTypeTest.cs" />\r
16316+ <Compile Include="MarkComSourceInterfacesAsIDispatchTest.cs" />\r
16317+ <Compile Include="ReviewComRegistrationMethodsTest.cs" />\r
16318+ </ItemGroup>\r
16319+ <ItemGroup>\r
16320+ <Folder Include="Properties\" />\r
16321+ </ItemGroup>\r
16322+ <ItemGroup>\r
16323+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
16324+ <Visible>False</Visible>\r
16325+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
16326+ <Install>false</Install>\r
16327+ </BootstrapperPackage>\r
16328+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
16329+ <Visible>False</Visible>\r
16330+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
16331+ <Install>true</Install>\r
16332+ </BootstrapperPackage>\r
16333+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
16334+ <Visible>False</Visible>\r
16335+ <ProductName>Windows Installer 3.1</ProductName>\r
16336+ <Install>true</Install>\r
16337+ </BootstrapperPackage>\r
16338+ </ItemGroup>\r
16339+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
16340 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
16341 Other similar extension points exist, see Microsoft.Common.targets.
16342 <Target Name="BeforeBuild">
16343 </Target>
16344 <Target Name="AfterBuild">
16345 </Target>
16346- -->
16347+ -->\r
16348 </Project>
16349\ No newline at end of file
16350diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/CentralizePInvokesIntoNativeMethodsTypeRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/CentralizePInvokesIntoNativeMethodsTypeRule.cs
16351index fbadfc9..26d1dca 100644
16352--- a/gendarme/rules/Gendarme.Rules.Interoperability/CentralizePInvokesIntoNativeMethodsTypeRule.cs
16353+++ b/gendarme/rules/Gendarme.Rules.Interoperability/CentralizePInvokesIntoNativeMethodsTypeRule.cs
16354@@ -27,6 +27,7 @@
16355 //
16356
16357 using System;
16358+using System.Globalization;
16359
16360 using Mono.Cecil;
16361
16362@@ -91,20 +92,22 @@ namespace Gendarme.Rules.Interoperability {
16363 {
16364 // *NativeMethods types should never be visible outside the assembly
16365 if (type.IsVisible ()) {
16366- string msg = String.Format ("'{0}' should not be visible outside the assembly.", type);
16367+ string msg = String.Format (CultureInfo.InvariantCulture,
16368+ "'{0}' should not be visible outside the assembly.", type.GetFullName ());
16369 Runner.Report (type, Severity.High, Confidence.Total, msg);
16370 }
16371
16372 if (CanInstantiateType (type)) {
16373- string msg = String.Format ("'{0}' should not be static or sealed with no visible constructor.", type);
16374+ string msg = String.Format (CultureInfo.InvariantCulture,
16375+ "'{0}' should not be static or sealed with no visible constructor.", type.GetFullName ());
16376 Runner.Report (type, Severity.High, Confidence.Total, msg);
16377 }
16378 }
16379
16380- private void CheckSuppressUnmanagedCodeSecurity (TypeDefinition type, bool required)
16381+ private void CheckSuppressUnmanagedCodeSecurity (ICustomAttributeProvider type, bool required)
16382 {
16383 string msg = null;
16384- if (type.HasCustomAttributes && type.CustomAttributes.ContainsType ("System.Security.SuppressUnmanagedCodeSecurityAttribute")) {
16385+ if (type.HasAttribute ("System.Security", "SuppressUnmanagedCodeSecurityAttribute")) {
16386 if (!required)
16387 msg = "Remove [SuppressUnmanagedCodeSecurity] attribute on the type declaration.";
16388 } else {
16389diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule.cs
16390index a407980..72b8ffc 100644
16391--- a/gendarme/rules/Gendarme.Rules.Interoperability/DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule.cs
16392+++ b/gendarme/rules/Gendarme.Rules.Interoperability/DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule.cs
16393@@ -32,6 +32,7 @@
16394 using System;
16395 using System.Collections.Generic;
16396 using System.Diagnostics;
16397+using System.Globalization;
16398
16399 using Mono.Cecil;
16400 using Mono.Cecil.Cil;
16401@@ -259,7 +260,7 @@ namespace Gendarme.Rules.Interoperability {
16402 // Pending implementation of "analysis warnings", as mentioned here (post #21):
16403 // http://groups.google.com/group/gendarme/browse_frm/thread/c37d157ae0c9682/57f89f3abf14f2fd?tvc=1&q=Gendarme+2.6+Preview+1+is+ready+for+download#57f89f3abf14f2fd
16404 Runner.Report (method, Severity.Low, Confidence.Low,
16405- string.Format ("An exception occurred while verifying this method. " +
16406+ String.Format (CultureInfo.CurrentCulture, "An exception occurred while verifying this method. " +
16407 "This failure can probably be ignored, it's most likely due to an " +
16408 "uncommon code sequence in the method the rule didn't understand. {0}", ex.Message));
16409 return RuleResult.Failure;
16410@@ -271,14 +272,14 @@ namespace Gendarme.Rules.Interoperability {
16411 locals.Clear ();
16412 stack.Clear ();
16413
16414- Log.WriteLine (this, "\n\nChecking method: {0} on type: {1}", method.Name, method.DeclaringType.FullName);
16415+ Log.WriteLine (this, "\n\nChecking method: {0} on type: {1}", method.Name, method.DeclaringType.GetFullName ());
16416 Log.WriteLine (this, method);
16417
16418 MethodBody body = method.Body;
16419 #if DEBUG
16420 foreach (ExceptionHandler e in body.ExceptionHandlers)
16421- Log.WriteLine (this, " HandlerType: {7}, TryStart: {4:X}, TryEnd: {5:X}, HandlerStart: {0:X}, HandlerEnd: {1:X}, FilterStart: {2:X}, FilterEnd: {3:X}, CatchType: {6}",
16422- e.HandlerStart.GetOffset (), e.HandlerEnd.GetOffset (), e.FilterStart.GetOffset (), e.FilterEnd.GetOffset (),
16423+ Log.WriteLine (this, " HandlerType: {6}, TryStart: {3:X}, TryEnd: {4:X}, HandlerStart: {0:X}, HandlerEnd: {1:X}, FilterStart: {2:X}, CatchType: {5}",
16424+ e.HandlerStart.GetOffset (), e.HandlerEnd.GetOffset (), e.FilterStart.GetOffset (),
16425 e.TryStart.GetOffset (), e.TryEnd.GetOffset (), e.CatchType, e.HandlerType);
16426 #endif
16427
16428@@ -493,12 +494,12 @@ namespace Gendarme.Rules.Interoperability {
16429 continue;
16430
16431 // no 'Catch ... When <condition>' clause. C# doesn't support it, VB does
16432- if (eh.FilterStart != null || eh.FilterEnd != null)
16433+ if (eh.FilterStart != null)
16434 continue;
16435
16436 // check for catch all clauses
16437- string exception_typename = eh.CatchType == null ? null : eh.CatchType.FullName;
16438- if (!(exception_typename == null || exception_typename == "System.Object" || exception_typename == "System.Exception"))
16439+ TypeReference ctype = eh.CatchType;
16440+ if (!(ctype == null || ctype.IsNamed ("System", "Object") || ctype.IsNamed ("System", "Exception")))
16441 continue;
16442
16443 // Mark the code this exception handler handles as safe.
16444@@ -521,8 +522,8 @@ namespace Gendarme.Rules.Interoperability {
16445 // Console.ResetColor ();
16446 }
16447 foreach (ExceptionHandler e in body.ExceptionHandlers)
16448- Log.WriteLine (this, " HandlerType: {7}, TryStart: {4}, TryEnd: {5}, HandlerStart: {0}, HandlerEnd: {1}, FilterStart: {2}, FilterEnd: {3}, CatchType: {6}",
16449- e.HandlerStart.GetOffset (), e.HandlerEnd.GetOffset (), e.FilterStart.GetOffset (), e.FilterEnd.GetOffset (),
16450+ Log.WriteLine (this, " HandlerType: {6}, TryStart: {3}, TryEnd: {4}, HandlerStart: {0}, HandlerEnd: {1}, FilterStart: {2}, CatchType: {5}",
16451+ e.HandlerStart.GetOffset (), e.HandlerEnd.GetOffset (), e.FilterStart.GetOffset (),
16452 e.TryStart.GetOffset (), e.TryEnd.GetOffset (), e.CatchType, e.HandlerType);
16453 #endif
16454
16455@@ -665,7 +666,8 @@ namespace Gendarme.Rules.Interoperability {
16456 case Code.Ldloca_S:
16457 case Code.Ldloc_S: return ((VariableDefinition) ins.Operand).Index;
16458 default:
16459- throw new ArgumentException (string.Format ("Invalid opcode: {0}", ins.OpCode.Name));
16460+ string msg = String.Format (CultureInfo.InvariantCulture, "Invalid opcode: {0}", ins.OpCode.Name);
16461+ throw new ArgumentException (msg);
16462 }
16463 }
16464
16465@@ -681,7 +683,8 @@ namespace Gendarme.Rules.Interoperability {
16466 case Code.Stloc: // Untested for stloc
16467 case Code.Stloc_S: return ((VariableDefinition) ins.Operand).Index;
16468 default:
16469- throw new ArgumentException (string.Format ("Invalid opcode: {0}", ins.OpCode.Name));
16470+ string msg = String.Format (CultureInfo.InvariantCulture, "Invalid opcode: {0}", ins.OpCode.Name);
16471+ throw new ArgumentException (msg);
16472 }
16473 }
16474 }
16475diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/DoNotCastIntPtrToInt32Rule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/DoNotCastIntPtrToInt32Rule.cs
16476index 908fb83..6e2f0d6 100644
16477--- a/gendarme/rules/Gendarme.Rules.Interoperability/DoNotCastIntPtrToInt32Rule.cs
16478+++ b/gendarme/rules/Gendarme.Rules.Interoperability/DoNotCastIntPtrToInt32Rule.cs
16479@@ -27,6 +27,7 @@
16480 //
16481
16482 using System;
16483+using System.Globalization;
16484
16485 using Mono.Cecil;
16486 using Mono.Cecil.Cil;
16487@@ -87,7 +88,7 @@ namespace Gendarme.Rules.Interoperability {
16488
16489 private void Report (MethodDefinition method, Instruction ins, string typeName)
16490 {
16491- string msg = String.Format ("Type cast to '{0}'.", typeName);
16492+ string msg = String.Format (CultureInfo.InvariantCulture, "Type cast to '{0}'.", typeName);
16493 Runner.Report (method, ins, Severity.High, Confidence.Normal, msg);
16494 }
16495
16496@@ -130,7 +131,7 @@ namespace Gendarme.Rules.Interoperability {
16497 } else if (uintptr && (name == "ToUInt32")) {
16498 Runner.Report (method, ins, Severity.High, Confidence.Normal, "Call to 'UIntPtr.ToUInt32()'.");
16499 } else if (name == "op_Explicit") {
16500- string rtfullname = mr.ReturnType.FullName;
16501+ string rtfullname = mr.ReturnType.GetFullName ();
16502 switch (rtfullname) {
16503 case "System.Int64":
16504 case "System.UInt64":
16505@@ -165,8 +166,9 @@ namespace Gendarme.Rules.Interoperability {
16506 if (m.Name != "op_Explicit")
16507 return;
16508
16509- string msg = String.Format ("A '{0}' value is casted into an '{1}' when reading marshalled memory.",
16510- mr.ReturnType.FullName, m.Parameters [0].ParameterType.FullName);
16511+ string msg = String.Format (CultureInfo.InvariantCulture,
16512+ "A '{0}' value is casted into an '{1}' when reading marshalled memory.",
16513+ mr.ReturnType.GetFullName (), m.Parameters [0].ParameterType.GetFullName ());
16514 Runner.Report (method, ins, Severity.High, Confidence.Normal, msg);
16515 }
16516 }
16517@@ -190,12 +192,14 @@ namespace Gendarme.Rules.Interoperability {
16518 continue;
16519
16520 // look for both IntPtr and the (less known) UIntPtr
16521- string type = mr.DeclaringType.FullName;
16522- bool intptr = (type == "System.IntPtr");
16523- bool uintptr = (type == "System.UIntPtr");
16524- if (intptr || uintptr) {
16525- CheckCastOnIntPtr (method, ins, mr, intptr, uintptr);
16526- } else if (type == "System.Runtime.InteropServices.Marshal") {
16527+ TypeReference type = mr.DeclaringType;
16528+ if (type.Namespace == "System") {
16529+ string name = type.Name;
16530+ bool intptr = (name == "IntPtr");
16531+ bool uintptr = (name == "UIntPtr");
16532+ if (intptr || uintptr)
16533+ CheckCastOnIntPtr (method, ins, mr, intptr, uintptr);
16534+ } else if (type.IsNamed ("System.Runtime.InteropServices", "Marshal")) {
16535 CheckCastOnMarshal (method, ins, mr);
16536 }
16537 }
16538diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/Gendarme.Rules.Interoperability.csproj b/gendarme/rules/Gendarme.Rules.Interoperability/Gendarme.Rules.Interoperability.csproj
16539index 04cd1c6..1b0a126 100755
16540--- a/gendarme/rules/Gendarme.Rules.Interoperability/Gendarme.Rules.Interoperability.csproj
16541+++ b/gendarme/rules/Gendarme.Rules.Interoperability/Gendarme.Rules.Interoperability.csproj
16542@@ -1,5 +1,5 @@
16543 <?xml version="1.0" encoding="utf-8"?>\r
16544-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
16545+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
16546 <PropertyGroup>\r
16547 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
16548 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
16549@@ -10,8 +10,28 @@
16550 <AppDesignerFolder>Properties</AppDesignerFolder>\r
16551 <RootNamespace>Gendarme.Rules.Interoperability</RootNamespace>\r
16552 <AssemblyName>Gendarme.Rules.Interoperability</AssemblyName>\r
16553- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
16554+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
16555 <FileAlignment>512</FileAlignment>\r
16556+ <FileUpgradeFlags>\r
16557+ </FileUpgradeFlags>\r
16558+ <OldToolsVersion>3.5</OldToolsVersion>\r
16559+ <UpgradeBackupLocation />\r
16560+ <PublishUrl>publish\</PublishUrl>\r
16561+ <Install>true</Install>\r
16562+ <InstallFrom>Disk</InstallFrom>\r
16563+ <UpdateEnabled>false</UpdateEnabled>\r
16564+ <UpdateMode>Foreground</UpdateMode>\r
16565+ <UpdateInterval>7</UpdateInterval>\r
16566+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
16567+ <UpdatePeriodically>false</UpdatePeriodically>\r
16568+ <UpdateRequired>false</UpdateRequired>\r
16569+ <MapFileExtensions>true</MapFileExtensions>\r
16570+ <ApplicationRevision>0</ApplicationRevision>\r
16571+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
16572+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
16573+ <UseApplicationTrust>false</UseApplicationTrust>\r
16574+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
16575+ <TargetFrameworkProfile />\r
16576 </PropertyGroup>\r
16577 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
16578 <DebugSymbols>true</DebugSymbols>\r
16579@@ -24,6 +44,7 @@
16580 <NoWarn>1591</NoWarn>\r
16581 <WarningsAsErrors>1570</WarningsAsErrors>\r
16582 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Interoperability.xml</DocumentationFile>\r
16583+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
16584 </PropertyGroup>\r
16585 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
16586 <DebugType>pdbonly</DebugType>\r
16587@@ -35,6 +56,7 @@
16588 <NoWarn>1591</NoWarn>\r
16589 <WarningsAsErrors>1570</WarningsAsErrors>\r
16590 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Interoperability.xml</DocumentationFile>\r
16591+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
16592 </PropertyGroup>\r
16593 <ItemGroup>\r
16594 <Reference Include="System" />\r
16595@@ -65,6 +87,23 @@
16596 <Name>Gendarme.Framework</Name>\r
16597 </ProjectReference>\r
16598 </ItemGroup>\r
16599+ <ItemGroup>\r
16600+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
16601+ <Visible>False</Visible>\r
16602+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
16603+ <Install>false</Install>\r
16604+ </BootstrapperPackage>\r
16605+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
16606+ <Visible>False</Visible>\r
16607+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
16608+ <Install>true</Install>\r
16609+ </BootstrapperPackage>\r
16610+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
16611+ <Visible>False</Visible>\r
16612+ <ProductName>Windows Installer 3.1</ProductName>\r
16613+ <Install>true</Install>\r
16614+ </BootstrapperPackage>\r
16615+ </ItemGroup>\r
16616 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
16617 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
16618 Other similar extension points exist, see Microsoft.Common.targets.\r
16619diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/GetLastErrorMustBeCalledRightAfterPInvokeRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/GetLastErrorMustBeCalledRightAfterPInvokeRule.cs
16620index 39cb63f..37b5dad 100644
16621--- a/gendarme/rules/Gendarme.Rules.Interoperability/GetLastErrorMustBeCalledRightAfterPInvokeRule.cs
16622+++ b/gendarme/rules/Gendarme.Rules.Interoperability/GetLastErrorMustBeCalledRightAfterPInvokeRule.cs
16623@@ -98,9 +98,9 @@ namespace Gendarme.Rules.Interoperability {
16624 return false;
16625 }
16626
16627- public bool Equals (Branch branch)
16628+ public bool Equals (Branch other)
16629 {
16630- return (Instruction == branch.Instruction) && (DirtyMethodCalled == branch.DirtyMethodCalled);
16631+ return (Instruction == other.Instruction) && (DirtyMethodCalled == other.DirtyMethodCalled);
16632 }
16633
16634 public override int GetHashCode ()
16635@@ -135,13 +135,18 @@ namespace Gendarme.Rules.Interoperability {
16636
16637 //check if a method is called
16638 if (ins.OpCode.FlowControl == FlowControl.Call) {
16639+ MethodReference mRef = ins.Operand as MethodReference;
16640
16641- MethodDefinition mDef = (ins.Operand as MethodReference).Resolve ();
16642+ if (mRef == null) {
16643+ continue;
16644+ }
16645+
16646+ MethodDefinition mDef = mRef.Resolve();
16647 if (mDef != null && mDef.IsPInvokeImpl) { //check if another pinvoke method is called, this counts as "GetLastError not called"
16648 break;
16649 }
16650-
16651- string s = (mDef == null) ? String.Empty : mDef.DeclaringType.FullName;
16652+
16653+ string s = (mDef == null) ? String.Empty : mDef.DeclaringType.GetFullName ();
16654 switch (s) {
16655 case "System.Runtime.InteropServices.Marshal":
16656 getLastErrorFound = (mDef.Name == "GetLastWin32Error");
16657diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/MarshalBooleansInPInvokeDeclarationsRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/MarshalBooleansInPInvokeDeclarationsRule.cs
16658index 588748a..acf7156 100644
16659--- a/gendarme/rules/Gendarme.Rules.Interoperability/MarshalBooleansInPInvokeDeclarationsRule.cs
16660+++ b/gendarme/rules/Gendarme.Rules.Interoperability/MarshalBooleansInPInvokeDeclarationsRule.cs
16661@@ -64,13 +64,13 @@ namespace Gendarme.Rules.Interoperability {
16662 [FxCopCompatibility ("Microsoft.Interoperability", "CA1414:MarkBooleanPInvokeArgumentsWithMarshalAs")]
16663 public class MarshalBooleansInPInvokeDeclarationsRule : Rule, IMethodRule {
16664
16665- static bool CheckBooleanMarshalling (IMarshalInfoProvider spec, MemberReference type)
16666+ static bool CheckBooleanMarshalling (IMarshalInfoProvider spec, TypeReference type)
16667 {
16668 // is marshalling information provided
16669 if (spec.MarshalInfo != null)
16670 return true;
16671 // using StartsWith to catch references (ref)
16672- return !type.FullName.StartsWith ("System.Boolean", StringComparison.Ordinal);
16673+ return !(type.Namespace == "System" && type.Name.StartsWith ("Boolean", StringComparison.Ordinal));
16674 }
16675
16676 public RuleResult CheckMethod (MethodDefinition method)
16677diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/MarshalStringsInPInvokeDeclarationsRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/MarshalStringsInPInvokeDeclarationsRule.cs
16678index 442dd74..7edf597 100644
16679--- a/gendarme/rules/Gendarme.Rules.Interoperability/MarshalStringsInPInvokeDeclarationsRule.cs
16680+++ b/gendarme/rules/Gendarme.Rules.Interoperability/MarshalStringsInPInvokeDeclarationsRule.cs
16681@@ -27,9 +27,11 @@
16682 //
16683
16684 using System;
16685+using System.Globalization;
16686
16687 using Mono.Cecil;
16688 using Gendarme.Framework;
16689+using Gendarme.Framework.Rocks;
16690
16691 namespace Gendarme.Rules.Interoperability {
16692
16693@@ -69,13 +71,8 @@ namespace Gendarme.Rules.Interoperability {
16694
16695 private static bool IsStringOrSBuilder (TypeReference reference)
16696 {
16697- switch (reference.GetElementType ().FullName) {
16698- case "System.String":
16699- case "System.Text.StringBuilder":
16700- return true;
16701- default:
16702- return false;
16703- }
16704+ TypeReference type = reference.GetElementType ();
16705+ return (type.IsNamed ("System", "String") || type.IsNamed ("System.Text", "StringBuilder"));
16706 }
16707
16708 public RuleResult CheckMethod (MethodDefinition method)
16709@@ -93,7 +90,8 @@ namespace Gendarme.Rules.Interoperability {
16710
16711 foreach (ParameterDefinition parameter in method.Parameters) {
16712 if (IsStringOrSBuilder (parameter.ParameterType) && (parameter.MarshalInfo == null)) {
16713- string text = string.Format ("Parameter '{0}', of type '{1}', does not have [MarshalAs] attribute, yet no [DllImport CharSet=] is set for the method '{2}'.",
16714+ string text = String.Format (CultureInfo.InvariantCulture,
16715+ "Parameter '{0}', of type '{1}', does not have [MarshalAs] attribute, yet no [DllImport CharSet=] is set for the method '{2}'.",
16716 parameter.Name, parameter.ParameterType.Name, method.Name);
16717 Runner.Report (parameter, Severity.High, Confidence.Total, text);
16718 }
16719diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/README.md b/gendarme/rules/Gendarme.Rules.Interoperability/README.md
16720new file mode 100644
16721index 0000000..7932c1e
16722--- /dev/null
16723+++ b/gendarme/rules/Gendarme.Rules.Interoperability/README.md
16724@@ -0,0 +1,9 @@
16725+# Gendarme.Rules.Interoperability Rules
16726+
16727+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Interoperability(git)]] pages.
16728+
16729+
16730+## Feedback
16731+
16732+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
16733+
16734diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/Test/Tests.Rules.Interoperability.csproj b/gendarme/rules/Gendarme.Rules.Interoperability/Test/Tests.Rules.Interoperability.csproj
16735index 8f6896b..ce293e7 100755
16736--- a/gendarme/rules/Gendarme.Rules.Interoperability/Test/Tests.Rules.Interoperability.csproj
16737+++ b/gendarme/rules/Gendarme.Rules.Interoperability/Test/Tests.Rules.Interoperability.csproj
16738@@ -1,5 +1,5 @@
16739 <?xml version="1.0" encoding="utf-8"?>\r
16740-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
16741+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
16742 <PropertyGroup>\r
16743 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
16744 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
16745@@ -10,8 +10,28 @@
16746 <AppDesignerFolder>Properties</AppDesignerFolder>\r
16747 <RootNamespace>Tests.Rules.Interoperability</RootNamespace>\r
16748 <AssemblyName>Tests.Rules.Interoperability</AssemblyName>\r
16749- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
16750+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
16751 <FileAlignment>512</FileAlignment>\r
16752+ <FileUpgradeFlags>\r
16753+ </FileUpgradeFlags>\r
16754+ <OldToolsVersion>3.5</OldToolsVersion>\r
16755+ <UpgradeBackupLocation />\r
16756+ <PublishUrl>publish\</PublishUrl>\r
16757+ <Install>true</Install>\r
16758+ <InstallFrom>Disk</InstallFrom>\r
16759+ <UpdateEnabled>false</UpdateEnabled>\r
16760+ <UpdateMode>Foreground</UpdateMode>\r
16761+ <UpdateInterval>7</UpdateInterval>\r
16762+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
16763+ <UpdatePeriodically>false</UpdatePeriodically>\r
16764+ <UpdateRequired>false</UpdateRequired>\r
16765+ <MapFileExtensions>true</MapFileExtensions>\r
16766+ <ApplicationRevision>0</ApplicationRevision>\r
16767+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
16768+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
16769+ <UseApplicationTrust>false</UseApplicationTrust>\r
16770+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
16771+ <TargetFrameworkProfile />\r
16772 </PropertyGroup>\r
16773 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
16774 <DebugSymbols>true</DebugSymbols>\r
16775@@ -22,6 +42,7 @@
16776 <ErrorReport>prompt</ErrorReport>\r
16777 <WarningLevel>4</WarningLevel>\r
16778 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
16779+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
16780 </PropertyGroup>\r
16781 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
16782 <DebugType>pdbonly</DebugType>\r
16783@@ -31,6 +52,7 @@
16784 <ErrorReport>prompt</ErrorReport>\r
16785 <WarningLevel>4</WarningLevel>\r
16786 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
16787+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
16788 </PropertyGroup>\r
16789 <ItemGroup>\r
16790 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
16791@@ -73,6 +95,23 @@
16792 <ItemGroup>\r
16793 <Folder Include="Properties\" />\r
16794 </ItemGroup>\r
16795+ <ItemGroup>\r
16796+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
16797+ <Visible>False</Visible>\r
16798+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
16799+ <Install>false</Install>\r
16800+ </BootstrapperPackage>\r
16801+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
16802+ <Visible>False</Visible>\r
16803+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
16804+ <Install>true</Install>\r
16805+ </BootstrapperPackage>\r
16806+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
16807+ <Visible>False</Visible>\r
16808+ <ProductName>Windows Installer 3.1</ProductName>\r
16809+ <Install>true</Install>\r
16810+ </BootstrapperPackage>\r
16811+ </ItemGroup>\r
16812 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
16813 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
16814 Other similar extension points exist, see Microsoft.Common.targets.\r
16815diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/UseManagedAlternativesToPInvokeRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/UseManagedAlternativesToPInvokeRule.cs
16816index 4f502cb..27c7d8f 100644
16817--- a/gendarme/rules/Gendarme.Rules.Interoperability/UseManagedAlternativesToPInvokeRule.cs
16818+++ b/gendarme/rules/Gendarme.Rules.Interoperability/UseManagedAlternativesToPInvokeRule.cs
16819@@ -29,8 +29,9 @@
16820 //
16821
16822 using System;
16823-using System.Linq;
16824 using System.Collections.Generic;
16825+using System.Globalization;
16826+using System.Linq;
16827
16828 using Gendarme.Framework;
16829 using Mono.Cecil;
16830@@ -129,7 +130,8 @@ namespace Gendarme.Rules.Interoperability {
16831 if (alternatives == null)
16832 return RuleResult.Success;
16833
16834- string message = string.Format ("Try to replace the platform-dependent call '{0}' by (one of) the following alternative(s): {1}.",
16835+ string message = String.Format (CultureInfo.InvariantCulture,
16836+ "Try to replace the platform-dependent call '{0}' by (one of) the following alternative(s): {1}.",
16837 method.Name, alternatives.Alternatives);
16838 Runner.Report (method, Severity.Low, Confidence.High, message);
16839 return RuleResult.Failure;
16840diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidAlwaysNullFieldRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidAlwaysNullFieldRule.cs
16841index 8fa7eb1..ac27858 100644
16842--- a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidAlwaysNullFieldRule.cs
16843+++ b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidAlwaysNullFieldRule.cs
16844@@ -166,6 +166,16 @@ namespace Gendarme.Rules.Maintainability {
16845 }
16846 };
16847 }
16848+
16849+ void CheckMethods (TypeDefinition type)
16850+ {
16851+ if (!type.HasMethods)
16852+ return;
16853+
16854+ IList<MethodDefinition> mc = type.Methods;
16855+ for (int i = 0; i < mc.Count && nullFields.Count > 0; ++i)
16856+ CheckMethod (mc [i]);
16857+ }
16858
16859 public RuleResult CheckType (TypeDefinition type)
16860 {
16861@@ -175,7 +185,7 @@ namespace Gendarme.Rules.Maintainability {
16862 Log.WriteLine (this);
16863 Log.WriteLine (this, "----------------------------------");
16864
16865- bool isWinFormControl = usesWinForms && type.Inherits("System.Windows.Forms.Control");
16866+ bool isWinFormControl = usesWinForms && type.Inherits ("System.Windows.Forms", "Control");
16867
16868 // All fields start out as always null and unused.
16869 foreach (FieldDefinition field in type.Fields) {
16870@@ -184,10 +194,10 @@ namespace Gendarme.Rules.Maintainability {
16871 nullFields.Add (field);
16872 }
16873
16874- if (type.HasMethods) {
16875- IList<MethodDefinition> mc = type.Methods;
16876- for (int i = 0; i < mc.Count && nullFields.Count > 0; ++i)
16877- CheckMethod (mc [i]);
16878+ CheckMethods (type);
16879+ if (type.HasNestedTypes) {
16880+ foreach (TypeDefinition nested in type.NestedTypes)
16881+ CheckMethods (nested);
16882 }
16883
16884 // Report a defect if:
16885diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidComplexMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidComplexMethodsRule.cs
16886index 46200ab..59d780d 100644
16887--- a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidComplexMethodsRule.cs
16888+++ b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidComplexMethodsRule.cs
16889@@ -31,6 +31,7 @@
16890 using System;
16891 using System.Collections.Generic;
16892 using System.ComponentModel;
16893+using System.Globalization;
16894
16895 using Mono.Cecil;
16896 using Mono.Cecil.Cil;
16897@@ -127,7 +128,8 @@ namespace Gendarme.Rules.Maintainability {
16898 //how's severity?
16899 Severity sev = GetCyclomaticComplexitySeverity(cc);
16900
16901- Runner.Report (method, sev, Confidence.High, String.Format ("Method's cyclomatic complexity : {0}.", cc));
16902+ string msg = String.Format (CultureInfo.CurrentCulture, "Method's cyclomatic complexity : {0}.", cc);
16903+ Runner.Report (method, sev, Confidence.High, msg);
16904 return RuleResult.Failure;
16905 }
16906
16907diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidDeepInheritanceTreeRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidDeepInheritanceTreeRule.cs
16908index a0e2af8..010ac00 100644
16909--- a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidDeepInheritanceTreeRule.cs
16910+++ b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidDeepInheritanceTreeRule.cs
16911@@ -28,6 +28,7 @@
16912
16913 using System;
16914 using System.ComponentModel;
16915+using System.Globalization;
16916
16917 using Mono.Cecil;
16918
16919@@ -84,11 +85,12 @@ namespace Gendarme.Rules.Maintainability {
16920 return RuleResult.DoesNotApply;
16921
16922 int depth = 0;
16923- while (type.BaseType != null) {
16924- type = type.BaseType.Resolve ();
16925- if (type == null)
16926+ TypeDefinition temp = type;
16927+ while (temp.BaseType != null) {
16928+ temp = temp.BaseType.Resolve();
16929+ if (temp == null)
16930 break;
16931- if (countExternalDepth || Runner.Assemblies.Contains (type.Module.Assembly))
16932+ if (countExternalDepth || Runner.Assemblies.Contains(temp.Module.Assembly))
16933 depth++;
16934 }
16935
16936@@ -99,7 +101,8 @@ namespace Gendarme.Rules.Maintainability {
16937 // where it's possible we can't resolve up to System.Object
16938 Confidence confidence = countExternalDepth ? Confidence.High : Confidence.Total;
16939 // Severity is based on the depth
16940- Runner.Report (type, GetSeverity (depth), confidence, String.Format ("Inheritance tree depth : {0}.", depth));
16941+ string msg = String.Format (CultureInfo.CurrentCulture, "Inheritance tree depth : {0}.", depth);
16942+ Runner.Report (type, GetSeverity (depth), confidence, msg);
16943 return RuleResult.Failure;
16944 }
16945 }
16946diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidLackOfCohesionOfMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidLackOfCohesionOfMethodsRule.cs
16947index 4a428f0..44df73b 100644
16948--- a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidLackOfCohesionOfMethodsRule.cs
16949+++ b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidLackOfCohesionOfMethodsRule.cs
16950@@ -31,6 +31,7 @@
16951 using System;
16952 using System.Collections.Generic;
16953 using System.ComponentModel;
16954+using System.Globalization;
16955
16956 using Mono.Cecil;
16957 using Mono.Cecil.Cil;
16958@@ -88,7 +89,8 @@ namespace Gendarme.Rules.Maintainability {
16959 //how's severity?
16960 Severity sev = GetCohesivenessSeverity(coh);
16961
16962- Runner.Report (type, sev, Confidence.Normal, String.Format ("Type cohesiveness : {0}%", (int) (coh * 100)));
16963+ string msg = String.Format (CultureInfo.CurrentCulture, "Type cohesiveness : {0}%", (int) (coh * 100));
16964+ Runner.Report (type, sev, Confidence.Normal, msg);
16965 return RuleResult.Failure;
16966 }
16967
16968diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidUnnecessarySpecializationRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidUnnecessarySpecializationRule.cs
16969index c16bfbf..a906ebd 100644
16970--- a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidUnnecessarySpecializationRule.cs
16971+++ b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidUnnecessarySpecializationRule.cs
16972@@ -215,7 +215,7 @@ namespace Gendarme.Rules.Maintainability {
16973 if (pType is GenericParameter)
16974 parameters [i] = null; //TODO: constructed mapping?
16975 else
16976- parameters [i] = pType.FullName;
16977+ parameters [i] = pType.GetFullName ();
16978 }
16979 return new MethodSignature (name, rtype, parameters);
16980 }
16981@@ -225,7 +225,7 @@ namespace Gendarme.Rules.Maintainability {
16982 //special exception
16983 if (!method.HasParameters && (method.Name == "GetEnumerator"))
16984 return null;
16985- return method.ReturnType.FullName;
16986+ return method.ReturnType.GetFullName ();
16987 }
16988
16989 private static bool IsSystemObjectMethod (MethodReference method)
16990@@ -250,7 +250,7 @@ namespace Gendarme.Rules.Maintainability {
16991 //HACK: BOO:
16992 case "EqualityOperator" :
16993 return (method.HasParameters && (method.Parameters.Count == 2) &&
16994- (method.DeclaringType.FullName == "Boo.Lang.Runtime.RuntimeServices"));
16995+ (method.DeclaringType.IsNamed ("Boo.Lang.Runtime", "RuntimeServices")));
16996 }
16997 return false;
16998 }
16999@@ -262,7 +262,7 @@ namespace Gendarme.Rules.Maintainability {
17000
17001 private static bool IsIgnoredSuggestionType (TypeReference type)
17002 {
17003- return ((type.FullName == "System.Object") || IsFromNonGenericCollectionNamespace (type.Namespace));
17004+ return (type.IsNamed ("System", "Object") || IsFromNonGenericCollectionNamespace (type.Namespace));
17005 }
17006
17007 private static List<MethodSignature> GetSignatures (IEnumerable<StackEntryUsageResult> usageResults)
17008@@ -285,7 +285,7 @@ namespace Gendarme.Rules.Maintainability {
17009
17010 private void UpdateParameterLeastType (ParameterReference parameter, IEnumerable<StackEntryUsageResult> usageResults)
17011 {
17012- int pIndex = parameter.GetSequence () - 1;
17013+ int pIndex = parameter.Index;
17014 int parameterDepth = GetActualTypeDepth (parameter.ParameterType);
17015
17016 int currentLeastDepth = 0;
17017@@ -366,7 +366,7 @@ namespace Gendarme.Rules.Maintainability {
17018
17019 ParameterDefinition parameter = ins.GetParameter (method);
17020 // this is `this`, we do not care
17021- if ((parameter == null) || (parameter.GetSequence () == 0))
17022+ if ((parameter == null) || (parameter.Index == -1))
17023 continue;
17024
17025 // is parameter already known ?
17026@@ -474,7 +474,7 @@ namespace Gendarme.Rules.Maintainability {
17027 {
17028 foreach (ParameterDefinition parameter in method.Parameters){
17029
17030- int i = parameter.GetSequence () - 1;
17031+ int i = parameter.Index;
17032 if (null == types_least [i])
17033 continue; //argument is not used
17034
17035@@ -540,7 +540,7 @@ namespace Gendarme.Rules.Maintainability {
17036 else
17037 nRemoveTrail = 3;
17038
17039- string fullname = type.FullName;
17040+ string fullname = type.GetFullName ();
17041 sb.Append (fullname.Substring (0, fullname.Length - nRemoveTrail));
17042 if (count > 0) {
17043 int n = 0;
17044diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/ConsiderUsingStopwatchRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/ConsiderUsingStopwatchRule.cs
17045index 17a448f..79353c1 100644
17046--- a/gendarme/rules/Gendarme.Rules.Maintainability/ConsiderUsingStopwatchRule.cs
17047+++ b/gendarme/rules/Gendarme.Rules.Maintainability/ConsiderUsingStopwatchRule.cs
17048@@ -77,9 +77,6 @@ namespace Gendarme.Rules.Maintainability {
17049 [EngineDependency (typeof (OpCodeEngine))]
17050 public class ConsiderUsingStopwatchRule : Rule, IMethodRule {
17051
17052- private const string DateTime = "System.DateTime";
17053- private const string GetNow = "get_Now";
17054-
17055 public override void Initialize (IRunner runner)
17056 {
17057 base.Initialize (runner);
17058@@ -90,8 +87,11 @@ namespace Gendarme.Rules.Maintainability {
17059 // did not exist back then.
17060 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
17061 Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0
17062- && (e.CurrentAssembly.Name.Name == "mscorlib"
17063- || e.CurrentModule.HasTypeReference (DateTime)));
17064+ && (e.CurrentAssembly.Name.Name == "mscorlib" ||
17065+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
17066+ return tr.IsNamed ("System", "DateTime");
17067+ }
17068+ )));
17069 };
17070 }
17071
17072@@ -106,7 +106,7 @@ namespace Gendarme.Rules.Maintainability {
17073 return false;
17074
17075 MethodReference calledMethod = (MethodReference) ins.Operand;
17076- return calledMethod.DeclaringType.FullName == DateTime && calledMethod.Name == GetNow;
17077+ return calledMethod.IsNamed ("System", "DateTime", "get_Now");
17078 }
17079
17080 private static bool CheckParameters (MethodDefinition method, Instruction ins)
17081@@ -125,14 +125,14 @@ namespace Gendarme.Rules.Maintainability {
17082 ParameterDefinition p = prev.GetParameter (method);
17083 if (p == null)
17084 return false;
17085- int arg = p.GetSequence ();
17086+ int arg = p.Index;
17087 prev = prev.Previous;
17088 while (null != prev) {
17089 // look for a STOBJ instruction and compare the objects
17090 if (prev.OpCode.Code == Code.Stobj) {
17091 prev = prev.TraceBack (method);
17092 p = prev.GetParameter (method);
17093- return (p == null) ? false : (arg == p.GetSequence ());
17094+ return (p == null) ? false : (arg == p.Index);
17095 }
17096 prev = prev.Previous;
17097 }
17098@@ -161,11 +161,10 @@ namespace Gendarme.Rules.Maintainability {
17099 return RuleResult.DoesNotApply;
17100
17101 foreach (Instruction ins in method.Body.Instructions) {
17102- if (!calls.Get (ins.OpCode.Code))
17103+ MethodReference calledMethod = ins.GetMethod ();
17104+ if (calledMethod == null)
17105 continue;
17106-
17107- MethodReference calledMethod = (MethodReference) ins.Operand;
17108- if (calledMethod.DeclaringType.FullName != DateTime)
17109+ if (!calledMethod.DeclaringType.IsNamed ("System", "DateTime"))
17110 continue;
17111 if (!MethodSignatures.op_Subtraction.Matches (calledMethod))
17112 continue;
17113diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/Gendarme.Rules.Maintainability.csproj b/gendarme/rules/Gendarme.Rules.Maintainability/Gendarme.Rules.Maintainability.csproj
17114index 3a4fd96..261474c 100755
17115--- a/gendarme/rules/Gendarme.Rules.Maintainability/Gendarme.Rules.Maintainability.csproj
17116+++ b/gendarme/rules/Gendarme.Rules.Maintainability/Gendarme.Rules.Maintainability.csproj
17117@@ -1,5 +1,5 @@
17118 <?xml version="1.0" encoding="utf-8"?>\r
17119-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
17120+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
17121 <PropertyGroup>\r
17122 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
17123 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
17124@@ -10,8 +10,28 @@
17125 <AppDesignerFolder>Properties</AppDesignerFolder>\r
17126 <RootNamespace>Gendarme.Rules.Maintainability</RootNamespace>\r
17127 <AssemblyName>Gendarme.Rules.Maintainability</AssemblyName>\r
17128- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
17129+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
17130 <FileAlignment>512</FileAlignment>\r
17131+ <FileUpgradeFlags>\r
17132+ </FileUpgradeFlags>\r
17133+ <OldToolsVersion>3.5</OldToolsVersion>\r
17134+ <UpgradeBackupLocation />\r
17135+ <PublishUrl>publish\</PublishUrl>\r
17136+ <Install>true</Install>\r
17137+ <InstallFrom>Disk</InstallFrom>\r
17138+ <UpdateEnabled>false</UpdateEnabled>\r
17139+ <UpdateMode>Foreground</UpdateMode>\r
17140+ <UpdateInterval>7</UpdateInterval>\r
17141+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
17142+ <UpdatePeriodically>false</UpdatePeriodically>\r
17143+ <UpdateRequired>false</UpdateRequired>\r
17144+ <MapFileExtensions>true</MapFileExtensions>\r
17145+ <ApplicationRevision>0</ApplicationRevision>\r
17146+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
17147+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
17148+ <UseApplicationTrust>false</UseApplicationTrust>\r
17149+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
17150+ <TargetFrameworkProfile />\r
17151 </PropertyGroup>\r
17152 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
17153 <DebugSymbols>true</DebugSymbols>\r
17154@@ -24,6 +44,7 @@
17155 <NoWarn>1591</NoWarn>\r
17156 <WarningsAsErrors>1570</WarningsAsErrors>\r
17157 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Maintainability.xml</DocumentationFile>\r
17158+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
17159 </PropertyGroup>\r
17160 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
17161 <DebugType>pdbonly</DebugType>\r
17162@@ -35,6 +56,7 @@
17163 <NoWarn>1591</NoWarn>\r
17164 <WarningsAsErrors>1570</WarningsAsErrors>\r
17165 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Maintainability.xml</DocumentationFile>\r
17166+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
17167 </PropertyGroup>\r
17168 <ItemGroup>\r
17169 <Reference Include="System" />\r
17170@@ -67,6 +89,23 @@
17171 <Name>Gendarme.Framework</Name>\r
17172 </ProjectReference>\r
17173 </ItemGroup>\r
17174+ <ItemGroup>\r
17175+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
17176+ <Visible>False</Visible>\r
17177+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
17178+ <Install>false</Install>\r
17179+ </BootstrapperPackage>\r
17180+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
17181+ <Visible>False</Visible>\r
17182+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
17183+ <Install>true</Install>\r
17184+ </BootstrapperPackage>\r
17185+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
17186+ <Visible>False</Visible>\r
17187+ <ProductName>Windows Installer 3.1</ProductName>\r
17188+ <Install>true</Install>\r
17189+ </BootstrapperPackage>\r
17190+ </ItemGroup>\r
17191 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
17192 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
17193 Other similar extension points exist, see Microsoft.Common.targets.
17194diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/PreferStringIsNullOrEmptyRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/PreferStringIsNullOrEmptyRule.cs
17195index fc5d1f8..efe4653 100644
17196--- a/gendarme/rules/Gendarme.Rules.Maintainability/PreferStringIsNullOrEmptyRule.cs
17197+++ b/gendarme/rules/Gendarme.Rules.Maintainability/PreferStringIsNullOrEmptyRule.cs
17198@@ -116,7 +116,14 @@ namespace Gendarme.Rules.Maintainability {
17199 case Code.Ldloc_S:
17200 return (ins.Operand as VariableDefinition).Name;
17201 default:
17202- return (ins.Operand == null) ? String.Empty : ins.Operand.ToString ();
17203+ object o = ins.Operand;
17204+ MemberReference mr = (o as MemberReference);
17205+ if (mr != null)
17206+ return mr.GetFullName ();
17207+ else if (o != null)
17208+ return o.ToString ();
17209+ else
17210+ return String.Empty;
17211 }
17212 }
17213
17214@@ -196,7 +203,7 @@ namespace Gendarme.Rules.Maintainability {
17215 continue;
17216
17217 MethodReference mr = (current.Operand as MethodReference);
17218- if ((mr.Name == "get_Length") && (mr.DeclaringType.FullName == "System.String")) {
17219+ if (mr.IsNamed ("System", "String", "get_Length")) {
17220 // now that we found it we check that
17221 // 1 - we previously did a check null on the same value (that we already know is a string)
17222 Instruction branch = PreLengthCheck (method, current.Previous);
17223diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/README.md b/gendarme/rules/Gendarme.Rules.Maintainability/README.md
17224new file mode 100644
17225index 0000000..d843fdd
17226--- /dev/null
17227+++ b/gendarme/rules/Gendarme.Rules.Maintainability/README.md
17228@@ -0,0 +1,9 @@
17229+# Gendarme.Rules.Maintainability Rules
17230+
17231+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Maintainability(git)]] pages.
17232+
17233+
17234+## Feedback
17235+
17236+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
17237+
17238diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/RemoveDependenceOnObsoleteCodeRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/RemoveDependenceOnObsoleteCodeRule.cs
17239index 7686b8e..31868ea 100644
17240--- a/gendarme/rules/Gendarme.Rules.Maintainability/RemoveDependenceOnObsoleteCodeRule.cs
17241+++ b/gendarme/rules/Gendarme.Rules.Maintainability/RemoveDependenceOnObsoleteCodeRule.cs
17242@@ -28,6 +28,7 @@
17243
17244 using System;
17245 using System.Collections.Generic;
17246+using System.Globalization;
17247
17248 using Mono.Cecil;
17249 using Mono.Cecil.Cil;
17250@@ -101,8 +102,6 @@ namespace Gendarme.Rules.Maintainability {
17251 [EngineDependency (typeof (OpCodeEngine))]
17252 public class RemoveDependenceOnObsoleteCodeRule : Rule, ITypeRule, IMethodRule {
17253
17254- const string Obsolete = "System.ObsoleteAttribute";
17255-
17256 static Dictionary<TypeReference, bool> types = new Dictionary<TypeReference, bool> ();
17257 static Dictionary<MethodReference, bool> methods = new Dictionary<MethodReference, bool> ();
17258 static Dictionary<FieldReference, bool> fields = new Dictionary<FieldReference, bool> ();
17259@@ -115,7 +114,7 @@ namespace Gendarme.Rules.Maintainability {
17260 bool obsolete = false;
17261 if (!types.TryGetValue (type, out obsolete)) {
17262 TypeDefinition t = type.Resolve ();
17263- obsolete = t == null ? false : t.HasAttribute (Obsolete);
17264+ obsolete = t.HasAttribute ("System", "ObsoleteAttribute");
17265 types.Add (type, obsolete);
17266 }
17267 return obsolete;
17268@@ -129,7 +128,7 @@ namespace Gendarme.Rules.Maintainability {
17269 bool obsolete = false;
17270 if (!methods.TryGetValue (method, out obsolete)) {
17271 MethodDefinition md = method.Resolve ();
17272- obsolete = (md == null) ? false : md.HasAttribute (Obsolete);
17273+ obsolete = md.HasAttribute ("System", "ObsoleteAttribute");
17274 methods.Add (method, obsolete);
17275 }
17276 return obsolete;
17277@@ -143,7 +142,7 @@ namespace Gendarme.Rules.Maintainability {
17278 bool obsolete = false;
17279 if (!fields.TryGetValue (field, out obsolete)) {
17280 FieldDefinition fd = field.Resolve ();
17281- obsolete = (fd == null) ? false : fd.HasAttribute (Obsolete);
17282+ obsolete = fd.HasAttribute ("System", "ObsoleteAttribute");
17283 fields.Add (field, obsolete);
17284 }
17285 return obsolete;
17286@@ -154,7 +153,7 @@ namespace Gendarme.Rules.Maintainability {
17287 if (!IsObsolete (type.BaseType))
17288 return;
17289
17290- string msg = String.Format ("Inherit from obsolete type '{0}'.", type.BaseType);
17291+ string msg = String.Format (CultureInfo.InvariantCulture, "Inherit from obsolete type '{0}'.", type.BaseType);
17292 Runner.Report (type, type.IsVisible () ? Severity.High : Severity.Medium, Confidence.Total, msg);
17293 }
17294
17295@@ -162,7 +161,7 @@ namespace Gendarme.Rules.Maintainability {
17296 {
17297 foreach (TypeReference intf in type.Interfaces) {
17298 if (IsObsolete (intf)) {
17299- string msg = String.Format ("Implement obsolete interface '{0}'.", intf);
17300+ string msg = String.Format (CultureInfo.InvariantCulture, "Implement obsolete interface '{0}'.", intf);
17301 Runner.Report (type, type.IsVisible () ? Severity.Medium : Severity.Low, Confidence.Total, msg);
17302 }
17303 }
17304@@ -172,7 +171,7 @@ namespace Gendarme.Rules.Maintainability {
17305 {
17306 foreach (FieldDefinition field in type.Fields) {
17307 if (IsObsolete (field.FieldType)) {
17308- string msg = String.Format ("Field type '{0}' is obsolete.", field.FieldType);
17309+ string msg = String.Format (CultureInfo.InvariantCulture, "Field type '{0}' is obsolete.", field.FieldType);
17310 Runner.Report (field, field.IsVisible () ? Severity.Medium : Severity.Low, Confidence.Total, msg);
17311 }
17312 }
17313@@ -183,7 +182,7 @@ namespace Gendarme.Rules.Maintainability {
17314 {
17315 foreach (PropertyDefinition property in type.Properties) {
17316 if (IsObsolete (property.PropertyType)) {
17317- string msg = String.Format ("Property type '{0}' is obsolete.", property.PropertyType);
17318+ string msg = String.Format (CultureInfo.InvariantCulture, "Property type '{0}' is obsolete.", property.PropertyType);
17319 bool visible = (IsVisible (property.GetMethod) || IsVisible (property.SetMethod));
17320 Runner.Report (property, visible ? Severity.High : Severity.Medium, Confidence.Total, msg);
17321 }
17322@@ -194,7 +193,7 @@ namespace Gendarme.Rules.Maintainability {
17323 {
17324 foreach (EventDefinition evnt in type.Events) {
17325 if (IsObsolete (evnt.EventType)) {
17326- string msg = String.Format ("Event type '{0}' is obsolete.", evnt.EventType);
17327+ string msg = String.Format (CultureInfo.InvariantCulture, "Event type '{0}' is obsolete.", evnt.EventType);
17328 bool visible = (IsVisible (evnt.AddMethod) || IsVisible (evnt.RemoveMethod) ||
17329 IsVisible (evnt.InvokeMethod));
17330 Runner.Report (evnt, visible ? Severity.High : Severity.Medium, Confidence.Total, msg);
17331@@ -220,7 +219,7 @@ namespace Gendarme.Rules.Maintainability {
17332 public RuleResult CheckType (TypeDefinition type)
17333 {
17334 // we're not interested in the details of [Obsolete] types
17335- if (type.HasAttribute (Obsolete))
17336+ if (type.HasAttribute ("System", "ObsoleteAttribute"))
17337 return RuleResult.DoesNotApply;
17338
17339 // check if we inherit from an [Obsolete] class / struct / enum
17340@@ -249,7 +248,7 @@ namespace Gendarme.Rules.Maintainability {
17341 {
17342 foreach (ParameterDefinition p in method.Parameters) {
17343 if (IsObsolete (p.ParameterType)) {
17344- string msg = String.Format ("Parameter type '{0}' is obsolete.", p.ParameterType);
17345+ string msg = String.Format (CultureInfo.InvariantCulture, "Parameter type '{0}' is obsolete.", p.ParameterType);
17346 Runner.Report (p, method.IsVisible () ? Severity.High : Severity.Medium, Confidence.Total, msg);
17347 }
17348 }
17349@@ -261,7 +260,7 @@ namespace Gendarme.Rules.Maintainability {
17350 if (!IsObsolete (rt))
17351 return;
17352
17353- string msg = String.Format ("Return type '{0}' is obsolete.", rt);
17354+ string msg = String.Format (CultureInfo.InvariantCulture, "Return type '{0}' is obsolete.", rt);
17355 Runner.Report (method, method.IsVisible () ? Severity.High : Severity.Medium, Confidence.Total, msg);
17356 }
17357
17358@@ -269,7 +268,7 @@ namespace Gendarme.Rules.Maintainability {
17359 {
17360 foreach (VariableDefinition v in method.Body.Variables) {
17361 if (IsObsolete (v.VariableType)) {
17362- string msg = String.Format ("Variable type '{0}' is obsolete.", v.VariableType);
17363+ string msg = String.Format (CultureInfo.InvariantCulture, "Variable type '{0}' is obsolete.", v.VariableType);
17364 Runner.Report (method, Severity.Low, Confidence.High, msg);
17365 }
17366 }
17367@@ -280,7 +279,7 @@ namespace Gendarme.Rules.Maintainability {
17368 if (!IsObsolete (type))
17369 return;
17370
17371- string msg = String.Format ("Type '{0}' is obsolete.", type);
17372+ string msg = String.Format (CultureInfo.InvariantCulture, "Type '{0}' is obsolete.", type);
17373 Severity severity = type.IsVisible () ? Severity.Medium : Severity.Low;
17374 Runner.Report (method, ins, severity, Confidence.High, msg);
17375 }
17376@@ -292,11 +291,11 @@ namespace Gendarme.Rules.Maintainability {
17377
17378 string msg = null;
17379 if (IsObsolete (call)) {
17380- msg = String.Format ("Method '{0}' is obsolete.", call);
17381+ msg = String.Format (CultureInfo.InvariantCulture, "Method '{0}' is obsolete.", call);
17382 } else {
17383 TypeReference type = call.DeclaringType;
17384 if (IsObsolete (type))
17385- msg = String.Format ("Type '{0}' is obsolete.", type);
17386+ msg = String.Format (CultureInfo.InvariantCulture, "Type '{0}' is obsolete.", type);
17387 }
17388
17389 if (msg != null) {
17390@@ -312,9 +311,9 @@ namespace Gendarme.Rules.Maintainability {
17391
17392 string msg = null;
17393 if (IsObsolete (field)) {
17394- msg = String.Format ("Field '{0}' is obsolete.", field.Name);
17395+ msg = String.Format (CultureInfo.InvariantCulture, "Field '{0}' is obsolete.", field.Name);
17396 } else if (IsObsolete (field.DeclaringType)) {
17397- msg = String.Format ("Field type '{0}' is obsolete.", field.FieldType);
17398+ msg = String.Format (CultureInfo.InvariantCulture, "Field type '{0}' is obsolete.", field.FieldType);
17399 } else {
17400 return;
17401 }
17402@@ -339,7 +338,7 @@ namespace Gendarme.Rules.Maintainability {
17403 return RuleResult.DoesNotApply;
17404
17405 // if the method is obsolete (directly or because it's type is)
17406- if (method.HasAttribute (Obsolete) || method.DeclaringType.HasAttribute (Obsolete))
17407+ if (method.HasAttribute ("System", "ObsoleteAttribute") || method.DeclaringType.HasAttribute ("System", "ObsoleteAttribute"))
17408 return RuleResult.DoesNotApply;
17409
17410 // check method signature (parameters, return value)
17411diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/ReviewMisleadingFieldNamesRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/ReviewMisleadingFieldNamesRule.cs
17412index 12999b3..6855c77 100644
17413--- a/gendarme/rules/Gendarme.Rules.Maintainability/ReviewMisleadingFieldNamesRule.cs
17414+++ b/gendarme/rules/Gendarme.Rules.Maintainability/ReviewMisleadingFieldNamesRule.cs
17415@@ -26,32 +26,32 @@
17416 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
17417 //
17418
17419-
17420+using System;
17421 using Mono.Cecil;
17422-
17423 using Gendarme.Framework;
17424
17425 namespace Gendarme.Rules.Maintainability {
17426
17427 /// <summary>
17428 /// This rule checks for fields which have misleading names, e.g. instance fields beginning with "s_"
17429+ /// or static fields beginning with "m_", since they can be confusing when reading source code.
17430 /// </summary>
17431 /// <example>
17432 /// Bad example:
17433 /// <code>
17434- /// public class Bad {
17435- /// public int s_Value;
17436- /// public static int m_OtherValue;
17437- /// }
17438+ /// public class Bad {
17439+ /// int s_value;
17440+ /// static int m_other_value;
17441+ /// }
17442 /// </code>
17443 /// </example>
17444 /// <example>
17445 /// Good example:
17446 /// <code>
17447- /// public class Good {
17448- /// public int m_Value;
17449- /// public static int s_OtherValue;
17450- /// }
17451+ /// public class Good {
17452+ /// int value;
17453+ /// static int other_value;
17454+ /// }
17455 /// </code>
17456 /// </example>
17457
17458@@ -68,7 +68,8 @@ namespace Gendarme.Rules.Maintainability {
17459
17460 foreach (FieldDefinition field in type.Fields) {
17461 string name = field.Name;
17462- if (field.IsStatic ? name.StartsWith ("m_") : name.StartsWith ("s_"))
17463+ string prefix = field.IsStatic ? "m_" : "s_";
17464+ if (name.StartsWith (prefix, StringComparison.Ordinal))
17465 Runner.Report (field, Severity.Low, Confidence.Total);
17466 }
17467
17468diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidAlwaysNullFieldTest.cs b/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidAlwaysNullFieldTest.cs
17469index 95ac856..4307c2f 100644
17470--- a/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidAlwaysNullFieldTest.cs
17471+++ b/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidAlwaysNullFieldTest.cs
17472@@ -3,8 +3,10 @@
17473 //
17474 // Authors:
17475 // Jesse Jones <jesjones@mindspring.com>
17476+// Sebastien Pouliot <sebastien@ximian.com>
17477 //
17478 // Copyright (C) 2008 Jesse Jones
17479+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
17480 //
17481 // Permission is hereby granted, free of charge, to any person obtaining
17482 // a copy of this software and associated documentation files (the
17483@@ -29,8 +31,7 @@
17484 using System;
17485 using System.Collections.Generic;
17486 using System.Linq;
17487-using System.Runtime.InteropServices;
17488-using System.Text;
17489+using System.Threading;
17490
17491 using Gendarme.Rules.Maintainability;
17492
17493@@ -231,5 +232,51 @@ namespace Test.Rules.Maintainability {
17494 AssertRuleSuccess<Bug667692a> ();
17495 AssertRuleSuccess<Bug667692b> ();
17496 }
17497+
17498+ // this will create an anonymous method
17499+ class AnonymousDelegatesAllFields {
17500+
17501+ string file;
17502+
17503+ void Parse ()
17504+ {
17505+ ThreadPool.QueueUserWorkItem (delegate {
17506+ file = "";
17507+ });
17508+ }
17509+
17510+ void Show ()
17511+ {
17512+ Console.WriteLine (file);
17513+ }
17514+ }
17515+
17516+ // this will create a nested type with the anonymous method
17517+ class AnonymousDelegatesFieldsAndLocals {
17518+
17519+ string file;
17520+
17521+ void Parse ()
17522+ {
17523+ string local;
17524+
17525+ ThreadPool.QueueUserWorkItem (delegate {
17526+ file = "";
17527+ local = file;
17528+ });
17529+ }
17530+
17531+ void Show ()
17532+ {
17533+ Console.WriteLine (file);
17534+ }
17535+ }
17536+
17537+ [Test]
17538+ public void AnonymousDelegates ()
17539+ {
17540+ AssertRuleSuccess<AnonymousDelegatesAllFields> ();
17541+ AssertRuleSuccess<AnonymousDelegatesFieldsAndLocals> ();
17542+ }
17543 }
17544 }
17545diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidUnnecessarySpecializationTest.cs b/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidUnnecessarySpecializationTest.cs
17546index c974504..1ae36c4 100644
17547--- a/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidUnnecessarySpecializationTest.cs
17548+++ b/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidUnnecessarySpecializationTest.cs
17549@@ -25,9 +25,10 @@
17550 // THE SOFTWARE.
17551
17552 using System;
17553-using System.Reflection;
17554 using System.Collections;
17555 using System.Collections.Generic;
17556+using System.Linq;
17557+using System.Reflection;
17558
17559 using Mono.Cecil;
17560
17561@@ -631,5 +632,34 @@ namespace Test.Rules.Maintainability {
17562 AssertRuleSuccess<GeneralizedClass> ("OverloadNotSupportedByInterface");
17563 AssertRuleFailure<SpecializedClass> ("OverloadNotSupportedByInterface", 1);
17564 }
17565+
17566+ class TestCase690057 {
17567+ public class nauczyciel {
17568+ public Guid Oid;
17569+ public List<object> NoweGrupies = new List<object> ();
17570+ }
17571+ public List<nauczyciel> nauczyciele = new List<nauczyciel> ();
17572+ public void WyslijMaile (List<Guid> ListIdJ, Guid idRok)
17573+ {
17574+
17575+ var cmd = from c in nauczyciele
17576+ where ListIdJ.Contains (c.Oid)
17577+ select c;
17578+ foreach (var s in cmd) {
17579+ try {
17580+ foreach (var grp in s.NoweGrupies)
17581+ ;
17582+ }
17583+ catch (Exception ex) {
17584+ }
17585+ }
17586+ }
17587+ }
17588+
17589+ [Test]
17590+ public void Bug690057 ()
17591+ {
17592+ AssertRuleSuccess<TestCase690057> ("WyslijMaile");
17593+ }
17594 }
17595 }
17596diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/Test/Tests.Rules.Maintainability.csproj b/gendarme/rules/Gendarme.Rules.Maintainability/Test/Tests.Rules.Maintainability.csproj
17597index f72d459..5f08e85 100755
17598--- a/gendarme/rules/Gendarme.Rules.Maintainability/Test/Tests.Rules.Maintainability.csproj
17599+++ b/gendarme/rules/Gendarme.Rules.Maintainability/Test/Tests.Rules.Maintainability.csproj
17600@@ -1,5 +1,5 @@
17601 <?xml version="1.0" encoding="utf-8"?>\r
17602-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
17603+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
17604 <PropertyGroup>\r
17605 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
17606 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
17607@@ -10,8 +10,28 @@
17608 <AppDesignerFolder>Properties</AppDesignerFolder>\r
17609 <RootNamespace>Tests.Rules.Maintainability</RootNamespace>\r
17610 <AssemblyName>Tests.Rules.Maintainability</AssemblyName>\r
17611- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
17612+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
17613 <FileAlignment>512</FileAlignment>\r
17614+ <FileUpgradeFlags>\r
17615+ </FileUpgradeFlags>\r
17616+ <OldToolsVersion>3.5</OldToolsVersion>\r
17617+ <UpgradeBackupLocation />\r
17618+ <PublishUrl>publish\</PublishUrl>\r
17619+ <Install>true</Install>\r
17620+ <InstallFrom>Disk</InstallFrom>\r
17621+ <UpdateEnabled>false</UpdateEnabled>\r
17622+ <UpdateMode>Foreground</UpdateMode>\r
17623+ <UpdateInterval>7</UpdateInterval>\r
17624+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
17625+ <UpdatePeriodically>false</UpdatePeriodically>\r
17626+ <UpdateRequired>false</UpdateRequired>\r
17627+ <MapFileExtensions>true</MapFileExtensions>\r
17628+ <ApplicationRevision>0</ApplicationRevision>\r
17629+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
17630+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
17631+ <UseApplicationTrust>false</UseApplicationTrust>\r
17632+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
17633+ <TargetFrameworkProfile />\r
17634 </PropertyGroup>\r
17635 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
17636 <DebugSymbols>true</DebugSymbols>\r
17637@@ -21,6 +41,7 @@
17638 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
17639 <ErrorReport>prompt</ErrorReport>\r
17640 <WarningLevel>4</WarningLevel>\r
17641+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
17642 </PropertyGroup>\r
17643 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
17644 <DebugType>pdbonly</DebugType>\r
17645@@ -29,6 +50,7 @@
17646 <DefineConstants>TRACE</DefineConstants>\r
17647 <ErrorReport>prompt</ErrorReport>\r
17648 <WarningLevel>4</WarningLevel>\r
17649+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
17650 </PropertyGroup>\r
17651 <ItemGroup>\r
17652 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
17653@@ -76,6 +98,23 @@
17654 <ItemGroup>\r
17655 <Folder Include="Properties\" />\r
17656 </ItemGroup>\r
17657+ <ItemGroup>\r
17658+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
17659+ <Visible>False</Visible>\r
17660+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
17661+ <Install>false</Install>\r
17662+ </BootstrapperPackage>\r
17663+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
17664+ <Visible>False</Visible>\r
17665+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
17666+ <Install>true</Install>\r
17667+ </BootstrapperPackage>\r
17668+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
17669+ <Visible>False</Visible>\r
17670+ <ProductName>Windows Installer 3.1</ProductName>\r
17671+ <Install>true</Install>\r
17672+ </BootstrapperPackage>\r
17673+ </ItemGroup>\r
17674 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
17675 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
17676 Other similar extension points exist, see Microsoft.Common.targets.
17677diff --git a/gendarme/rules/Gendarme.Rules.NUnit/Gendarme.Rules.NUnit.csproj b/gendarme/rules/Gendarme.Rules.NUnit/Gendarme.Rules.NUnit.csproj
17678index b621be2..6ce2d1d 100755
17679--- a/gendarme/rules/Gendarme.Rules.NUnit/Gendarme.Rules.NUnit.csproj
17680+++ b/gendarme/rules/Gendarme.Rules.NUnit/Gendarme.Rules.NUnit.csproj
17681@@ -1,72 +1,111 @@
17682-<?xml version="1.0" encoding="utf-8"?>
17683-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
17684- <PropertyGroup>
17685- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
17686- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
17687- <ProductVersion>9.0.30729</ProductVersion>
17688- <SchemaVersion>2.0</SchemaVersion>
17689- <ProjectGuid>{54625746-D966-4BC2-A465-8F0928A767E6}</ProjectGuid>
17690- <OutputType>Library</OutputType>
17691- <AppDesignerFolder>Properties</AppDesignerFolder>
17692- <RootNamespace>Gendarme.Rules.NUnit</RootNamespace>
17693- <AssemblyName>Gendarme.Rules.NUnit</AssemblyName>
17694- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
17695- <FileAlignment>512</FileAlignment>
17696- </PropertyGroup>
17697- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
17698- <DebugSymbols>true</DebugSymbols>
17699- <DebugType>full</DebugType>
17700- <Optimize>false</Optimize>
17701- <OutputPath>..\..\console\bin\Debug\</OutputPath>
17702- <DefineConstants>DEBUG;TRACE</DefineConstants>
17703- <ErrorReport>prompt</ErrorReport>
17704- <WarningLevel>4</WarningLevel>
17705- <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.NUnit.xml</DocumentationFile>
17706- </PropertyGroup>
17707- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
17708- <DebugType>pdbonly</DebugType>
17709- <Optimize>true</Optimize>
17710- <OutputPath>..\..\console\bin\Release\</OutputPath>
17711- <DefineConstants>TRACE;RELEASE</DefineConstants>
17712- <ErrorReport>prompt</ErrorReport>
17713- <WarningLevel>4</WarningLevel>
17714- <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.NUnit.xml</DocumentationFile>
17715- </PropertyGroup>
17716- <ItemGroup>
17717- <Reference Include="System" />
17718- <Reference Include="System.Core">
17719- <RequiredTargetFramework>3.5</RequiredTargetFramework>
17720- </Reference>
17721- </ItemGroup>
17722- <ItemGroup>
17723- <Compile Include="..\..\AssemblyStaticInfo.cs">
17724- <Link>AssemblyStaticInfo.cs</Link>
17725- </Compile>
17726- <Compile Include="NUnitRocks.cs" />
17727- <Compile Include="NUnitRule.cs" />
17728- <Compile Include="ProvideMessageOnAssertCallsRule.cs" />
17729- <Compile Include="TestMethodsMustBePublicRule.cs" />
17730- <Compile Include="UnitTestsMissingTestFixtureRule.cs" />
17731- </ItemGroup>
17732- <ItemGroup>
17733- <ProjectReference Include="..\..\..\..\cecil\Mono.Cecil.csproj">
17734- <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>
17735- <Name>Mono.Cecil</Name>
17736- </ProjectReference>
17737- <ProjectReference Include="..\..\framework\Gendarme.Framework.csproj">
17738- <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>
17739- <Name>Gendarme.Framework</Name>
17740- </ProjectReference>
17741- </ItemGroup>
17742- <ItemGroup>
17743- <Folder Include="Properties\" />
17744- </ItemGroup>
17745- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
17746+<?xml version="1.0" encoding="utf-8"?>\r
17747+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
17748+ <PropertyGroup>\r
17749+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
17750+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
17751+ <ProductVersion>9.0.30729</ProductVersion>\r
17752+ <SchemaVersion>2.0</SchemaVersion>\r
17753+ <ProjectGuid>{54625746-D966-4BC2-A465-8F0928A767E6}</ProjectGuid>\r
17754+ <OutputType>Library</OutputType>\r
17755+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
17756+ <RootNamespace>Gendarme.Rules.NUnit</RootNamespace>\r
17757+ <AssemblyName>Gendarme.Rules.NUnit</AssemblyName>\r
17758+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
17759+ <FileAlignment>512</FileAlignment>\r
17760+ <FileUpgradeFlags>\r
17761+ </FileUpgradeFlags>\r
17762+ <OldToolsVersion>3.5</OldToolsVersion>\r
17763+ <UpgradeBackupLocation />\r
17764+ <PublishUrl>publish\</PublishUrl>\r
17765+ <Install>true</Install>\r
17766+ <InstallFrom>Disk</InstallFrom>\r
17767+ <UpdateEnabled>false</UpdateEnabled>\r
17768+ <UpdateMode>Foreground</UpdateMode>\r
17769+ <UpdateInterval>7</UpdateInterval>\r
17770+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
17771+ <UpdatePeriodically>false</UpdatePeriodically>\r
17772+ <UpdateRequired>false</UpdateRequired>\r
17773+ <MapFileExtensions>true</MapFileExtensions>\r
17774+ <ApplicationRevision>0</ApplicationRevision>\r
17775+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
17776+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
17777+ <UseApplicationTrust>false</UseApplicationTrust>\r
17778+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
17779+ <TargetFrameworkProfile />\r
17780+ </PropertyGroup>\r
17781+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
17782+ <DebugSymbols>true</DebugSymbols>\r
17783+ <DebugType>full</DebugType>\r
17784+ <Optimize>false</Optimize>\r
17785+ <OutputPath>..\..\console\bin\Debug\</OutputPath>\r
17786+ <DefineConstants>DEBUG;TRACE</DefineConstants>\r
17787+ <ErrorReport>prompt</ErrorReport>\r
17788+ <WarningLevel>4</WarningLevel>\r
17789+ <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.NUnit.xml</DocumentationFile>\r
17790+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
17791+ </PropertyGroup>\r
17792+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
17793+ <DebugType>pdbonly</DebugType>\r
17794+ <Optimize>true</Optimize>\r
17795+ <OutputPath>..\..\console\bin\Release\</OutputPath>\r
17796+ <DefineConstants>TRACE;RELEASE</DefineConstants>\r
17797+ <ErrorReport>prompt</ErrorReport>\r
17798+ <WarningLevel>4</WarningLevel>\r
17799+ <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.NUnit.xml</DocumentationFile>\r
17800+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
17801+ </PropertyGroup>\r
17802+ <ItemGroup>\r
17803+ <Reference Include="System" />\r
17804+ <Reference Include="System.Core">\r
17805+ <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
17806+ </Reference>\r
17807+ </ItemGroup>\r
17808+ <ItemGroup>\r
17809+ <Compile Include="..\..\AssemblyStaticInfo.cs">\r
17810+ <Link>AssemblyStaticInfo.cs</Link>\r
17811+ </Compile>\r
17812+ <Compile Include="NUnitRocks.cs" />\r
17813+ <Compile Include="NUnitRule.cs" />\r
17814+ <Compile Include="ProvideMessageOnAssertCallsRule.cs" />\r
17815+ <Compile Include="TestMethodsMustBePublicRule.cs" />\r
17816+ <Compile Include="UnitTestsMissingTestFixtureRule.cs" />\r
17817+ </ItemGroup>\r
17818+ <ItemGroup>\r
17819+ <ProjectReference Include="..\..\..\..\cecil\Mono.Cecil.csproj">\r
17820+ <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
17821+ <Name>Mono.Cecil</Name>\r
17822+ </ProjectReference>\r
17823+ <ProjectReference Include="..\..\framework\Gendarme.Framework.csproj">\r
17824+ <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>\r
17825+ <Name>Gendarme.Framework</Name>\r
17826+ </ProjectReference>\r
17827+ </ItemGroup>\r
17828+ <ItemGroup>\r
17829+ <Folder Include="Properties\" />\r
17830+ </ItemGroup>\r
17831+ <ItemGroup>\r
17832+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
17833+ <Visible>False</Visible>\r
17834+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
17835+ <Install>false</Install>\r
17836+ </BootstrapperPackage>\r
17837+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
17838+ <Visible>False</Visible>\r
17839+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
17840+ <Install>true</Install>\r
17841+ </BootstrapperPackage>\r
17842+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
17843+ <Visible>False</Visible>\r
17844+ <ProductName>Windows Installer 3.1</ProductName>\r
17845+ <Install>true</Install>\r
17846+ </BootstrapperPackage>\r
17847+ </ItemGroup>\r
17848+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
17849 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
17850 Other similar extension points exist, see Microsoft.Common.targets.
17851 <Target Name="BeforeBuild">
17852 </Target>
17853 <Target Name="AfterBuild">
17854 </Target>
17855- -->
17856+ -->\r
17857 </Project>
17858\ No newline at end of file
17859diff --git a/gendarme/rules/Gendarme.Rules.NUnit/ProvideMessageOnAssertCallsRule.cs b/gendarme/rules/Gendarme.Rules.NUnit/ProvideMessageOnAssertCallsRule.cs
17860index 4c58065..1e01a2b 100644
17861--- a/gendarme/rules/Gendarme.Rules.NUnit/ProvideMessageOnAssertCallsRule.cs
17862+++ b/gendarme/rules/Gendarme.Rules.NUnit/ProvideMessageOnAssertCallsRule.cs
17863@@ -95,7 +95,7 @@ namespace Gendarme.Rules.NUnit {
17864 continue;
17865
17866 MethodReference m = (instruction.Operand as MethodReference);
17867- if (m == null || m.DeclaringType.FullName != "NUnit.Framework.Assert" ||
17868+ if (m == null || !m.DeclaringType.IsNamed ("NUnit.Framework", "Assert") ||
17869 exceptions.Contains (m.Name))
17870 continue;
17871
17872@@ -105,7 +105,7 @@ namespace Gendarme.Rules.NUnit {
17873 if (resolvedMethod == null)
17874 continue;
17875 foreach (ParameterDefinition parameter in resolvedMethod.Parameters) {
17876- if (parameter.ParameterType.FullName == "System.String" &&
17877+ if (parameter.ParameterType.IsNamed ("System", "String") &&
17878 parameter.Name == "message") {
17879 foundMessage = true;
17880 break;
17881diff --git a/gendarme/rules/Gendarme.Rules.NUnit/README.md b/gendarme/rules/Gendarme.Rules.NUnit/README.md
17882new file mode 100644
17883index 0000000..00a3cb5
17884--- /dev/null
17885+++ b/gendarme/rules/Gendarme.Rules.NUnit/README.md
17886@@ -0,0 +1,9 @@
17887+# Gendarme.Rules.NUnit Rules
17888+
17889+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.NUnit(git)]] pages.
17890+
17891+
17892+## Feedback
17893+
17894+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
17895+
17896diff --git a/gendarme/rules/Gendarme.Rules.NUnit/Test/Tests.Rules.NUnit.csproj b/gendarme/rules/Gendarme.Rules.NUnit/Test/Tests.Rules.NUnit.csproj
17897index 411ce56..7fc3ffe 100755
17898--- a/gendarme/rules/Gendarme.Rules.NUnit/Test/Tests.Rules.NUnit.csproj
17899+++ b/gendarme/rules/Gendarme.Rules.NUnit/Test/Tests.Rules.NUnit.csproj
17900@@ -1,5 +1,5 @@
17901 <?xml version="1.0" encoding="utf-8"?>\r
17902-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
17903+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
17904 <PropertyGroup>\r
17905 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
17906 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
17907@@ -10,8 +10,28 @@
17908 <AppDesignerFolder>Properties</AppDesignerFolder>\r
17909 <RootNamespace>Tests.Rules.NUnit</RootNamespace>\r
17910 <AssemblyName>Tests.Rules.NUnit</AssemblyName>\r
17911- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
17912+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
17913 <FileAlignment>512</FileAlignment>\r
17914+ <FileUpgradeFlags>\r
17915+ </FileUpgradeFlags>\r
17916+ <OldToolsVersion>3.5</OldToolsVersion>\r
17917+ <UpgradeBackupLocation />\r
17918+ <PublishUrl>publish\</PublishUrl>\r
17919+ <Install>true</Install>\r
17920+ <InstallFrom>Disk</InstallFrom>\r
17921+ <UpdateEnabled>false</UpdateEnabled>\r
17922+ <UpdateMode>Foreground</UpdateMode>\r
17923+ <UpdateInterval>7</UpdateInterval>\r
17924+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
17925+ <UpdatePeriodically>false</UpdatePeriodically>\r
17926+ <UpdateRequired>false</UpdateRequired>\r
17927+ <MapFileExtensions>true</MapFileExtensions>\r
17928+ <ApplicationRevision>0</ApplicationRevision>\r
17929+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
17930+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
17931+ <UseApplicationTrust>false</UseApplicationTrust>\r
17932+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
17933+ <TargetFrameworkProfile />\r
17934 </PropertyGroup>\r
17935 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
17936 <DebugSymbols>true</DebugSymbols>\r
17937@@ -21,6 +41,7 @@
17938 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
17939 <ErrorReport>prompt</ErrorReport>\r
17940 <WarningLevel>4</WarningLevel>\r
17941+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
17942 </PropertyGroup>\r
17943 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
17944 <DebugType>pdbonly</DebugType>\r
17945@@ -29,6 +50,7 @@
17946 <DefineConstants>TRACE</DefineConstants>\r
17947 <ErrorReport>prompt</ErrorReport>\r
17948 <WarningLevel>4</WarningLevel>\r
17949+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
17950 </PropertyGroup>\r
17951 <ItemGroup>\r
17952 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
17953@@ -68,6 +90,23 @@
17954 <ItemGroup>\r
17955 <Folder Include="Properties\" />\r
17956 </ItemGroup>\r
17957+ <ItemGroup>\r
17958+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
17959+ <Visible>False</Visible>\r
17960+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
17961+ <Install>false</Install>\r
17962+ </BootstrapperPackage>\r
17963+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
17964+ <Visible>False</Visible>\r
17965+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
17966+ <Install>true</Install>\r
17967+ </BootstrapperPackage>\r
17968+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
17969+ <Visible>False</Visible>\r
17970+ <ProductName>Windows Installer 3.1</ProductName>\r
17971+ <Install>true</Install>\r
17972+ </BootstrapperPackage>\r
17973+ </ItemGroup>\r
17974 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
17975 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
17976 Other similar extension points exist, see Microsoft.Common.targets.
17977diff --git a/gendarme/rules/Gendarme.Rules.NUnit/UnitTestsMissingTestFixtureRule.cs b/gendarme/rules/Gendarme.Rules.NUnit/UnitTestsMissingTestFixtureRule.cs
17978index 4b0164c..daa4721 100644
17979--- a/gendarme/rules/Gendarme.Rules.NUnit/UnitTestsMissingTestFixtureRule.cs
17980+++ b/gendarme/rules/Gendarme.Rules.NUnit/UnitTestsMissingTestFixtureRule.cs
17981@@ -81,7 +81,7 @@ namespace Gendarme.Rules.NUnit {
17982 // check if TestFixture is applied to any type in the hierarchy
17983 TypeDefinition testingType = type;
17984 while (testingType != null) {
17985- if (testingType.HasAttribute ("NUnit.Framework.TestFixtureAttribute"))
17986+ if (testingType.HasAttribute ("NUnit.Framework", "TestFixtureAttribute"))
17987 return RuleResult.Success;
17988 if (testingType.BaseType != null)
17989 testingType = testingType.BaseType.Resolve ();
17990diff --git a/gendarme/rules/Gendarme.Rules.Naming/AvoidDeepNamespaceHierarchyRule.cs b/gendarme/rules/Gendarme.Rules.Naming/AvoidDeepNamespaceHierarchyRule.cs
17991index a8f2afa..f9d2783 100644
17992--- a/gendarme/rules/Gendarme.Rules.Naming/AvoidDeepNamespaceHierarchyRule.cs
17993+++ b/gendarme/rules/Gendarme.Rules.Naming/AvoidDeepNamespaceHierarchyRule.cs
17994@@ -96,7 +96,9 @@ namespace Gendarme.Rules.Naming {
17995 [DefaultValue (DefaultMaxDepth)]
17996 [Description ("The depth at which namespaces may be nested without triggering a defect.")]
17997 public int MaxDepth {
17998- get { return max_depth; }
17999+ get {
18000+ return max_depth;
18001+ }
18002 set {
18003 if (value < 1)
18004 throw new ArgumentOutOfRangeException ("MaxDepth", "Minimum: 1");
18005@@ -139,7 +141,7 @@ namespace Gendarme.Rules.Naming {
18006 if (levels == MaxDepth + 1) {
18007 if (NamespaceDefinition.IsSpecialized (ns)) {
18008 continue;
18009- } else if (ns.EndsWith (".Internal") || ns.EndsWith (".Impl")) {
18010+ } else if (ns.EndsWith (".Internal", StringComparison.Ordinal) || ns.EndsWith (".Impl", StringComparison.Ordinal)) {
18011 continue;
18012 }
18013 }
18014@@ -149,5 +151,11 @@ namespace Gendarme.Rules.Naming {
18015 }
18016 return Runner.CurrentRuleResult;
18017 }
18018+
18019+ public override string Solution {
18020+ get {
18021+ return string.Format("Try to keep the depth below {0}, with an additional one for specialization (e.g. Design, Interop, Permissions).", MaxDepth);
18022+ }
18023+ }
18024 }
18025 }
18026diff --git a/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInMethodNameRule.cs b/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInMethodNameRule.cs
18027index 305f23b..2bff9a0 100644
18028--- a/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInMethodNameRule.cs
18029+++ b/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInMethodNameRule.cs
18030@@ -26,6 +26,7 @@
18031 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18032
18033 using System;
18034+using System.Globalization;
18035
18036 using Mono.Cecil;
18037
18038@@ -138,7 +139,7 @@ namespace Gendarme.Rules.Naming {
18039 if (method_name.StartsWith (name, StringComparison.Ordinal))
18040 return RuleResult.Success;
18041
18042- int pos = method_name.LastIndexOf (name);
18043+ int pos = method_name.LastIndexOf (name, StringComparison.Ordinal);
18044 if (-1 == pos)
18045 return RuleResult.Success;
18046
18047@@ -159,10 +160,11 @@ namespace Gendarme.Rules.Naming {
18048 string msg;
18049 if (method.IsStatic) { //we already have a rule that checks if the method should be static
18050 string memberKind = GetSuggestionMemberKind (method);
18051- msg = String.Format ("Consider renaming method to '{2}', or extracting method to type '{0}' as {1} '{2}', or making an extension method of that type.",
18052+ msg = String.Format (CultureInfo.InvariantCulture,
18053+ "Consider renaming method to '{2}', or extracting method to type '{0}' as {1} '{2}', or making an extension method of that type.",
18054 p0.ParameterType, memberKind, suggestion);
18055 } else {
18056- msg = String.Format ("Consider renaming method to '{0}'.", suggestion);
18057+ msg = String.Format (CultureInfo.InvariantCulture, "Consider renaming method to '{0}'.", suggestion);
18058 }
18059
18060 Runner.Report (method, severity, confidence, msg);
18061@@ -184,7 +186,7 @@ namespace Gendarme.Rules.Naming {
18062
18063 private static string GetSuggestionMemberKind (IMethodSignature method)
18064 {
18065- if (method.Parameters.Count == 1 && method.ReturnType.FullName != "System.Void")
18066+ if (method.Parameters.Count == 1 && !method.ReturnType.IsNamed ("System", "Void"))
18067 return "property";
18068 return "method";
18069 }
18070diff --git a/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInTypeNameRule.cs b/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInTypeNameRule.cs
18071index b050cb5..7a36180 100644
18072--- a/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInTypeNameRule.cs
18073+++ b/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInTypeNameRule.cs
18074@@ -27,6 +27,7 @@
18075
18076 using System;
18077 using System.Collections.Generic;
18078+using System.Globalization;
18079
18080 using Mono.Cecil;
18081
18082@@ -94,6 +95,7 @@ namespace Gendarme.Rules.Naming {
18083 [Problem ("This type name is prefixed with the last component of its enclosing namespace. This usually makes an API more verbose and less autocompletion-friendly than necessary.")]
18084 [Solution ("Remove the prefix from the type or replace it with a more meaningful term in the context of the namespace.")]
18085 [EngineDependency (typeof (NamespaceEngine))]
18086+ [FxCopCompatibility ("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
18087 public class AvoidRedundancyInTypeNameRule : Rule, ITypeRule {
18088
18089 public RuleResult CheckType (TypeDefinition type)
18090@@ -153,7 +155,7 @@ namespace Gendarme.Rules.Naming {
18091 //main goal is to keep the API as simple as possible so this is more severe for visible types
18092 Severity severity = type.IsVisible () ? Severity.Medium : Severity.Low;
18093
18094- string msg = String.Format ("Consider renaming type to '{0}'.", suggestion);
18095+ string msg = String.Format (CultureInfo.InvariantCulture, "Consider renaming type to '{0}'.", suggestion);
18096 Runner.Report (type, severity, Confidence.Normal, msg);
18097 return RuleResult.Failure;
18098 }
18099diff --git a/gendarme/rules/Gendarme.Rules.Naming/AvoidTypeInterfaceInconsistencyRule.cs b/gendarme/rules/Gendarme.Rules.Naming/AvoidTypeInterfaceInconsistencyRule.cs
18100index 0570b72..0d47376 100644
18101--- a/gendarme/rules/Gendarme.Rules.Naming/AvoidTypeInterfaceInconsistencyRule.cs
18102+++ b/gendarme/rules/Gendarme.Rules.Naming/AvoidTypeInterfaceInconsistencyRule.cs
18103@@ -92,11 +92,11 @@ namespace Gendarme.Rules.Naming {
18104 if (name [0] != 'I')
18105 return RuleResult.DoesNotApply;
18106
18107- string candidate_name = String.Concat (type.Namespace, ".", name.Substring (1));
18108- TypeDefinition candidate = type.Module.GetType (candidate_name);
18109+ string nspace = type.Namespace;
18110+ TypeDefinition candidate = type.Module.GetType (nspace, name.Substring (1));
18111 if (candidate != null) {
18112 // does Foo implement IFoo ?
18113- if (!candidate.Implements (type.FullName)) {
18114+ if (!candidate.Implements (nspace, name)) {
18115 Runner.Report (candidate, Severity.High, Confidence.High);
18116 }
18117 }
18118diff --git a/gendarme/rules/Gendarme.Rules.Naming/DetectNonAlphaNumericsInTypeNamesRule.cs b/gendarme/rules/Gendarme.Rules.Naming/DetectNonAlphaNumericsInTypeNamesRule.cs
18119index 9bb8063..972d031 100644
18120--- a/gendarme/rules/Gendarme.Rules.Naming/DetectNonAlphaNumericsInTypeNamesRule.cs
18121+++ b/gendarme/rules/Gendarme.Rules.Naming/DetectNonAlphaNumericsInTypeNamesRule.cs
18122@@ -98,9 +98,6 @@ namespace Gendarme.Rules.Naming {
18123 [FxCopCompatibility ("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")]
18124 public class AvoidNonAlphanumericIdentifierRule : Rule, IAssemblyRule, IMethodRule, ITypeRule {
18125
18126- private const string GuidAttribute = "System.Runtime.InteropServices.GuidAttribute";
18127- private const string InterfaceTypeAttribute = "System.Runtime.InteropServices.InterfaceTypeAttribute";
18128-
18129 // Compiler generates an error for any other non alpha-numerics than underscore ('_'),
18130 // so we just need to check the presence of underscore in method names
18131 private static bool CheckName (string name, bool special)
18132@@ -111,8 +108,8 @@ namespace Gendarme.Rules.Naming {
18133
18134 private static bool UsedForComInterop (TypeDefinition type)
18135 {
18136- return (type.IsInterface && type.HasAttribute (GuidAttribute) &&
18137- type.HasAttribute (InterfaceTypeAttribute));
18138+ return (type.IsInterface && type.HasAttribute ("System.Runtime.InteropServices", "GuidAttribute") &&
18139+ type.HasAttribute ("System.Runtime.InteropServices", "InterfaceTypeAttribute"));
18140 }
18141
18142 public RuleResult CheckAssembly (AssemblyDefinition assembly)
18143diff --git a/gendarme/rules/Gendarme.Rules.Naming/Gendarme.Rules.Naming.csproj b/gendarme/rules/Gendarme.Rules.Naming/Gendarme.Rules.Naming.csproj
18144index bfb1fbe..8de71e4 100755
18145--- a/gendarme/rules/Gendarme.Rules.Naming/Gendarme.Rules.Naming.csproj
18146+++ b/gendarme/rules/Gendarme.Rules.Naming/Gendarme.Rules.Naming.csproj
18147@@ -1,5 +1,5 @@
18148 <?xml version="1.0" encoding="utf-8"?>\r
18149-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
18150+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
18151 <PropertyGroup>\r
18152 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
18153 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
18154@@ -10,8 +10,28 @@
18155 <AppDesignerFolder>Properties</AppDesignerFolder>\r
18156 <RootNamespace>Gendarme.Rules.Naming</RootNamespace>\r
18157 <AssemblyName>Gendarme.Rules.Naming</AssemblyName>\r
18158- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
18159+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
18160 <FileAlignment>512</FileAlignment>\r
18161+ <FileUpgradeFlags>\r
18162+ </FileUpgradeFlags>\r
18163+ <OldToolsVersion>3.5</OldToolsVersion>\r
18164+ <UpgradeBackupLocation />\r
18165+ <PublishUrl>publish\</PublishUrl>\r
18166+ <Install>true</Install>\r
18167+ <InstallFrom>Disk</InstallFrom>\r
18168+ <UpdateEnabled>false</UpdateEnabled>\r
18169+ <UpdateMode>Foreground</UpdateMode>\r
18170+ <UpdateInterval>7</UpdateInterval>\r
18171+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
18172+ <UpdatePeriodically>false</UpdatePeriodically>\r
18173+ <UpdateRequired>false</UpdateRequired>\r
18174+ <MapFileExtensions>true</MapFileExtensions>\r
18175+ <ApplicationRevision>0</ApplicationRevision>\r
18176+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
18177+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
18178+ <UseApplicationTrust>false</UseApplicationTrust>\r
18179+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
18180+ <TargetFrameworkProfile />\r
18181 </PropertyGroup>\r
18182 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
18183 <DebugSymbols>true</DebugSymbols>\r
18184@@ -24,6 +44,7 @@
18185 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Naming.xml</DocumentationFile>\r
18186 <NoWarn>1591</NoWarn>\r
18187 <WarningsAsErrors>1570</WarningsAsErrors>\r
18188+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
18189 </PropertyGroup>\r
18190 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
18191 <DebugType>pdbonly</DebugType>\r
18192@@ -35,6 +56,7 @@
18193 <NoWarn>1591</NoWarn>\r
18194 <WarningsAsErrors>1570</WarningsAsErrors>\r
18195 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Naming.xml</DocumentationFile>\r
18196+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
18197 </PropertyGroup>\r
18198 <ItemGroup>\r
18199 <Compile Include="..\..\AssemblyStaticInfo.cs">\r
18200@@ -72,6 +94,23 @@
18201 <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
18202 </Reference>\r
18203 </ItemGroup>\r
18204+ <ItemGroup>\r
18205+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
18206+ <Visible>False</Visible>\r
18207+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
18208+ <Install>false</Install>\r
18209+ </BootstrapperPackage>\r
18210+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
18211+ <Visible>False</Visible>\r
18212+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
18213+ <Install>true</Install>\r
18214+ </BootstrapperPackage>\r
18215+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
18216+ <Visible>False</Visible>\r
18217+ <ProductName>Windows Installer 3.1</ProductName>\r
18218+ <Install>true</Install>\r
18219+ </BootstrapperPackage>\r
18220+ </ItemGroup>\r
18221 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
18222 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
18223 Other similar extension points exist, see Microsoft.Common.targets.
18224diff --git a/gendarme/rules/Gendarme.Rules.Naming/ParameterNamesShouldMatchOverridenMethodRule.cs b/gendarme/rules/Gendarme.Rules.Naming/ParameterNamesShouldMatchOverridenMethodRule.cs
18225index 95a3e46..7e4a8db 100644
18226--- a/gendarme/rules/Gendarme.Rules.Naming/ParameterNamesShouldMatchOverridenMethodRule.cs
18227+++ b/gendarme/rules/Gendarme.Rules.Naming/ParameterNamesShouldMatchOverridenMethodRule.cs
18228@@ -3,8 +3,10 @@
18229 //
18230 // Authors:
18231 // Andreas Noever <andreas.noever@gmail.com>
18232+// Sebastien Pouliot <sebastien@ximian.com>
18233 //
18234 // (C) 2008 Andreas Noever
18235+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
18236 //
18237 // Permission is hereby granted, free of charge, to any person obtaining
18238 // a copy of this software and associated documentation files (the
18239@@ -84,8 +86,10 @@ namespace Gendarme.Rules.Naming {
18240 base.Initialize (runner);
18241
18242 //check if this is a Boo assembly using macros
18243- Runner.AnalyzeAssembly += delegate (object o, RunnerEventArgs e) {
18244- IsBooAssemblyUsingMacro = (e.CurrentAssembly.MainModule.HasTypeReference (BooMacroStatement));
18245+ Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
18246+ IsBooAssemblyUsingMacro = (e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
18247+ return tr.IsNamed ("Boo.Lang.Compiler.Ast", "MacroStatement");
18248+ }));
18249 };
18250 }
18251
18252@@ -97,29 +101,26 @@ namespace Gendarme.Rules.Naming {
18253 if (name != base_name) {
18254 if (!explicitInterfaceCheck)
18255 return false;
18256- string full_name = baseMethod.DeclaringType.FullName;
18257- if (!name.StartsWith (full_name, StringComparison.Ordinal))
18258+
18259+ TypeReference btype = baseMethod.DeclaringType;
18260+ string bnspace = btype.Namespace;
18261+ if (!name.StartsWith (bnspace, StringComparison.Ordinal))
18262 return false;
18263- if (name [full_name.Length] != '.')
18264+ if (name [bnspace.Length] != '.')
18265 return false;
18266- if (name.LastIndexOf (base_name, StringComparison.Ordinal) != full_name.Length + 1)
18267+
18268+ string bname = btype.Name;
18269+ if (String.CompareOrdinal (bname, 0, name, bnspace.Length + 1, bname.Length) != 0)
18270 return false;
18271- }
18272- if (method.ReturnType.FullName != baseMethod.ReturnType.FullName)
18273- return false;
18274- if (method.HasParameters != baseMethod.HasParameters)
18275- return false;
18276
18277- IList<ParameterDefinition> pdc = method.Parameters;
18278- IList<ParameterDefinition> base_pdc = baseMethod.Parameters;
18279- if (pdc.Count != base_pdc.Count)
18280- return false;
18281+ int dot = bnspace.Length + bname.Length + 1;
18282+ if (name [dot] != '.')
18283+ return false;
18284
18285- for (int i = 0; i < pdc.Count; i++) {
18286- if (pdc [i].ParameterType != base_pdc [i].ParameterType)
18287+ if (name.LastIndexOf (base_name, StringComparison.Ordinal) != dot + 1)
18288 return false;
18289 }
18290- return true;
18291+ return method.CompareSignature (baseMethod);
18292 }
18293
18294 private static MethodDefinition GetBaseMethod (MethodDefinition method)
18295@@ -130,7 +131,7 @@ namespace Gendarme.Rules.Naming {
18296
18297 while ((baseType.BaseType != null) && (baseType != baseType.BaseType)) {
18298 baseType = baseType.BaseType.Resolve ();
18299- if (baseType == null)
18300+ if ((baseType == null) || !baseType.HasMethods)
18301 return null; // could not resolve
18302
18303 foreach (MethodDefinition baseMethodCandidate in baseType.Methods) {
18304@@ -143,11 +144,15 @@ namespace Gendarme.Rules.Naming {
18305
18306 private static MethodDefinition GetInterfaceMethod (MethodDefinition method)
18307 {
18308- TypeDefinition type = (TypeDefinition) method.DeclaringType;
18309+ TypeDefinition type = (method.DeclaringType as TypeDefinition);
18310+ if (!type.HasInterfaces)
18311+ return null;
18312+
18313 foreach (TypeReference interfaceReference in type.Interfaces) {
18314 TypeDefinition interfaceCandidate = interfaceReference.Resolve ();
18315- if (interfaceCandidate == null)
18316+ if ((interfaceCandidate == null) || !interfaceCandidate.HasMethods)
18317 continue;
18318+
18319 foreach (MethodDefinition interfaceMethodCandidate in interfaceCandidate.Methods) {
18320 if (SignatureMatches (method, interfaceMethodCandidate, true))
18321 return interfaceMethodCandidate;
18322@@ -177,7 +182,8 @@ namespace Gendarme.Rules.Naming {
18323 IList<ParameterDefinition> pdc = method.Parameters;
18324 for (int i = 0; i < pdc.Count; i++) {
18325 if (pdc [i].Name != base_pdc [i].Name) {
18326- string s = string.Format ("The name of parameter #{0} ({1}) does not match the name of the parameter in the overriden method ({2}).",
18327+ string s = String.Format (CultureInfo.InvariantCulture,
18328+ "The name of parameter #{0} ({1}) does not match the name of the parameter in the overriden method ({2}).",
18329 i + 1, pdc [i].Name, base_pdc [i].Name);
18330 Runner.Report (method, Severity.Medium, Confidence.High, s);
18331 }
18332@@ -185,21 +191,11 @@ namespace Gendarme.Rules.Naming {
18333 return Runner.CurrentRuleResult;
18334 }
18335
18336- private const string BooMacroStatement = "Boo.Lang.Compiler.Ast.MacroStatement";
18337-
18338- private bool IsBooAssemblyUsingMacro {
18339- get {
18340- return isBooAssemblyUsingMacro;
18341- }
18342- set {
18343- isBooAssemblyUsingMacro = value;
18344- }
18345- }
18346- private bool isBooAssemblyUsingMacro;
18347+ private bool IsBooAssemblyUsingMacro { get; set; }
18348
18349 private static bool IsBooMacroParameter (ParameterReference p)
18350 {
18351- return p.Name == "macro" && p.ParameterType.FullName == BooMacroStatement;
18352+ return p.Name == "macro" && p.ParameterType.IsNamed ("Boo.Lang.Compiler.Ast", "MacroStatement");
18353 }
18354 }
18355 }
18356diff --git a/gendarme/rules/Gendarme.Rules.Naming/README.md b/gendarme/rules/Gendarme.Rules.Naming/README.md
18357new file mode 100644
18358index 0000000..a5e5992
18359--- /dev/null
18360+++ b/gendarme/rules/Gendarme.Rules.Naming/README.md
18361@@ -0,0 +1,9 @@
18362+# Gendarme.Rules.Naming Rules
18363+
18364+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Naming(git)]] pages.
18365+
18366+
18367+## Feedback
18368+
18369+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
18370+
18371diff --git a/gendarme/rules/Gendarme.Rules.Naming/Test/ParameterNamesShouldMatchOverridenMethodTest.cs b/gendarme/rules/Gendarme.Rules.Naming/Test/ParameterNamesShouldMatchOverridenMethodTest.cs
18372index ff5fc3a..7baa37f 100644
18373--- a/gendarme/rules/Gendarme.Rules.Naming/Test/ParameterNamesShouldMatchOverridenMethodTest.cs
18374+++ b/gendarme/rules/Gendarme.Rules.Naming/Test/ParameterNamesShouldMatchOverridenMethodTest.cs
18375@@ -3,8 +3,10 @@
18376 //
18377 // Authors:
18378 // Andreas Noever <andreas.noever@gmail.com>
18379+// Sebastien Pouliot <sebastien@ximian.com>
18380 //
18381 // (C) 2008 Andreas Noever
18382+// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
18383 //
18384 // Permission is hereby granted, free of charge, to any person obtaining
18385 // a copy of this software and associated documentation files (the
18386@@ -27,15 +29,12 @@
18387 //
18388
18389 using System;
18390-using System.Reflection;
18391
18392-using Gendarme.Framework;
18393+using Gendarme.Framework.Helpers;
18394 using Gendarme.Rules.Naming;
18395-using Gendarme.Framework.Rocks;
18396-using Mono.Cecil;
18397
18398 using NUnit.Framework;
18399-using Test.Rules.Helpers;
18400+using Test.Rules.Fixtures;
18401
18402 namespace Test.Rules.Naming {
18403
18404@@ -75,141 +74,94 @@ namespace Test.Rules.Naming {
18405 }
18406
18407 [TestFixture]
18408- public class ParameterNamesShouldMatchOverridenMethodTest : BaseClass, ISomeInterface, ISomeInterface2 {
18409+ public class ParameterNamesShouldMatchOverridenMethodTest : MethodRuleTestFixture<ParameterNamesShouldMatchOverriddenMethodRule> {
18410
18411- private ParameterNamesShouldMatchOverriddenMethodRule rule;
18412- private AssemblyDefinition assembly;
18413- private TypeDefinition type;
18414- private TestRunner runner;
18415+ class TestCase : BaseClass, ISomeInterface, ISomeInterface2, IEquatable<string> {
18416+ protected override void VirtualCorrect (int vc1, int vc2)
18417+ {
18418+ }
18419
18420- [TestFixtureSetUp]
18421- public void FixtureSetUp ()
18422- {
18423- string unit = Assembly.GetExecutingAssembly ().Location;
18424- assembly = AssemblyDefinition.ReadAssembly (unit);
18425- type = assembly.MainModule.GetType ("Test.Rules.Naming.ParameterNamesShouldMatchOverridenMethodTest");
18426- rule = new ParameterNamesShouldMatchOverriddenMethodRule ();
18427- runner = new TestRunner (rule);
18428- }
18429+ protected override void VirtualIncorrect (int vi1, int vi2a)
18430+ {
18431+ }
18432
18433- private MethodDefinition GetTest (string name)
18434- {
18435- foreach (MethodDefinition method in type.Methods) {
18436- if (method.Name == name)
18437- return method;
18438+ protected override void VirtualSuperIncorrect (int vsi1, bool vsi2_)
18439+ {
18440 }
18441- return null;
18442- }
18443
18444- protected override void VirtualCorrect (int vc1, int vc2)
18445- {
18446- }
18447+ protected override void AbstractCorrect (int ac1, int ac2)
18448+ {
18449+ throw new NotImplementedException ();
18450+ }
18451
18452- [Test]
18453- public void TestVirtualCorrect ()
18454- {
18455- MethodDefinition method = GetTest ("VirtualCorrect");
18456- Assert.AreEqual (RuleResult.Success, runner.CheckMethod (method), "RuleResult");
18457- Assert.AreEqual (0, runner.Defects.Count, "Count");
18458- }
18459+ protected override void AbstractIncorrect (int ai1, int ai2_)
18460+ {
18461+ throw new NotImplementedException ();
18462+ }
18463
18464- protected override void VirtualIncorrect (int vi1, int vi2a)
18465- {
18466- }
18467+ protected virtual void NoOverwrite (int a, int bb)
18468+ {
18469+ }
18470
18471- [Test]
18472- public void TestVirtualIncorrect ()
18473- {
18474- MethodDefinition method = GetTest ("VirtualIncorrect");
18475- Assert.AreEqual (RuleResult.Failure, runner.CheckMethod (method), "RuleResult");
18476- Assert.AreEqual (1, runner.Defects.Count, "Count");
18477- }
18478+ public bool InterfaceMethod (int im_)
18479+ {
18480+ return false;
18481+ }
18482
18483- protected override void VirtualSuperIncorrect (int vsi1, bool vsi2_)
18484- {
18485- }
18486+ bool ISomeInterface2.InterfaceMethod2 (int im_)
18487+ {
18488+ return false;
18489+ }
18490
18491- [Test]
18492- public void TestVirtualSuperIncorrect ()
18493- {
18494- MethodDefinition method = GetTest ("VirtualSuperIncorrect");
18495- Assert.AreEqual (RuleResult.Failure, runner.CheckMethod (method), "RuleResult");
18496- Assert.AreEqual (1, runner.Defects.Count, "Count");
18497- }
18498+ void NoParameter ()
18499+ {
18500+ }
18501
18502- protected override void AbstractCorrect (int ac1, int ac2)
18503- {
18504- throw new NotImplementedException ();
18505+ public bool Equals (string s)
18506+ {
18507+ throw new NotImplementedException ();
18508+ }
18509 }
18510
18511 [Test]
18512- public void TestAbstractCorrect ()
18513+ public void TestVirtual ()
18514 {
18515- MethodDefinition method = GetTest ("AbstractCorrect");
18516- Assert.AreEqual (RuleResult.Success, runner.CheckMethod (method), "RuleResult");
18517- Assert.AreEqual (0, runner.Defects.Count, "Count");
18518- }
18519-
18520- protected override void AbstractIncorrect (int ai1, int ai2_)
18521- {
18522- throw new NotImplementedException ();
18523+ AssertRuleSuccess<TestCase> ("VirtualCorrect");
18524+ AssertRuleFailure<TestCase> ("VirtualIncorrect", 1);
18525+ AssertRuleFailure<TestCase> ("VirtualSuperIncorrect", 1);
18526 }
18527
18528 [Test]
18529- public void TestAbstractIncorrect ()
18530- {
18531- MethodDefinition method = GetTest ("AbstractIncorrect");
18532- Assert.AreEqual (RuleResult.Failure, runner.CheckMethod (method), "RuleResult");
18533- Assert.AreEqual (1, runner.Defects.Count, "Count");
18534- }
18535-
18536- protected virtual void NoOverwrite (int a, int bb)
18537+ public void TestAbstract ()
18538 {
18539+ AssertRuleSuccess<TestCase> ("AbstractCorrect");
18540+ AssertRuleFailure<TestCase> ("AbstractIncorrect", 1);
18541 }
18542
18543 [Test]
18544 public void TestNoOverwrite ()
18545 {
18546- MethodDefinition method = GetTest ("NoOverwrite");
18547- Assert.AreEqual (RuleResult.Success, runner.CheckMethod (method), "RuleResult");
18548- Assert.AreEqual (0, runner.Defects.Count, "Count");
18549- }
18550-
18551- public bool InterfaceMethod (int im_)
18552- {
18553- return false;
18554+ AssertRuleSuccess<TestCase> ("NoOverwrite");
18555 }
18556
18557 [Test]
18558 public void TestInterfaceMethod ()
18559 {
18560- MethodDefinition method = GetTest ("InterfaceMethod");
18561- Assert.AreEqual (RuleResult.Failure, runner.CheckMethod (method), "RuleResult");
18562- Assert.AreEqual (1, runner.Defects.Count, "Count");
18563- }
18564-
18565- bool ISomeInterface2.InterfaceMethod2 (int im_)
18566- {
18567- return false;
18568+ AssertRuleFailure<TestCase> ("InterfaceMethod", 1);
18569+ AssertRuleFailure<TestCase> ("Test.Rules.Naming.ISomeInterface2.InterfaceMethod2", 1);
18570 }
18571
18572 [Test]
18573- public void TestInterfaceMethod2 ()
18574- {
18575- MethodDefinition method = GetTest ("Test.Rules.Naming.ISomeInterface2.InterfaceMethod2");
18576- Assert.AreEqual (RuleResult.Failure, runner.CheckMethod (method), "RuleResult");
18577- Assert.AreEqual (1, runner.Defects.Count, "Count");
18578- }
18579-
18580- void NoParameter ()
18581+ public void TestDoesNotApply ()
18582 {
18583+ AssertRuleDoesNotApply<TestCase> ("NoParameter");
18584 }
18585
18586 [Test]
18587- public void TestDoesNotApply ()
18588+ public void GenericInterface ()
18589 {
18590- MethodDefinition method = GetTest ("NoParameter");
18591- Assert.AreEqual (RuleResult.DoesNotApply, runner.CheckMethod (method), "RuleResult");
18592+ AssertRuleSuccess<OpCodeBitmask> ("Equals", new Type [] { typeof (OpCodeBitmask) });
18593+ AssertRuleFailure<TestCase> ("Equals", 1);
18594 }
18595 }
18596 }
18597diff --git a/gendarme/rules/Gendarme.Rules.Naming/Test/Tests.Rules.Naming.csproj b/gendarme/rules/Gendarme.Rules.Naming/Test/Tests.Rules.Naming.csproj
18598index 549c8b8..549dc4d 100755
18599--- a/gendarme/rules/Gendarme.Rules.Naming/Test/Tests.Rules.Naming.csproj
18600+++ b/gendarme/rules/Gendarme.Rules.Naming/Test/Tests.Rules.Naming.csproj
18601@@ -1,5 +1,5 @@
18602 <?xml version="1.0" encoding="utf-8"?>\r
18603-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
18604+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
18605 <PropertyGroup>\r
18606 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
18607 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
18608@@ -10,8 +10,28 @@
18609 <AppDesignerFolder>Properties</AppDesignerFolder>\r
18610 <RootNamespace>Tests.Rules.Naming</RootNamespace>\r
18611 <AssemblyName>Tests.Rules.Naming</AssemblyName>\r
18612- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
18613+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
18614 <FileAlignment>512</FileAlignment>\r
18615+ <FileUpgradeFlags>\r
18616+ </FileUpgradeFlags>\r
18617+ <OldToolsVersion>3.5</OldToolsVersion>\r
18618+ <UpgradeBackupLocation />\r
18619+ <PublishUrl>publish\</PublishUrl>\r
18620+ <Install>true</Install>\r
18621+ <InstallFrom>Disk</InstallFrom>\r
18622+ <UpdateEnabled>false</UpdateEnabled>\r
18623+ <UpdateMode>Foreground</UpdateMode>\r
18624+ <UpdateInterval>7</UpdateInterval>\r
18625+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
18626+ <UpdatePeriodically>false</UpdatePeriodically>\r
18627+ <UpdateRequired>false</UpdateRequired>\r
18628+ <MapFileExtensions>true</MapFileExtensions>\r
18629+ <ApplicationRevision>0</ApplicationRevision>\r
18630+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
18631+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
18632+ <UseApplicationTrust>false</UseApplicationTrust>\r
18633+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
18634+ <TargetFrameworkProfile />\r
18635 </PropertyGroup>\r
18636 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
18637 <DebugSymbols>true</DebugSymbols>\r
18638@@ -21,6 +41,7 @@
18639 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
18640 <ErrorReport>prompt</ErrorReport>\r
18641 <WarningLevel>4</WarningLevel>\r
18642+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
18643 </PropertyGroup>\r
18644 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
18645 <DebugType>pdbonly</DebugType>\r
18646@@ -29,6 +50,7 @@
18647 <DefineConstants>TRACE</DefineConstants>\r
18648 <ErrorReport>prompt</ErrorReport>\r
18649 <WarningLevel>4</WarningLevel>\r
18650+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
18651 </PropertyGroup>\r
18652 <ItemGroup>\r
18653 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
18654@@ -76,6 +98,23 @@
18655 <ItemGroup>\r
18656 <Folder Include="Properties\" />\r
18657 </ItemGroup>\r
18658+ <ItemGroup>\r
18659+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
18660+ <Visible>False</Visible>\r
18661+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
18662+ <Install>false</Install>\r
18663+ </BootstrapperPackage>\r
18664+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
18665+ <Visible>False</Visible>\r
18666+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
18667+ <Install>true</Install>\r
18668+ </BootstrapperPackage>\r
18669+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
18670+ <Visible>False</Visible>\r
18671+ <ProductName>Windows Installer 3.1</ProductName>\r
18672+ <Install>true</Install>\r
18673+ </BootstrapperPackage>\r
18674+ </ItemGroup>\r
18675 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
18676 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
18677 Other similar extension points exist, see Microsoft.Common.targets.
18678diff --git a/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectPrefixTest.cs b/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectPrefixTest.cs
18679index 7ac6880..7000340 100644
18680--- a/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectPrefixTest.cs
18681+++ b/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectPrefixTest.cs
18682@@ -54,6 +54,10 @@ namespace Test.Rules.Naming {
18683 public class ILRange {
18684 }
18685
18686+ public class InMemoryDoohicky
18687+ {
18688+ }
18689+
18690 public interface I {
18691 }
18692
18693@@ -102,6 +106,7 @@ namespace Test.Rules.Naming {
18694 AssertRuleFailure<CIncorrectClass> (1);
18695 AssertRuleFailure<INcorrectClass> (1);
18696 AssertRuleSuccess<ILRange> ();
18697+ AssertRuleSuccess<InMemoryDoohicky> ();
18698 }
18699
18700 [Test]
18701diff --git a/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectSuffixTest.cs b/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectSuffixTest.cs
18702index adb15fa..0fc5205 100644
18703--- a/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectSuffixTest.cs
18704+++ b/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectSuffixTest.cs
18705@@ -176,13 +176,8 @@ namespace Test.Rules.Naming {
18706 }
18707 }
18708
18709- public class DerivingClassImplementingInterfaces : EventArgs, IEnumerable, IPermission {
18710+ public class DerivingClassImplementingInterfaces : EventArgs, IPermission {
18711
18712- public IEnumerator GetEnumerator ()
18713- {
18714- throw new NotImplementedException();
18715- }
18716-
18717 public void FromXml (SecurityElement e)
18718 {
18719 throw new NotImplementedException();
18720@@ -246,16 +241,27 @@ namespace Test.Rules.Naming {
18721 public class DictionaryIncorrectDerived<T, V> : DictionaryIncorrect<T, V> {
18722 }
18723
18724+ // test case from https://github.com/Iristyle/mono-tools/commit/40bfb2260511cfe4171e9153c3c434fedd8a4d4a.diff
18725+
18726+ public class CorrectCollectionAndDictionary<T, V> : Dictionary<T, V>, ICollection<V> {
18727+ public void Add(V item) { throw new NotImplementedException(); }
18728+ public bool Contains(V item) { throw new NotImplementedException(); }
18729+ public void CopyTo(V[] array, int arrayIndex) { throw new NotImplementedException(); }
18730+ public bool IsReadOnly { get { throw new NotImplementedException(); } }
18731+ public bool Remove(V item) { throw new NotImplementedException(); }
18732+ public new IEnumerator<V> GetEnumerator() { throw new NotImplementedException(); }
18733+ }
18734+
18735 [TestFixture]
18736 public class UseCorrectSuffixTest : TypeRuleTestFixture<UseCorrectSuffixRule> {
18737
18738- void AssertRuleFailureWithHighConfidence<T>()
18739+ void AssertRuleFailureWithHighConfidence<T> (int num)
18740 {
18741- AssertRuleFailure<T> (1);
18742+ AssertRuleFailure<T> (num);
18743 Assert.AreEqual (Confidence.High, Runner.Defects [0].Confidence, typeof (T).Name);
18744 }
18745
18746- void AssertRuleFailureWithLowConfidence<T>()
18747+ void AssertRuleFailureWithLowConfidence<T> ()
18748 {
18749 AssertRuleFailure<T> (1);
18750 Assert.AreEqual (Confidence.Low, Runner.Defects [0].Confidence, typeof (T).Name);
18751@@ -270,7 +276,7 @@ namespace Test.Rules.Naming {
18752 [Test]
18753 public void TestOneLevelInheritanceIncorrectName ()
18754 {
18755- AssertRuleFailureWithHighConfidence<IncorrectAttr> ();
18756+ AssertRuleFailureWithHighConfidence<IncorrectAttr> (1);
18757 }
18758
18759 [Test]
18760@@ -288,7 +294,7 @@ namespace Test.Rules.Naming {
18761 [Test]
18762 public void TestVariousLevelInheritanceIncorrectName ()
18763 {
18764- AssertRuleFailureWithHighConfidence<OtherAttr> ();
18765+ AssertRuleFailureWithHighConfidence<OtherAttr> (1);
18766 }
18767
18768 [Test]
18769@@ -326,7 +332,7 @@ namespace Test.Rules.Naming {
18770 [Test]
18771 public void TestMultipleInterfaceImplementerIncorrectName ()
18772 {
18773- AssertRuleFailureWithHighConfidence<MultipleInterfaceImplementer> ();
18774+ AssertRuleFailureWithHighConfidence<MultipleInterfaceImplementer> (1);
18775 }
18776
18777 [Test]
18778@@ -342,7 +348,7 @@ namespace Test.Rules.Naming {
18779 {
18780 //this type derives from an incorrect base type, but also introduce its own defect
18781 //hence it has high confidence
18782- AssertRuleFailureWithHighConfidence<IncorrectICollectionImplementer> ();
18783+ AssertRuleFailureWithHighConfidence<IncorrectICollectionImplementer> (1);
18784 }
18785
18786 [Test]
18787@@ -360,23 +366,24 @@ namespace Test.Rules.Naming {
18788 [Test]
18789 public void TestDerivingClassImplementingInterfacesAnotherIncorrectName ()
18790 {
18791- //this type derives from an incorrect base type, *without* introducing its own defect
18792- //hence it has low confidence
18793- AssertRuleFailureWithLowConfidence<IncorrectDerivingClassImplementingInterfacesCollection> ();
18794+ //this type derives from an incorrect base type
18795+ AssertRuleFailureWithHighConfidence<IncorrectDerivingClassImplementingInterfacesCollection> (2);
18796 }
18797
18798 [Test]
18799 public void GenericCollection ()
18800 {
18801 AssertRuleSuccess<CorrectCollection<int>> ();
18802- AssertRuleFailureWithHighConfidence<CollectionIncorrect<int>> ();
18803+ AssertRuleFailureWithHighConfidence<CollectionIncorrect<int>> (1);
18804 }
18805
18806 [Test]
18807 public void GenericDictionary ()
18808 {
18809 AssertRuleSuccess<CorrectDictionary<int,int>> ();
18810- AssertRuleFailureWithHighConfidence<DictionaryIncorrect<int,int>> ();
18811+ // to be consistent with FxCop, a class implementing IDictionary and ICollection should end in Dictionary
18812+ AssertRuleSuccess<CorrectCollectionAndDictionary<int, int>> ();
18813+ AssertRuleFailureWithHighConfidence<DictionaryIncorrect<int, int>> (1);
18814 }
18815
18816 [Test]
18817@@ -410,11 +417,11 @@ namespace Test.Rules.Naming {
18818 public void CheckShouldNeverBeUsedSuffixes ()
18819 {
18820 AssertRuleSuccess<My> ();
18821- AssertRuleFailureWithHighConfidence<MyDelegate> ();
18822- AssertRuleFailureWithHighConfidence<MyEnum> ();
18823- AssertRuleFailureWithHighConfidence<MyFlags> ();
18824- AssertRuleFailureWithHighConfidence<MyEx> ();
18825- AssertRuleFailureWithHighConfidence<MyImpl> ();
18826+ AssertRuleFailureWithHighConfidence<MyDelegate> (1);
18827+ AssertRuleFailureWithHighConfidence<MyEnum> (1);
18828+ AssertRuleFailureWithHighConfidence<MyFlags> (1);
18829+ AssertRuleFailureWithHighConfidence<MyEx> (1);
18830+ AssertRuleFailureWithHighConfidence<MyImpl> (1);
18831 }
18832
18833 class MyCollection : EventArgs {
18834@@ -467,16 +474,16 @@ namespace Test.Rules.Naming {
18835 public void EnumName ()
18836 {
18837 AssertRuleSuccess<ReturnValue> ();
18838- AssertRuleFailureWithHighConfidence<ReturnValueEnum> ();
18839- AssertRuleFailureWithHighConfidence<returnvalueenum> ();
18840+ AssertRuleFailureWithHighConfidence<ReturnValueEnum> (1);
18841+ AssertRuleFailureWithHighConfidence<returnvalueenum> (1);
18842 }
18843
18844 [Test]
18845 public void FlagsName ()
18846 {
18847 AssertRuleSuccess<ReturnValues> ();
18848- AssertRuleFailureWithHighConfidence<ReturnValuesFlags> ();
18849- AssertRuleFailureWithHighConfidence<returnvaluesflags> ();
18850+ AssertRuleFailureWithHighConfidence<ReturnValuesFlags> (1);
18851+ AssertRuleFailureWithHighConfidence<returnvaluesflags> (1);
18852 }
18853 }
18854 }
18855diff --git a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectCasingRule.cs b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectCasingRule.cs
18856index 32cec08..6a6252b 100644
18857--- a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectCasingRule.cs
18858+++ b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectCasingRule.cs
18859@@ -30,6 +30,7 @@
18860
18861 using System;
18862 using System.Collections.Generic;
18863+using System.Globalization;
18864 using System.Linq;
18865
18866 using Mono.Cecil;
18867@@ -96,7 +97,7 @@ namespace Gendarme.Rules.Naming {
18868 return name.ToUpperInvariant ();
18869
18870 int index = IndexOfFirstCorrectChar (name);
18871- return Char.ToUpperInvariant (name [index]).ToString () + name.Substring (index + 1);
18872+ return Char.ToUpperInvariant (name [index]).ToString (CultureInfo.InvariantCulture) + name.Substring (index + 1);
18873 }
18874
18875 // check if name is camelCased
18876@@ -118,7 +119,7 @@ namespace Gendarme.Rules.Naming {
18877 return name.ToLowerInvariant ();
18878
18879 int index = IndexOfFirstCorrectChar (name);
18880- return Char.ToLowerInvariant (name [index]).ToString () + name.Substring (index + 1);
18881+ return Char.ToLowerInvariant (name [index]).ToString (CultureInfo.InvariantCulture) + name.Substring (index + 1);
18882 }
18883
18884 private static int IndexOfFirstCorrectChar (string s)
18885@@ -144,14 +145,15 @@ namespace Gendarme.Rules.Naming {
18886 foreach (string ns in nspace.Split ('.')) {
18887 switch (ns.Length) {
18888 case 1:
18889- ReportCasingError (nd, string.Format (
18890+ ReportCasingError (nd, String.Format (CultureInfo.InvariantCulture,
18891 "Use of single character namespace is discouraged. Rename namespace {0}", ns));
18892
18893 break;
18894 case 2:
18895 // if the subnamespace is made of 2 chars, each letter have to be uppercase
18896 if (ns.Any (c => Char.IsLetter (c) && Char.IsLower (c))) {
18897- string msg = String.Format ("In namespaces made of two characters, both characters should uppercase. Rename namespace '{0}' to '{1}'",
18898+ string msg = String.Format (CultureInfo.InvariantCulture,
18899+ "In namespaces made of two characters, both characters should uppercase. Rename namespace '{0}' to '{1}'",
18900 ns, ns.ToUpperInvariant ());
18901 ReportCasingError (nd, msg);
18902 }
18903@@ -159,11 +161,13 @@ namespace Gendarme.Rules.Naming {
18904 default:
18905 // if the sub namespace is made of 3 or more chars, make sure they're not all uppercase
18906 if (ns.All (c => Char.IsLetter (c) && Char.IsUpper (c))) {
18907- string msg = String.Format ("Namespaces longer than two characters should not be all uppercase. Rename namespace '{0}' to '{1}{2}'",
18908- ns, ns [0].ToString (), ns.Substring (1).ToLowerInvariant ());
18909+ string msg = String.Format (CultureInfo.InvariantCulture,
18910+ "Namespaces longer than two characters should not be all uppercase. Rename namespace '{0}' to '{1}{2}'",
18911+ ns, ns [0].ToString (CultureInfo.InvariantCulture), ns.Substring (1).ToLowerInvariant ());
18912 ReportCasingError (nd, msg);
18913 } else if (!IsPascalCase (ns)) {
18914- string msg = String.Format ("Namespaces longer than two characters should be pascal cased. Rename namespace '{0}' to '{1}'",
18915+ string msg = String.Format (CultureInfo.InvariantCulture,
18916+ "Namespaces longer than two characters should be pascal cased. Rename namespace '{0}' to '{1}'",
18917 ns, PascalCase (ns));
18918 ReportCasingError (nd, msg);
18919 }
18920@@ -189,7 +193,7 @@ namespace Gendarme.Rules.Naming {
18921 // types should all be PascalCased
18922 string name = type.Name;
18923 if (!IsPascalCase (name)) {
18924- ReportCasingError (type, string.Format (
18925+ ReportCasingError (type, String.Format (CultureInfo.InvariantCulture,
18926 "Type names should all be pascal-cased. Rename '{0}' type to '{1}'.",
18927 name, PascalCase (name)));
18928 }
18929@@ -222,7 +226,8 @@ namespace Gendarme.Rules.Naming {
18930
18931 // like types, methods/props should all be PascalCased, too
18932 if (!IsPascalCase (name)) {
18933- string errorMessage = String.Format ("By existing naming conventions, all the method and property names should all be pascal-cased (e.g. MyOperation). Rename '{0}' to '{1}'.",
18934+ string errorMessage = String.Format (CultureInfo.InvariantCulture,
18935+ "By existing naming conventions, all the method and property names should all be pascal-cased (e.g. MyOperation). Rename '{0}' to '{1}'.",
18936 name, PascalCase (name));
18937 Runner.Report (method, Severity.Medium, Confidence.High, errorMessage);
18938 }
18939@@ -232,7 +237,8 @@ namespace Gendarme.Rules.Naming {
18940 foreach (ParameterDefinition param in method.Parameters) {
18941 // params should all be camelCased
18942 if (!IsCamelCase (param.Name)) {
18943- string errorMessage = String.Format ("By existing naming conventions, the parameter names should all be camel-cased (e.g. myParameter). Rename '{0}' parameter to '{1}'.",
18944+ string errorMessage = String.Format (CultureInfo.InvariantCulture,
18945+ "By existing naming conventions, the parameter names should all be camel-cased (e.g. myParameter). Rename '{0}' parameter to '{1}'.",
18946 param, CamelCase (param.Name));
18947 Runner.Report (method, Severity.Medium, Confidence.High, errorMessage);
18948 }
18949diff --git a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectPrefixRule.cs b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectPrefixRule.cs
18950index 68de78a..03ff58c 100644
18951--- a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectPrefixRule.cs
18952+++ b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectPrefixRule.cs
18953@@ -29,6 +29,7 @@
18954 //
18955
18956 using System;
18957+using System.Globalization;
18958
18959 using Mono.Cecil;
18960 using Gendarme.Framework;
18961@@ -89,9 +90,9 @@ namespace Gendarme.Rules.Naming {
18962 return true;
18963
18964 switch (name [0]) {
18965- case 'C': // MFC like CMyClass - but works for CLSCompliant
18966- case 'I': // interface-like
18967- return Char.IsLower (name [1]) == Char.IsLower (name [2]);
18968+ case 'C': // MFC like CMyClass should fail - but works for CLSCompliant
18969+ case 'I': // interface-like - Classes beginning with In or Is etc should pass, e.g. InMemoryDoohicky
18970+ return Char.IsLower (name [1]) ? true : Char.IsUpper (name [2]);
18971 default:
18972 return true;
18973 }
18974@@ -118,13 +119,16 @@ namespace Gendarme.Rules.Naming {
18975 if (type.IsInterface) {
18976 // interfaces should look like 'ISomething'
18977 if (!IsCorrectInterfaceName (name)) {
18978- string s = String.Format ("The '{0}' interface name doesn't have the required 'I' prefix. Acoording to existing naming conventions, all interface names should begin with the 'I' letter followed by another capital letter.", name);
18979+ string s = String.Format (CultureInfo.InvariantCulture,
18980+ "The '{0}' interface name doesn't have the required 'I' prefix. Acoording to existing naming conventions, all interface names should begin with the 'I' letter followed by another capital letter.",
18981+ name);
18982 Runner.Report (type, Severity.Critical, Confidence.High, s);
18983 }
18984 } else {
18985 // class should _not_ look like 'CSomething" or like an interface 'IOops'
18986 if (!IsCorrectTypeName (name)) {
18987- string s = String.Format ("The '{0}' type name starts with '{1}' prefix but, according to existing naming conventions, type names should not have any specific prefix.",
18988+ string s = String.Format (CultureInfo.InvariantCulture,
18989+ "The '{0}' type name starts with '{1}' prefix but, according to existing naming conventions, type names should not have any specific prefix.",
18990 name, name [0]);
18991 Runner.Report (type, Severity.Medium, Confidence.High, s);
18992 }
18993@@ -137,7 +141,9 @@ namespace Gendarme.Rules.Naming {
18994 foreach (GenericParameter parameter in type.GenericParameters) {
18995 string param_name = parameter.Name;
18996 if (IsCorrectGenericParameterName (param_name)) {
18997- string s = String.Format ("The generic parameter '{0}' should be prefixed with 'T' or be a single, uppercased letter.", param_name);
18998+ string s = String.Format (CultureInfo.InvariantCulture,
18999+ "The generic parameter '{0}' should be prefixed with 'T' or be a single, uppercased letter.",
19000+ param_name);
19001 Runner.Report (type, Severity.High, Confidence.High, s);
19002 }
19003 }
19004diff --git a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectSuffixRule.cs b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectSuffixRule.cs
19005index cad641b..671d842 100644
19006--- a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectSuffixRule.cs
19007+++ b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectSuffixRule.cs
19008@@ -32,6 +32,7 @@
19009
19010 using System;
19011 using System.Collections.Generic;
19012+using System.Globalization;
19013 using System.Text;
19014
19015 using Mono.Cecil;
19016@@ -83,29 +84,30 @@ namespace Gendarme.Rules.Naming {
19017 public class UseCorrectSuffixRule : Rule, ITypeRule {
19018
19019 static Dictionary<string, HashSet<string>> definedSuffixes = new Dictionary<string, HashSet<string>> ();
19020+ static Dictionary<string, string> namespaces = new Dictionary<string, string> ();
19021 static SortedDictionary<string, Func<TypeDefinition, string>> reservedSuffixes = new SortedDictionary<string, Func<TypeDefinition, string>> ();
19022
19023 static UseCorrectSuffixRule ()
19024 {
19025- Add ("Attribute", "System.Attribute", true);
19026- Add ("Collection", "System.Collections.ICollection", false);
19027- Add ("Collection", "System.Collections.IEnumerable", false);
19028- Add ("Collection", "System.Collections.Queue", false);
19029- Add ("Collection", "System.Collections.Stack", false);
19030- Add ("Collection", "System.Collections.Generic.ICollection`1", false);
19031- Add ("Collection", "System.Data.DataSet", false);
19032- Add ("Collection", "System.Data.DataTable", false);
19033- Add ("Condition", "System.Security.Policy.IMembershipCondition", true);
19034- Add ("DataSet", "System.Data.DataSet", true);
19035- Add ("DataTable", "System.Data.DataTable", true);
19036- Add ("Dictionary", "System.Collections.IDictionary", false);
19037- Add ("Dictionary", "System.Collections.IDictionary`2", false);
19038- Add ("EventArgs", "System.EventArgs", true);
19039- Add ("Exception", "System.Exception", true);
19040- Add ("Permission", "System.Security.IPermission", true);
19041- Add ("Queue", "System.Collections.Queue", true);
19042- Add ("Stack", "System.Collections.Stack", true);
19043- Add ("Stream", "System.IO.Stream", true);
19044+ Add ("Attribute", "System", "Attribute", true);
19045+ Add ("Collection", "System.Collections", "ICollection", false);
19046+ Add ("Collection", "System.Collections", "IEnumerable", false);
19047+ Add ("Collection", "System.Collections", "Queue", false);
19048+ Add ("Collection", "System.Collections", "Stack", false);
19049+ Add ("Collection", "System.Collections.Generic", "ICollection`1", false);
19050+ Add ("Collection", "System.Data", "DataSet", false);
19051+ Add ("Collection", "System.Data", "DataTable", false);
19052+ Add ("Condition", "System.Security.Policy", "IMembershipCondition", true);
19053+ Add ("DataSet", "System.Data", "DataSet", true);
19054+ Add ("DataTable", "System.Data", "DataTable", true);
19055+ Add ("Dictionary", "System.Collections", "IDictionary", false);
19056+ Add ("Dictionary", "System.Collections", "IDictionary`2", false);
19057+ Add ("EventArgs", "System", "EventArgs", true);
19058+ Add ("Exception", "System", "Exception", true);
19059+ Add ("Permission", "System.Security", "IPermission", true);
19060+ Add ("Queue", "System.Collections", "Queue", true);
19061+ Add ("Stack", "System.Collections", "Stack", true);
19062+ Add ("Stream", "System.IO", "Stream", true);
19063
19064 // special cases
19065 reservedSuffixes.Add ("Collection", message => CheckCollection (message));
19066@@ -119,36 +121,40 @@ namespace Gendarme.Rules.Naming {
19067 reservedSuffixes.Add ("Impl", message => "Use the 'Core' prefix instead of 'Impl'.");
19068 }
19069
19070- static void Add (string suffix, string type, bool reserved)
19071+ static void Add (string suffix, string nameSpace, string name, bool reserved)
19072 {
19073 if (reserved) {
19074- reservedSuffixes.Add (suffix, message => InheritsOrImplements (message, type));
19075+ reservedSuffixes.Add (suffix, message => InheritsOrImplements (message, nameSpace, name));
19076 }
19077
19078 HashSet<string> set;
19079- if (!definedSuffixes.TryGetValue (type, out set)) {
19080+ if (!definedSuffixes.TryGetValue (name, out set)) {
19081 set = new HashSet<string> ();
19082- definedSuffixes.Add (type, set);
19083+ definedSuffixes.Add (name, set);
19084+ namespaces.Add (name, nameSpace);
19085 }
19086 set.Add (suffix);
19087 }
19088
19089- static string InheritsOrImplements (TypeReference type, string subtype)
19090+ static string InheritsOrImplements (TypeReference type, string nameSpace, string name)
19091 {
19092- if (type.Inherits (subtype) || type.Implements (subtype))
19093+ if (type.Inherits (nameSpace, name) || type.Implements (nameSpace, name))
19094 return String.Empty;
19095- return String.Format ("'{0}' should only be used for types that inherits or implements {1}.", type.Name, subtype);
19096+
19097+ return String.Format (CultureInfo.InvariantCulture,
19098+ "'{0}' should only be used for types that inherits or implements '{1}.{2}'.",
19099+ type.Name, nameSpace, name);
19100 }
19101
19102 static string CheckCollection (TypeReference type)
19103 {
19104- if (type.Implements ("System.Collections.ICollection") ||
19105- type.Implements ("System.Collections.IEnumerable") ||
19106- type.Implements ("System.Collections.Generic.ICollection`1"))
19107+ if (type.Implements ("System.Collections", "ICollection") ||
19108+ type.Implements ("System.Collections", "IEnumerable") ||
19109+ type.Implements ("System.Collections.Generic", "ICollection`1"))
19110 return String.Empty;
19111
19112- if (type.Inherits ("System.Collections.Queue") || type.Inherits ("System.Collections.Stack") ||
19113- type.Inherits ("System.Data.DataSet") || type.Inherits ("System.Data.DataTable"))
19114+ if (type.Inherits ("System.Collections", "Queue") || type.Inherits ("System.Collections", "Stack") ||
19115+ type.Inherits ("System.Data", "DataSet") || type.Inherits ("System.Data", "DataTable"))
19116 return String.Empty;
19117
19118 return "'Collection' should only be used for implementing ICollection or IEnumerable or inheriting from Queue, Stack, DataSet and DataTable.";
19119@@ -156,7 +162,7 @@ namespace Gendarme.Rules.Naming {
19120
19121 static string CheckDictionary (TypeReference type)
19122 {
19123- if (type.Implements ("System.Collections.IDictionary") || type.Implements ("System.Collections.Generic.IDictionary`2"))
19124+ if (type.Implements ("System.Collections", "IDictionary") || type.Implements ("System.Collections.Generic", "IDictionary`2"))
19125 return String.Empty;
19126 return "'Dictionary' should only be used for types implementing IDictionary and IDictionary<TKey,TValue>.";
19127 }
19128@@ -168,16 +174,24 @@ namespace Gendarme.Rules.Naming {
19129 return "'EventHandler' should only be used for event handler delegates.";
19130 }
19131
19132- // handle types using generics
19133- private static string GetFullName (TypeReference type)
19134+ static bool TryGetCandidates (TypeReference type, out HashSet<string> candidates)
19135 {
19136- string name = type.FullName;
19137- // handle types using generics
19138+ string name = type.Name;
19139 if ((type is GenericInstanceType) || type.HasGenericParameters) {
19140 int pos = name.IndexOf ('`');
19141- name = name.Substring (0, pos);
19142+ if (pos != -1)
19143+ name = name.Substring (0, pos);
19144+ }
19145+
19146+ if (definedSuffixes.TryGetValue (name, out candidates)) {
19147+ string nspace;
19148+ if (namespaces.TryGetValue (name, out nspace)) {
19149+ if (nspace == type.Namespace)
19150+ return true;
19151+ }
19152 }
19153- return name;
19154+ candidates = null;
19155+ return false;
19156 }
19157
19158 // checks if type name ends with an approriate suffix
19159@@ -189,18 +203,15 @@ namespace Gendarme.Rules.Naming {
19160 currentTypeSuffix = false;
19161
19162 while (current != null && current.BaseType != null) {
19163- string base_name = GetFullName (current.BaseType);
19164-
19165 HashSet<string> candidates;
19166- if (definedSuffixes.TryGetValue (base_name, out candidates)) {
19167+ if (TryGetCandidates (current.BaseType, out candidates)) {
19168 suffixes.AddRangeIfNew (candidates);
19169 if (current == type)
19170 currentTypeSuffix = true;
19171 } else {
19172 // if no suffix for base type is found, we start looking through interfaces
19173 foreach (TypeReference iface in current.Interfaces) {
19174- string interface_name = GetFullName (iface);
19175- if (definedSuffixes.TryGetValue (interface_name, out candidates)) {
19176+ if (TryGetCandidates (iface, out candidates)) {
19177 suffixes.AddRangeIfNew (candidates);
19178 if (current == type)
19179 currentTypeSuffix = true;
19180@@ -210,8 +221,9 @@ namespace Gendarme.Rules.Naming {
19181 if (suffixes.Count > 0) {
19182 // if any suffixes found
19183 // check whether type name ends with any of these suffixes
19184+ string tname = type.Name;
19185 return suffixes.Exists (delegate (string suffix) {
19186- return GetFullName (type).EndsWith (suffix, StringComparison.Ordinal);
19187+ return HasSuffix (tname, suffix);
19188 });
19189 } else {
19190 // inspect base type
19191@@ -224,8 +236,11 @@ namespace Gendarme.Rules.Naming {
19192
19193 private static string ComposeMessage (List<string> candidates)
19194 {
19195- if (candidates.Count == 1)
19196- return String.Format ("The type name does not end with '{0}' suffix. Append it to the type name.", candidates [0]);
19197+ if (candidates.Count == 1) {
19198+ return String.Format (CultureInfo.InvariantCulture,
19199+ "The type name does not end with '{0}' suffix. Append it to the type name.",
19200+ candidates [0]);
19201+ }
19202
19203 StringBuilder sb = new StringBuilder ("The type name does not end with one of the following suffixes: ");
19204 sb.Append (candidates [0]);
19205@@ -239,6 +254,21 @@ namespace Gendarme.Rules.Naming {
19206
19207 private List<string> proposedSuffixes = new List<string> ();
19208
19209+ static bool HasSuffix (string typeName, string suffix)
19210+ {
19211+ if (suffix.Length > typeName.Length)
19212+ return false;
19213+
19214+ // generic aware
19215+ int gpos = typeName.LastIndexOf ('`');
19216+ if (gpos == -1)
19217+ gpos = typeName.Length;
19218+ else if (suffix.Length > gpos)
19219+ return false;
19220+
19221+ return (String.Compare (suffix, 0, typeName, gpos - suffix.Length, suffix.Length, StringComparison.OrdinalIgnoreCase) == 0);
19222+ }
19223+
19224 public RuleResult CheckType (TypeDefinition type)
19225 {
19226 // rule does not apply to generated code (outside developer's control)
19227@@ -247,15 +277,19 @@ namespace Gendarme.Rules.Naming {
19228
19229 // ok, rule applies
19230
19231+ string tname = type.Name;
19232 // first check if the current suffix is correct
19233 // e.g. MyAttribute where the type does not inherit from Attribute
19234 foreach (string suffix in reservedSuffixes.Keys) {
19235- if (type.Name.EndsWith (suffix, StringComparison.OrdinalIgnoreCase)) {
19236+ if (HasSuffix (tname, suffix)) {
19237 Func<TypeDefinition, string> f;
19238 if (reservedSuffixes.TryGetValue (suffix, out f)) {
19239 string msg = f (type);
19240- if (!String.IsNullOrEmpty (msg))
19241- Runner.Report (type, Severity.Medium, Confidence.High, msg);
19242+ // if this is a valid suffix then there's not need to check for invalid later
19243+ if (String.IsNullOrEmpty (msg))
19244+ return RuleResult.Success;
19245+
19246+ Runner.Report (type, Severity.Medium, Confidence.High, msg);
19247 }
19248 }
19249 }
19250diff --git a/gendarme/rules/Gendarme.Rules.Naming/UsePreferredTermsRule.cs b/gendarme/rules/Gendarme.Rules.Naming/UsePreferredTermsRule.cs
19251index 59ede41..d2367c5 100644
19252--- a/gendarme/rules/Gendarme.Rules.Naming/UsePreferredTermsRule.cs
19253+++ b/gendarme/rules/Gendarme.Rules.Naming/UsePreferredTermsRule.cs
19254@@ -30,6 +30,7 @@
19255
19256 using System;
19257 using System.Collections.Generic;
19258+using System.Globalization;
19259
19260 using Mono.Cecil;
19261
19262@@ -140,7 +141,7 @@ namespace Gendarme.Rules.Naming {
19263 continue;
19264 if (index > 0 && char.IsLetter (name, index - 1) && char.IsLower (name, index))
19265 continue; //term is part of a larger word
19266- string s = String.Format (Message, pair.Key, pair.Value);
19267+ string s = String.Format (CultureInfo.InvariantCulture, Message, pair.Key, pair.Value);
19268 Runner.Report (identifier, severity, Confidence.High, s);
19269 }
19270 }
19271diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidConcatenatingCharsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidConcatenatingCharsRule.cs
19272index e753a0d..44ba1e6 100644
19273--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidConcatenatingCharsRule.cs
19274+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidConcatenatingCharsRule.cs
19275@@ -27,6 +27,7 @@
19276 //
19277
19278 using System;
19279+using System.Globalization;
19280
19281 using Mono.Cecil;
19282 using Mono.Cecil.Cil;
19283@@ -74,26 +75,20 @@ namespace Gendarme.Rules.Performance {
19284 [EngineDependency (typeof (OpCodeEngine))]
19285 public class AvoidConcatenatingCharsRule : Rule, IMethodRule {
19286
19287- static bool IsStringConcat (MemberReference member)
19288- {
19289- if (member == null || (member.Name != "Concat"))
19290- return false;
19291-
19292- return (member.DeclaringType.FullName == "System.String");
19293- }
19294-
19295 static bool HasReferenceToStringConcatObject (ModuleDefinition module)
19296 {
19297 foreach (MemberReference mr in module.GetMemberReferences ()) {
19298- if (IsStringConcat (mr)) {
19299+ if (mr.IsNamed ("System", "String", "Concat")) {
19300 MethodReference method = (mr as MethodReference);
19301 // catch both System.Object and System.Object[]
19302 if (!method.HasParameters)
19303 continue;
19304- switch (method.Parameters [0].ParameterType.FullName) {
19305- case "System.Object":
19306- case "System.Object[]":
19307- return true;
19308+
19309+ TypeReference ptype = method.Parameters [0].ParameterType;
19310+ switch (ptype.Name) {
19311+ case "Object":
19312+ case "Object[]":
19313+ return (ptype.Namespace == "System");
19314 }
19315 }
19316 }
19317@@ -113,7 +108,8 @@ namespace Gendarme.Rules.Performance {
19318
19319 private void ReportBoxing (MethodDefinition method, Instruction ins, Confidence confidence)
19320 {
19321- string msg = String.Format ("Type '{0}' is being boxed.", (ins.Operand as TypeReference).FullName);
19322+ string msg = String.Format (CultureInfo.InvariantCulture,
19323+ "Type '{0}' is being boxed.", (ins.Operand as TypeReference).GetFullName ());
19324 Runner.Report (method, ins, Severity.High, confidence, msg);
19325 }
19326
19327@@ -159,14 +155,18 @@ namespace Gendarme.Rules.Performance {
19328
19329 // look for String.Concat overloads using System.Object
19330 MethodReference mr = (ins.Operand as MethodReference);
19331- if (!IsStringConcat (mr) || !mr.HasParameters)
19332+ if (!mr.HasParameters || !mr.IsNamed ("System", "String", "Concat"))
19333 continue;
19334
19335- switch (mr.Parameters [0].ParameterType.FullName) {
19336- case "System.Object":
19337+ TypeReference ptype = mr.Parameters [0].ParameterType;
19338+ if (ptype.Namespace != "System")
19339+ continue; // very unlikely
19340+
19341+ switch (ptype.Name) {
19342+ case "Object":
19343 CheckParameters (mr, method, ins);
19344 break;
19345- case "System.Object[]":
19346+ case "Object[]":
19347 if ((ins.Previous.OpCode.Code == Code.Stelem_Ref) || ins.Previous.IsLoadLocal ())
19348 ScanArray (method, ins.Previous);
19349 break;
19350diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeNumberOfLocalVariablesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeNumberOfLocalVariablesRule.cs
19351index a1bd50f..698867c 100644
19352--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeNumberOfLocalVariablesRule.cs
19353+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeNumberOfLocalVariablesRule.cs
19354@@ -28,6 +28,7 @@
19355
19356 using System;
19357 using System.ComponentModel;
19358+using System.Globalization;
19359
19360 using Mono.Cecil;
19361 using Mono.Cecil.Cil;
19362@@ -70,7 +71,7 @@ namespace Gendarme.Rules.Performance {
19363 // special case for System.Windows.Forms since it's designer does not
19364 // mark this code as generated :-(
19365 if (method.Name == "InitializeComponent") {
19366- if (method.DeclaringType.Inherits ("System.Windows.Forms.Form"))
19367+ if (method.DeclaringType.Inherits ("System.Windows.Forms", "Form"))
19368 return RuleResult.DoesNotApply;
19369 }
19370
19371@@ -78,7 +79,8 @@ namespace Gendarme.Rules.Performance {
19372 if (num <= MaximumVariables)
19373 return RuleResult.Success;
19374
19375- string msg = String.Format ("Found {0} local variables (maximum {1}).", num, MaximumVariables);
19376+ string msg = String.Format (CultureInfo.InvariantCulture,
19377+ "Found {0} local variables (maximum {1}).", num, MaximumVariables);
19378 Runner.Report (method, Severity.High, Confidence.High, msg);
19379 return RuleResult.Failure;
19380 }
19381diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeStructureRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeStructureRule.cs
19382index 99ecb4f..2ce5e3f 100644
19383--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeStructureRule.cs
19384+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeStructureRule.cs
19385@@ -29,6 +29,7 @@
19386 using System;
19387 using System.Collections.Generic;
19388 using System.ComponentModel;
19389+using System.Globalization;
19390
19391 using Mono.Cecil;
19392
19393@@ -75,20 +76,20 @@ namespace Gendarme.Rules.Performance {
19394 private const int ReferenceSize = 4;
19395
19396 static Dictionary<string, int> Primitives = new Dictionary<string, int> (14) {
19397- { "System.Byte", 1 },
19398- { "System.SByte", 1 },
19399- { "System.Boolean", 1 },
19400- { "System.Int16", 2 },
19401- { "System.UInt16", 2 },
19402- { "System.Char", 2 },
19403- { "System.Int32", 4 },
19404- { "System.UInt32", 4 },
19405- { "System.Single", 4 },
19406- { "System.Int64", 8 },
19407- { "System.UInt64", 8 },
19408- { "System.Double", 8 },
19409- { "System.IntPtr", ReferenceSize }, // so rule return the same results
19410- { "System.UIntPtr", ReferenceSize }, // on 32 and 64 bits architectures
19411+ { "Byte", 1 },
19412+ { "SByte", 1 },
19413+ { "Boolean", 1 },
19414+ { "Int16", 2 },
19415+ { "UInt16", 2 },
19416+ { "Char", 2 },
19417+ { "Int32", 4 },
19418+ { "UInt32", 4 },
19419+ { "Single", 4 },
19420+ { "Int64", 8 },
19421+ { "UInt64", 8 },
19422+ { "Double", 8 },
19423+ { "IntPtr", ReferenceSize }, // so rule return the same results
19424+ { "UIntPtr", ReferenceSize }, // on 32 and 64 bits architectures
19425 };
19426
19427 private int max_size = MaximumRecommendedSize;
19428@@ -179,7 +180,7 @@ namespace Gendarme.Rules.Performance {
19429 // list based on Type.IsPrimitive
19430 if (type.Namespace == "System") {
19431 int size;
19432- if (Primitives.TryGetValue (type.FullName, out size))
19433+ if (Primitives.TryGetValue (type.Name, out size))
19434 return (long) size;
19435 }
19436
19437@@ -216,7 +217,7 @@ namespace Gendarme.Rules.Performance {
19438 else if (size > medium_severity_limit)
19439 severity = Severity.Medium;
19440
19441- string text = String.Format ("Structure size is {0} bytes.", size);
19442+ string text = String.Format (CultureInfo.CurrentCulture, "Structure size is {0} bytes.", size);
19443 Runner.Report (type, severity, Confidence.High, text);
19444 return RuleResult.Failure;
19445 }
19446diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidLocalDataStoreSlotRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidLocalDataStoreSlotRule.cs
19447index a039d6a..b881c09 100644
19448--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidLocalDataStoreSlotRule.cs
19449+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidLocalDataStoreSlotRule.cs
19450@@ -89,8 +89,6 @@ namespace Gendarme.Rules.Performance {
19451 [EngineDependency (typeof (OpCodeEngine))]
19452 public class AvoidLocalDataStoreSlotRule : Rule, IMethodRule {
19453
19454- private const string LocalDataStoreSlot = "System.LocalDataStoreSlot";
19455-
19456 public override void Initialize (IRunner runner)
19457 {
19458 base.Initialize (runner);
19459@@ -99,7 +97,9 @@ namespace Gendarme.Rules.Performance {
19460 // if the module does not reference System.LocalDataStoreSlot
19461 // then no method inside it will be using it
19462 Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
19463- e.CurrentModule.HasTypeReference (LocalDataStoreSlot));
19464+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
19465+ return tr.IsNamed ("System", "LocalDataStoreSlot");
19466+ }));
19467 };
19468 }
19469
19470@@ -119,9 +119,18 @@ namespace Gendarme.Rules.Performance {
19471 if (mr == null)
19472 continue;
19473
19474- switch (mr.DeclaringType.FullName) {
19475- case "System.Threading.Thread":
19476- case "System.Runtime.Remoting.Contexts.Context":
19477+ TypeReference type = mr.DeclaringType;
19478+ switch (type.Namespace) {
19479+ case "System.Threading":
19480+ case "System.Runtime.Remoting.Contexts":
19481+ break;
19482+ default:
19483+ continue;
19484+ }
19485+
19486+ switch (type.Name) {
19487+ case "Thread":
19488+ case "Context":
19489 break;
19490 default:
19491 continue;
19492diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidMethodWithLargeMaximumStackSizeRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidMethodWithLargeMaximumStackSizeRule.cs
19493index 5fbc09d..576e211 100644
19494--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidMethodWithLargeMaximumStackSizeRule.cs
19495+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidMethodWithLargeMaximumStackSizeRule.cs
19496@@ -27,6 +27,7 @@
19497 //
19498
19499 using System;
19500+using System.Globalization;
19501
19502 using Mono.Cecil;
19503 using Mono.Cecil.Cil;
19504@@ -64,7 +65,8 @@ namespace Gendarme.Rules.Performance {
19505 if (num <= MaximumStackSize)
19506 return RuleResult.Success;
19507
19508- string msg = String.Format ("Found {0} maximum stack size (maximum {1}).", num, MaximumStackSize);
19509+ string msg = String.Format (CultureInfo.InvariantCulture,
19510+ "Found {0} maximum stack size (maximum {1}).", num, MaximumStackSize);
19511 Runner.Report (method, Severity.High, Confidence.High, msg);
19512 return RuleResult.Failure;
19513 }
19514diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCallsToPropertiesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCallsToPropertiesRule.cs
19515index a470e55..7e1bc64 100644
19516--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCallsToPropertiesRule.cs
19517+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCallsToPropertiesRule.cs
19518@@ -29,6 +29,7 @@
19519 using System;
19520 using System.Collections.Generic;
19521 using System.ComponentModel;
19522+using System.Globalization;
19523 using System.Text;
19524
19525 using Mono.Cecil;
19526@@ -107,14 +108,19 @@ namespace Gendarme.Rules.Performance {
19527 static string GetKey (MethodDefinition caller, MethodDefinition callee, Instruction ins)
19528 {
19529 if (callee.IsStatic)
19530- return callee.ToString ();
19531+ return callee.GetFullName ();
19532
19533 IMetadataTokenProvider chain = callee;
19534 Instruction instance = ins.TraceBack (caller);
19535
19536 StringBuilder sb = new StringBuilder ();
19537 while (instance != null) {
19538- sb.Append (chain.ToString () ?? "null").Append ('.');
19539+ MemberReference mr = (chain as MemberReference);
19540+ if (mr == null)
19541+ sb.Append (chain.ToString ()); // ?? "null")
19542+ else
19543+ sb.Append (mr.GetFullName ());
19544+ sb.Append ('.');
19545 chain = (instance.Operand as IMetadataTokenProvider);
19546 if (chain == null) {
19547 sb.Append (instance.GetOperand (caller));
19548@@ -151,16 +157,15 @@ namespace Gendarme.Rules.Performance {
19549
19550 static bool Filter (MethodDefinition method)
19551 {
19552- switch (method.DeclaringType.FullName) {
19553+ TypeReference type = method.DeclaringType;
19554 // Elapsed* and IsRunning
19555- case "System.Diagnostics.Stopwatch":
19556+ if (type.IsNamed ("System.Diagnostics", "Stopwatch"))
19557 return true;
19558 // Now and UtcNow
19559- case "System.DateTime":
19560+ else if (type.IsNamed ("System", "DateTime"))
19561 return method.IsStatic;
19562- default:
19563- return false;
19564- }
19565+
19566+ return false;
19567 }
19568
19569 public RuleResult CheckMethod (MethodDefinition method)
19570@@ -218,13 +223,15 @@ namespace Gendarme.Rules.Performance {
19571 MethodDefinition md = kvp.Value.Key;
19572 if (md.IsVirtual && !md.IsFinal) {
19573 // virtual calls are expensive, so the code better cache the value
19574- string msg = String.Format ("Multiple ({0}) calls to virtual property '{1}'.", count, md.ToString ());
19575+ string msg = String.Format (CultureInfo.InvariantCulture,
19576+ "Multiple ({0}) calls to virtual property '{1}'.", count, md.ToString ());
19577 Runner.Report (method, GetSeverity (count, true), Confidence.Normal, msg);
19578 } else if (!IsInliningCandidate (md)) {
19579 // non-virtual calls might be inlined
19580 // otherwise caching the value is again a good idea
19581 int size = md.HasBody ? md.Body.CodeSize : 0;
19582- string msg = String.Format ("Multiple ({0}) calls to non-virtual property '{1}', likely non-inlined due to size ({2} >= {3}).",
19583+ string msg = String.Format (CultureInfo.InvariantCulture,
19584+ "Multiple ({0}) calls to non-virtual property '{1}', likely non-inlined due to size ({2} >= {3}).",
19585 count, md.ToString (), size, InlineLimit);
19586 Runner.Report (method, GetSeverity (count, false), Confidence.Normal, msg);
19587 }
19588diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCastsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCastsRule.cs
19589index 5680c14..5a4a10e 100644
19590--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCastsRule.cs
19591+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCastsRule.cs
19592@@ -29,6 +29,7 @@
19593
19594 using System;
19595 using System.Collections.Generic;
19596+using System.Globalization;
19597
19598 using Mono.Cecil;
19599 using Mono.Cecil.Cil;
19600@@ -237,7 +238,7 @@ namespace Gendarme.Rules.Performance {
19601 return match;
19602 }
19603
19604- private int FindDuplicates (MethodDefinition method, string type, Instruction origin)
19605+ private int FindDuplicates (MethodDefinition method, TypeReference type, Instruction origin)
19606 {
19607 // we already had our first cast if we got here
19608 int count = 1;
19609@@ -245,7 +246,7 @@ namespace Gendarme.Rules.Performance {
19610 // don't check 0 since it's the one we compare with
19611 for (int i = 1; i < casts.Count; i++) {
19612 Instruction ins = casts [i];
19613- if (type != (ins.Operand as TypeReference).FullName)
19614+ if (!(ins.Operand as TypeReference).IsNamed (type.Namespace, type.Name))
19615 continue;
19616 if (!OriginsMatch(method, origin, GetOrigin (ins)))
19617 continue;
19618@@ -287,7 +288,7 @@ namespace Gendarme.Rules.Performance {
19619 // if there's only one then it can't be a duplicate cast
19620 while (casts.Count > 1) {
19621 Instruction ins = casts [0];
19622- string type = (ins.Operand as TypeReference).FullName;
19623+ TypeReference type = (ins.Operand as TypeReference);
19624 Instruction origin = GetOrigin (ins);
19625
19626 int count = FindDuplicates (method, type, origin);
19627@@ -296,7 +297,8 @@ namespace Gendarme.Rules.Performance {
19628
19629 // rare, but it's possible to cast a null value (ldnull)
19630 object name = origin.GetOperand (method) ?? "Null";
19631- string msg = String.Format ("'{0}' is casted {1} times for type '{2}'.", name, count, type);
19632+ string msg = String.Format (CultureInfo.InvariantCulture,
19633+ "'{0}' is casted {1} times for type '{2}'.", name, count, type.GetFullName ());
19634 Runner.Report (method, ins, Severity.Medium, Confidence.Normal, msg);
19635 }
19636 casts.RemoveAt (0);
19637diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidTypeGetTypeForConstantStringsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidTypeGetTypeForConstantStringsRule.cs
19638index 23da450..e2d9ed1 100644
19639--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidTypeGetTypeForConstantStringsRule.cs
19640+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidTypeGetTypeForConstantStringsRule.cs
19641@@ -27,6 +27,7 @@
19642 //
19643
19644 using System;
19645+using System.Globalization;
19646
19647 using Mono.Cecil;
19648 using Mono.Cecil.Cil;
19649@@ -34,6 +35,7 @@ using Mono.Cecil.Cil;
19650 using Gendarme.Framework;
19651 using Gendarme.Framework.Engines;
19652 using Gendarme.Framework.Helpers;
19653+using Gendarme.Framework.Rocks;
19654
19655 namespace Gendarme.Rules.Performance {
19656
19657@@ -84,9 +86,9 @@ namespace Gendarme.Rules.Performance {
19658
19659 // look for calls to: static Type System.Type.GetType(string...)
19660 MethodReference mr = (ins.Operand as MethodReference);
19661- if ((mr == null) || !mr.HasParameters || (mr.Name != "GetType"))
19662+ if ((mr == null) || !mr.HasParameters)
19663 continue;
19664- if (mr.DeclaringType.FullName != "System.Type")
19665+ if (!mr.IsNamed ("System", "Type", "GetType"))
19666 continue;
19667
19668 if (ins.Previous.OpCode.Code != Code.Ldstr)
19669@@ -100,7 +102,8 @@ namespace Gendarme.Rules.Performance {
19670 if (type_name == "Mono.Runtime")
19671 continue;
19672
19673- string msg = string.Format ("Replace call to Type.GetType(\"{0}\") into typeof({0}).", type_name);
19674+ string msg = String.Format (CultureInfo.InvariantCulture,
19675+ "Replace call to Type.GetType(\"{0}\") into typeof({0}).", type_name);
19676 Runner.Report (method, ins, Severity.Medium, Confidence.Normal, msg);
19677 }
19678 return Runner.CurrentRuleResult;
19679diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUncalledPrivateCodeRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUncalledPrivateCodeRule.cs
19680index 529657a..37d0478 100644
19681--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUncalledPrivateCodeRule.cs
19682+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUncalledPrivateCodeRule.cs
19683@@ -93,11 +93,21 @@ namespace Gendarme.Rules.Performance {
19684 [FxCopCompatibility ("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
19685 public class AvoidUncalledPrivateCodeRule : Rule, IMethodRule {
19686
19687- static string [] SpecialAttributes = new string[] {
19688- "System.Runtime.InteropServices.ComRegisterFunctionAttribute",
19689- "System.Runtime.InteropServices.ComUnregisterFunctionAttribute",
19690- "System.Diagnostics.ConditionalAttribute"
19691- };
19692+ static bool HasAnySpecialAttribute (ICustomAttributeProvider method)
19693+ {
19694+ if (!method.HasCustomAttributes)
19695+ return false;
19696+
19697+ foreach (CustomAttribute ca in method.CustomAttributes) {
19698+ TypeReference cat = ca.AttributeType;
19699+ string name = cat.Name;
19700+ if ((cat.IsNamed ("System.Diagnostics", name)) || (cat.Namespace == "System.Runtime.InteropServices" &&
19701+ (name == "ComRegisterFunctionAttribute" || name == "ComUnregisterFunctionAttribute"))) {
19702+ return true;
19703+ }
19704+ }
19705+ return false;
19706+ }
19707
19708 static private bool Applicable (MethodDefinition method)
19709 {
19710@@ -119,10 +129,8 @@ namespace Gendarme.Rules.Performance {
19711
19712 // does not apply if the method is used to register/unregister COM objects
19713 // or it is decorated with a [Conditional("x")] attribute
19714- if (method.HasCustomAttributes) {
19715- if (method.CustomAttributes.ContainsAnyType (SpecialAttributes))
19716- return false;
19717- }
19718+ if (HasAnySpecialAttribute (method))
19719+ return false;
19720
19721 return true;
19722 }
19723@@ -301,7 +309,7 @@ namespace Gendarme.Rules.Performance {
19724 return methods;
19725 }
19726
19727- private static void BuildMethodUsage (HashSet<ulong> methods, MethodDefinition method)
19728+ private static void BuildMethodUsage (ISet<ulong> methods, MethodDefinition method)
19729 {
19730 foreach (Instruction ins in method.Body.Instructions) {
19731 MethodReference mr = (ins.Operand as MethodReference);
19732@@ -310,7 +318,7 @@ namespace Gendarme.Rules.Performance {
19733 continue;
19734
19735 TypeReference type = mr.DeclaringType;
19736- if (!(type is ArrayType)) {
19737+ if (!type.IsArray) {
19738 // if (type.GetElementType ().HasGenericParameters)
19739 // the simpler ^^^ does not work under Mono but works on MS
19740 type = type.Resolve ();
19741diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUninstantiatedInternalClassesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUninstantiatedInternalClassesRule.cs
19742index 518a451..2406244 100644
19743--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUninstantiatedInternalClassesRule.cs
19744+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUninstantiatedInternalClassesRule.cs
19745@@ -101,7 +101,7 @@ namespace Gendarme.Rules.Performance {
19746 cache.Add (assembly, typeset);
19747 }
19748
19749- static void AddType (HashSet<TypeReference> typeset, TypeReference type)
19750+ static void AddType (ISet<TypeReference> typeset, TypeReference type)
19751 {
19752 // we're interested in the array element type, not the array itself
19753 if (type.IsArray)
19754@@ -240,7 +240,7 @@ namespace Gendarme.Rules.Performance {
19755 // if we can't find the non-public type being used in the assembly then the rule fails
19756 if (typeset == null || !typeset.Contains (type)) {
19757 // base confidence on whether the internals are visible or not
19758- Confidence c = assembly.HasAttribute ("System.Runtime.CompilerServices.InternalsVisibleToAttribute") ?
19759+ Confidence c = assembly.HasAttribute ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute") ?
19760 Confidence.Low : Confidence.Normal;
19761 Runner.Report (type, Severity.High, c);
19762 return RuleResult.Failure;
19763diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnnecessaryOverridesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnnecessaryOverridesRule.cs
19764index 5dac506..f1c9d8b 100644
19765--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnnecessaryOverridesRule.cs
19766+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnnecessaryOverridesRule.cs
19767@@ -80,8 +80,9 @@ namespace Gendarme.Rules.Performance {
19768 if (!mr.CompareSignature (method))
19769 return false;
19770
19771+ TypeReference type = mr.DeclaringType;
19772 foreach (TypeDefinition baseType in method.DeclaringType.AllSuperTypes ()) {
19773- if (mr.DeclaringType.FullName == baseType.FullName)
19774+ if (baseType.IsNamed (type.Namespace, type.Name))
19775 return true;
19776 }
19777 return false;
19778diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededCallsOnStringRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededCallsOnStringRule.cs
19779index 212892a..08a051b 100644
19780--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededCallsOnStringRule.cs
19781+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededCallsOnStringRule.cs
19782@@ -29,6 +29,7 @@
19783 //
19784
19785 using System;
19786+using System.Globalization;
19787
19788 using Mono.Cecil;
19789 using Mono.Cecil.Cil;
19790@@ -126,15 +127,15 @@ namespace Gendarme.Rules.Performance {
19791 if (call.HasParameters)
19792 return String.Empty;
19793
19794- if (!IsSystemString (ins.Previous.GetOperandType (method)))
19795+ if (!ins.Previous.GetOperandType (method).IsNamed ("System", "String"))
19796 return String.Empty;
19797
19798- return String.Format (MessageString, call.Name, String.Empty);
19799+ return String.Format (CultureInfo.InvariantCulture, MessageString, call.Name, String.Empty);
19800 }
19801
19802 private static string CheckSubstring (MethodReference call, Instruction ins)
19803 {
19804- if (!IsSystemString (call.DeclaringType))
19805+ if (!call.DeclaringType.IsNamed ("System", "String"))
19806 return String.Empty;
19807
19808 // ensure it's System.String::Substring(System.Int32) and that it's given 0 as a parameter
19809@@ -143,24 +144,19 @@ namespace Gendarme.Rules.Performance {
19810 if (!ins.Previous.IsOperandZero ())
19811 return String.Empty;
19812
19813- return String.Format (MessageString, call.Name, "0");
19814+ return String.Format (CultureInfo.InvariantCulture, MessageString, call.Name, "0");
19815 }
19816
19817 private static string CheckToString (MethodReference call, Instruction ins, MethodDefinition method)
19818 {
19819- if (IsSystemString (call.DeclaringType)) {
19820+ if (call.DeclaringType.IsNamed ("System", "String")) {
19821 // most probably ToString(IFormatProvider), possibly ToString()
19822- return String.Format (MessageString, call.Name,
19823+ return String.Format (CultureInfo.InvariantCulture, MessageString, call.Name,
19824 (call.HasParameters && (call.Parameters.Count > 1)) ? "IFormatProvider" : String.Empty);
19825 } else {
19826 // signature for Clone is identical (well close enough) to share code
19827 return CheckClone (call, ins, method);
19828 }
19829 }
19830-
19831- private static bool IsSystemString (MemberReference type)
19832- {
19833- return (type == null) ? false : (type.FullName == "System.String");
19834- }
19835 }
19836 }
19837diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededUnboxingRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededUnboxingRule.cs
19838index 06bbc3b..1b5e6d7 100644
19839--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededUnboxingRule.cs
19840+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededUnboxingRule.cs
19841@@ -28,6 +28,7 @@
19842
19843 using System;
19844 using System.Collections.Generic;
19845+using System.Globalization;
19846
19847 using Mono.Cecil;
19848 using Mono.Cecil.Cil;
19849@@ -95,7 +96,6 @@ namespace Gendarme.Rules.Performance {
19850 private static string Previous (MethodDefinition method, Instruction ins)
19851 {
19852 string kind, name;
19853- string type = (ins.Operand as TypeReference).FullName;
19854
19855 ins = ins.Previous;
19856 Code previous_op_code = ins.OpCode.Code;
19857@@ -139,7 +139,8 @@ namespace Gendarme.Rules.Performance {
19858 default:
19859 return String.Empty;
19860 }
19861- return String.Format ("{0} '{1}' unboxed to type '{2}' {{0}} times.", kind, name, type);
19862+ return String.Format (CultureInfo.InvariantCulture, "{0} '{1}' unboxed to type '{2}' {{0}} times.",
19863+ kind, name, (ins.Operand as TypeReference).GetFullName ());
19864 }
19865
19866 // unboxing is never critical - but a high amount can be a sign of other problems too
19867@@ -189,7 +190,7 @@ namespace Gendarme.Rules.Performance {
19868 // we can't (always) avoid unboxing one time
19869 if (kvp.Value < 2)
19870 continue;
19871- string s = String.Format (kvp.Key, kvp.Value);
19872+ string s = String.Format (CultureInfo.InvariantCulture, kvp.Key, kvp.Value);
19873 Runner.Report (method, GetSeverityFromCount (kvp.Value), Confidence.Normal, s);
19874 }
19875
19876diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnsealedUninheritedInternalClassesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnsealedUninheritedInternalClassesRule.cs
19877index c5f53ac..d7489c3 100644
19878--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnsealedUninheritedInternalClassesRule.cs
19879+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnsealedUninheritedInternalClassesRule.cs
19880@@ -74,16 +74,17 @@ namespace Gendarme.Rules.Performance {
19881 return RuleResult.Success;
19882
19883 ModuleDefinition module = type.Module;
19884- string type_name = type.FullName;
19885+ string name = type.Name;
19886+ string nspace = type.Namespace;
19887 foreach (TypeDefinition type_definition in module.GetAllTypes ()) {
19888 // skip ourself
19889- if (type_definition.FullName == type_name)
19890+ if (type_definition.IsNamed (nspace, name))
19891 continue;
19892- if (type_definition.Inherits (type_name))
19893+ if (type_definition.Inherits (nspace, name))
19894 return RuleResult.Success;
19895 }
19896
19897- Confidence c = module.Assembly.HasAttribute ("System.Runtime.CompilerServices.InternalsVisibleToAttribute") ?
19898+ Confidence c = module.Assembly.HasAttribute ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute") ?
19899 Confidence.High : Confidence.Total;
19900 Runner.Report (type, Severity.Medium, c);
19901 return RuleResult.Failure;
19902diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedParametersRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedParametersRule.cs
19903index 75a6448..8df328f 100644
19904--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedParametersRule.cs
19905+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedParametersRule.cs
19906@@ -30,6 +30,7 @@
19907
19908 using System;
19909 using System.Collections.Generic;
19910+using System.Globalization;
19911
19912 using Mono.Cecil;
19913 using Mono.Cecil.Cil;
19914@@ -132,10 +133,8 @@ namespace Gendarme.Rules.Performance {
19915 return RuleResult.DoesNotApply;
19916
19917 // methods with [Conditional] can be empty (not using any parameter) IL-wise but not source-wise, ignore them
19918- if (method.HasCustomAttributes) {
19919- if (method.CustomAttributes.ContainsType ("System.Diagnostics.ConditionalAttribute"))
19920- return RuleResult.DoesNotApply;
19921- }
19922+ if (method.HasAttribute ("System.Diagnostics", "ConditionalAttribute"))
19923+ return RuleResult.DoesNotApply;
19924
19925 // rule applies
19926
19927@@ -151,7 +150,7 @@ namespace Gendarme.Rules.Performance {
19928 ParameterDefinition parameter = ins.GetParameter (method);
19929 if (parameter == null)
19930 continue;
19931- mask |= ((ulong)1 << (parameter.GetSequence () - 1));
19932+ mask |= ((ulong)1 << parameter.Index);
19933 }
19934
19935 // quick out based on value - i.e. every parameter is being used
19936@@ -162,7 +161,8 @@ namespace Gendarme.Rules.Performance {
19937 for (int i = 0; i < pcount; i++) {
19938 if ((mask & ((ulong) 1 << i)) == 0) {
19939 ParameterDefinition parameter = pdc [i];
19940- string text = String.Format ("Parameter '{0}' of type '{1}' is never used in the method.",
19941+ string text = String.Format (CultureInfo.InvariantCulture,
19942+ "Parameter '{0}' of type '{1}' is never used in the method.",
19943 parameter.Name, parameter.ParameterType);
19944 Runner.Report (parameter, Severity.Medium, Confidence.Normal, text);
19945 }
19946diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedPrivateFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedPrivateFieldsRule.cs
19947index bc8c0e5..72a548c 100644
19948--- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedPrivateFieldsRule.cs
19949+++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedPrivateFieldsRule.cs
19950@@ -105,13 +105,32 @@ namespace Gendarme.Rules.Performance {
19951 // copy all fields into an hashset
19952 fields.Clear ();
19953 foreach (FieldDefinition field in type.Fields) {
19954- if (!field.IsPrivate || field.IsLiteral)
19955+ if (!field.IsPrivate || field.IsLiteral || field.IsGeneratedCode ())
19956 continue;
19957
19958 fields.Add (field);
19959 }
19960
19961 // scan all methods, including constructors, to find if the field is used
19962+ if (fields.Count > 0) {
19963+ CheckFieldsUsageInType (type);
19964+
19965+ // scan nested types becuase they also have access to private fields of their parent
19966+ if (type.HasNestedTypes) {
19967+ foreach (TypeDefinition nested in type.NestedTypes)
19968+ CheckFieldsUsageInType (nested);
19969+ }
19970+
19971+ // check remaining (private) fields in the set
19972+ foreach (FieldDefinition field in fields) {
19973+ Runner.Report (field, Severity.Medium, Confidence.Normal);
19974+ }
19975+ }
19976+ return Runner.CurrentRuleResult;
19977+ }
19978+
19979+ private void CheckFieldsUsageInType (TypeDefinition type)
19980+ {
19981 foreach (MethodDefinition method in type.Methods) {
19982 if (!method.HasBody)
19983 continue;
19984@@ -127,14 +146,12 @@ namespace Gendarme.Rules.Performance {
19985
19986 fields.Remove (fd);
19987 }
19988+
19989+ if (fields.Count == 0)
19990+ break;
19991 }
19992-
19993- // check remaining (private) fields in the set
19994- foreach (FieldDefinition field in fields) {
19995- Runner.Report (field, Severity.Medium, Confidence.Normal);
19996- }
19997- return Runner.CurrentRuleResult;
19998 }
19999+
20000 #if false
20001 public void Bitmask ()
20002 {
20003diff --git a/gendarme/rules/Gendarme.Rules.Performance/CompareWithStringEmptyEfficientlyRule.cs b/gendarme/rules/Gendarme.Rules.Performance/CompareWithStringEmptyEfficientlyRule.cs
20004index 61fdee9..47f6e1e 100644
20005--- a/gendarme/rules/Gendarme.Rules.Performance/CompareWithStringEmptyEfficientlyRule.cs
20006+++ b/gendarme/rules/Gendarme.Rules.Performance/CompareWithStringEmptyEfficientlyRule.cs
20007@@ -94,13 +94,16 @@ namespace Gendarme.Rules.Performance {
20008 case "Equals":
20009 if (mref.Parameters.Count > 1)
20010 continue;
20011- string tname = mref.DeclaringType.FullName;
20012- if ((tname != "System.String") && (tname != "System.Object"))
20013+ TypeReference type = mref.DeclaringType;
20014+ if (type.Namespace != "System")
20015+ continue;
20016+ string name = type.Name;
20017+ if ((name != "String") && (name != "Object"))
20018 continue;
20019 break;
20020 case "op_Equality":
20021 case "op_Inequality":
20022- if (mref.DeclaringType.FullName != "System.String")
20023+ if (!mref.DeclaringType.IsNamed ("System", "String"))
20024 continue;
20025 break;
20026 default:
20027@@ -115,7 +118,7 @@ namespace Gendarme.Rules.Performance {
20028 break;
20029 case Code.Ldsfld:
20030 FieldReference field = (prev.Operand as FieldReference);
20031- if (field.DeclaringType.FullName != "System.String")
20032+ if (!field.DeclaringType.IsNamed ("System", "String"))
20033 continue;
20034 // unlikely to be anything else (at least with released fx)
20035 if (field.Name != "Empty")
20036diff --git a/gendarme/rules/Gendarme.Rules.Performance/DontIgnoreMethodResultRule.cs b/gendarme/rules/Gendarme.Rules.Performance/DontIgnoreMethodResultRule.cs
20037index aadb867..fbd1931 100644
20038--- a/gendarme/rules/Gendarme.Rules.Performance/DontIgnoreMethodResultRule.cs
20039+++ b/gendarme/rules/Gendarme.Rules.Performance/DontIgnoreMethodResultRule.cs
20040@@ -29,6 +29,7 @@
20041 //
20042
20043 using System;
20044+using System.Globalization;
20045
20046 using Mono.Cecil;
20047 using Mono.Cecil.Cil;
20048@@ -99,17 +100,17 @@ namespace Gendarme.Rules.Performance {
20049
20050 private static bool IsCallException (MethodReference method)
20051 {
20052- switch (method.DeclaringType.FullName) {
20053+ switch (method.DeclaringType.GetFullName ()) {
20054 case "System.String":
20055 // Since strings are immutable, calling System.String methods that returns strings
20056 // better be assigned to something
20057- return (method.ReturnType.FullName != "System.String");
20058+ return !method.ReturnType.IsNamed ("System", "String");
20059 case "System.IO.DirectoryInfo":
20060 // GetDirectories overloads don't apply to the instance
20061 return (method.Name != "GetDirectories");
20062 case "System.Security.PermissionSet":
20063 // Intersection and Union returns a new PermissionSet (it does not change the instance)
20064- return (method.ReturnType.FullName != "System.Security.PermissionSet");
20065+ return !method.ReturnType.IsNamed ("System.Security", "PermissionSet");
20066 default:
20067 // this is useless anytime, if unassigned, more in cases like a StringBuilder
20068 return (method.Name != "ToString");
20069@@ -118,7 +119,7 @@ namespace Gendarme.Rules.Performance {
20070
20071 private static bool IsNewException (MemberReference method)
20072 {
20073- switch (method.ToString ()) {
20074+ switch (method.GetFullName ()) {
20075 // supplying a callback is enough to make the Timer creation worthwhile
20076 case "System.Void System.Threading.Timer::.ctor(System.Threading.TimerCallback,System.Object,System.Int32,System.Int32)":
20077 return true;
20078@@ -132,7 +133,8 @@ namespace Gendarme.Rules.Performance {
20079 if ((instruction.OpCode.Code == Code.Newobj || instruction.OpCode.Code == Code.Newarr)) {
20080 MemberReference member = (instruction.Operand as MemberReference);
20081 if ((member != null) && !IsNewException (member)) {
20082- string s = String.Format ("Unused object of type '{0}' created.", member.ToString ());
20083+ string s = String.Format (CultureInfo.InvariantCulture,
20084+ "Unused object of type '{0}' created.", member.GetFullName ());
20085 Runner.Report (method, instruction, Severity.High, Confidence.Normal, s);
20086 }
20087 }
20088@@ -142,7 +144,8 @@ namespace Gendarme.Rules.Performance {
20089 if (callee != null && !callee.ReturnType.IsValueType) {
20090 // check for some common exceptions (to reduce false positive)
20091 if (!IsCallException (callee)) {
20092- string s = String.Format ("Do not ignore method results from call to '{0}'.", callee.ToString ());
20093+ string s = String.Format (CultureInfo.InvariantCulture,
20094+ "Do not ignore method results from call to '{0}'.", callee.GetFullName ());
20095 Runner.Report (method, instruction, Severity.Medium, Confidence.Normal, s);
20096 }
20097 }
20098diff --git a/gendarme/rules/Gendarme.Rules.Performance/EmptyDestructorRule.cs b/gendarme/rules/Gendarme.Rules.Performance/EmptyDestructorRule.cs
20099index a6b3bb3..4971448 100644
20100--- a/gendarme/rules/Gendarme.Rules.Performance/EmptyDestructorRule.cs
20101+++ b/gendarme/rules/Gendarme.Rules.Performance/EmptyDestructorRule.cs
20102@@ -27,6 +27,7 @@
20103 //
20104
20105 using System;
20106+using System.Globalization;
20107
20108 using Mono.Cecil;
20109 using Mono.Cecil.Cil;
20110@@ -131,7 +132,8 @@ namespace Gendarme.Rules.Performance {
20111
20112 // finalizer is empty (bad / useless)
20113 string msg = nullify_fields == 0 ? String.Empty :
20114- String.Format ("Contains {0} fields being nullified needlessly", nullify_fields);
20115+ String.Format (CultureInfo.InvariantCulture,
20116+ "Contains {0} fields being nullified needlessly", nullify_fields);
20117 Runner.Report (type, Severity.Medium, Confidence.Normal, msg);
20118 return RuleResult.Failure;
20119 }
20120diff --git a/gendarme/rules/Gendarme.Rules.Performance/Gendarme.Rules.Performance.csproj b/gendarme/rules/Gendarme.Rules.Performance/Gendarme.Rules.Performance.csproj
20121index f9a5521..e8266ab 100755
20122--- a/gendarme/rules/Gendarme.Rules.Performance/Gendarme.Rules.Performance.csproj
20123+++ b/gendarme/rules/Gendarme.Rules.Performance/Gendarme.Rules.Performance.csproj
20124@@ -1,5 +1,5 @@
20125 <?xml version="1.0" encoding="utf-8"?>\r
20126-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
20127+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
20128 <PropertyGroup>\r
20129 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
20130 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
20131@@ -12,9 +12,11 @@
20132 <AssemblyName>Gendarme.Rules.Performance</AssemblyName>\r
20133 <FileUpgradeFlags>\r
20134 </FileUpgradeFlags>\r
20135- <OldToolsVersion>2.0</OldToolsVersion>\r
20136+ <OldToolsVersion>3.5</OldToolsVersion>\r
20137 <UpgradeBackupLocation>\r
20138 </UpgradeBackupLocation>\r
20139+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
20140+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
20141 <PublishUrl>http://localhost/Gendarme.Rules.Performance/</PublishUrl>\r
20142 <Install>true</Install>\r
20143 <InstallFrom>Web</InstallFrom>\r
20144@@ -27,10 +29,9 @@
20145 <MapFileExtensions>true</MapFileExtensions>\r
20146 <ApplicationRevision>0</ApplicationRevision>\r
20147 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
20148- <IsWebBootstrapper>true</IsWebBootstrapper>\r
20149 <UseApplicationTrust>false</UseApplicationTrust>\r
20150 <BootstrapperEnabled>true</BootstrapperEnabled>\r
20151- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
20152+ <TargetFrameworkProfile />\r
20153 </PropertyGroup>\r
20154 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
20155 <DebugSymbols>true</DebugSymbols>\r
20156@@ -43,6 +44,7 @@
20157 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Performance.xml</DocumentationFile>\r
20158 <NoWarn>1591</NoWarn>\r
20159 <WarningsAsErrors>1570</WarningsAsErrors>\r
20160+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
20161 </PropertyGroup>\r
20162 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
20163 <DebugType>pdbonly</DebugType>\r
20164@@ -54,6 +56,7 @@
20165 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Performance.xml</DocumentationFile>\r
20166 <NoWarn>1591</NoWarn>\r
20167 <WarningsAsErrors>1570</WarningsAsErrors>\r
20168+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
20169 </PropertyGroup>\r
20170 <ItemGroup>\r
20171 <Reference Include="System" />\r
20172@@ -117,14 +120,33 @@
20173 <None Include="ChangeLog" />\r
20174 </ItemGroup>\r
20175 <ItemGroup>\r
20176+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
20177+ <Visible>False</Visible>\r
20178+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
20179+ <Install>false</Install>\r
20180+ </BootstrapperPackage>\r
20181 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
20182 <Visible>False</Visible>\r
20183+ <ProductName>\r
20184+ </ProductName>\r
20185+ <Install>false</Install>\r
20186 </BootstrapperPackage>\r
20187 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
20188 <Visible>False</Visible>\r
20189+ <ProductName>\r
20190+ </ProductName>\r
20191+ <Install>false</Install>\r
20192 </BootstrapperPackage>\r
20193 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
20194 <Visible>False</Visible>\r
20195+ <ProductName>\r
20196+ </ProductName>\r
20197+ <Install>false</Install>\r
20198+ </BootstrapperPackage>\r
20199+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
20200+ <Visible>False</Visible>\r
20201+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
20202+ <Install>false</Install>\r
20203 </BootstrapperPackage>\r
20204 </ItemGroup>\r
20205 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
20206diff --git a/gendarme/rules/Gendarme.Rules.Performance/IDisposableWithDestructorWithoutSuppressFinalizeRule.cs b/gendarme/rules/Gendarme.Rules.Performance/IDisposableWithDestructorWithoutSuppressFinalizeRule.cs
20207index 7d81391..d02c1c0 100644
20208--- a/gendarme/rules/Gendarme.Rules.Performance/IDisposableWithDestructorWithoutSuppressFinalizeRule.cs
20209+++ b/gendarme/rules/Gendarme.Rules.Performance/IDisposableWithDestructorWithoutSuppressFinalizeRule.cs
20210@@ -128,7 +128,7 @@ namespace Gendarme.Rules.Performance {
20211 case Code.Callvirt:
20212 // are we calling GC.SuppressFinalize ?
20213 MethodReference callee = (ins.Operand as MethodReference);
20214- if ((callee.Name == "SuppressFinalize") && (callee.DeclaringType.FullName == "System.GC")) {
20215+ if (callee.IsNamed ("System", "GC", "SuppressFinalize")) {
20216 return true;
20217 } else if (level < 3) {
20218 if (Recurse (callee.Resolve (), level + 1))
20219@@ -154,7 +154,7 @@ namespace Gendarme.Rules.Performance {
20220 return RuleResult.DoesNotApply;
20221
20222 // rule applies to types that implements System.IDisposable
20223- if (!type.Implements ("System.IDisposable"))
20224+ if (!type.Implements ("System", "IDisposable"))
20225 return RuleResult.DoesNotApply;
20226
20227 // and provide a finalizer
20228diff --git a/gendarme/rules/Gendarme.Rules.Performance/ImplementEqualsTypeRule.cs b/gendarme/rules/Gendarme.Rules.Performance/ImplementEqualsTypeRule.cs
20229index 528a7cf..76240b4 100644
20230--- a/gendarme/rules/Gendarme.Rules.Performance/ImplementEqualsTypeRule.cs
20231+++ b/gendarme/rules/Gendarme.Rules.Performance/ImplementEqualsTypeRule.cs
20232@@ -27,6 +27,7 @@
20233 //
20234
20235 using System;
20236+using System.Globalization;
20237
20238 using Mono.Cecil;
20239
20240@@ -107,20 +108,20 @@ namespace Gendarme.Rules.Performance {
20241 // * the assembly targets the 2.0 (or later) runtime
20242 // * and it does not already implement it
20243 if (type.Module.Runtime >= TargetRuntime.Net_2_0) {
20244- if (!type.Implements ("System.IEquatable`1")) {
20245+ if (!type.Implements ("System", "IEquatable`1")) {
20246 Runner.Report (type, Severity.Medium, Confidence.Total, "Implement System.IEquatable<T>");
20247 }
20248 return Runner.CurrentRuleResult;
20249 }
20250
20251- parameters [0] = type.FullName;
20252+ parameters [0] = type.GetFullName ();
20253 if (type.GetMethod (MethodAttributes.Public, "Equals", "System.Boolean", parameters) != null)
20254 return RuleResult.Success;
20255
20256 // we consider this a step more severe for value types since it will need
20257 // boxing/unboxing with Equals(object)
20258 Severity severity = type.IsValueType ? Severity.Medium : Severity.Low;
20259- string msg = String.Format ("Implement 'bool Equals({0})'", type.Name);
20260+ string msg = String.Format (CultureInfo.InvariantCulture, "Implement 'bool Equals({0})'", type.Name);
20261 Runner.Report (type, severity, Confidence.High, msg);
20262 return RuleResult.Failure;
20263 }
20264diff --git a/gendarme/rules/Gendarme.Rules.Performance/MathMinMaxCandidateRule.cs b/gendarme/rules/Gendarme.Rules.Performance/MathMinMaxCandidateRule.cs
20265index 37bca4c..b87866f 100644
20266--- a/gendarme/rules/Gendarme.Rules.Performance/MathMinMaxCandidateRule.cs
20267+++ b/gendarme/rules/Gendarme.Rules.Performance/MathMinMaxCandidateRule.cs
20268@@ -83,18 +83,21 @@ namespace Gendarme.Rules.Performance {
20269 // unlikely than any JIT inlines it
20270 private static bool IsSupported (TypeReference type)
20271 {
20272- // GetOriginalType will remove the '&' for references
20273- switch (type.GetElementType ().FullName) {
20274- case "System.Byte":
20275- case "System.Double":
20276- case "System.Int16":
20277- case "System.Int32":
20278- case "System.Int64":
20279- case "System.SByte":
20280- case "System.Single":
20281- case "System.UInt16":
20282- case "System.UInt32":
20283- case "System.UInt64":
20284+ if (type.Namespace != "System")
20285+ return false;
20286+ // GetElementType will remove the '&' for references
20287+ TypeReference tr = type.GetElementType ();
20288+ switch (tr.Name) {
20289+ case "Byte":
20290+ case "Double":
20291+ case "Int16":
20292+ case "Int32":
20293+ case "Int64":
20294+ case "SByte":
20295+ case "Single":
20296+ case "UInt16":
20297+ case "UInt32":
20298+ case "UInt64":
20299 return true;
20300 default:
20301 return false;
20302diff --git a/gendarme/rules/Gendarme.Rules.Performance/OverrideValueTypeDefaultsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/OverrideValueTypeDefaultsRule.cs
20303index 5ab9c1c..169ced5 100644
20304--- a/gendarme/rules/Gendarme.Rules.Performance/OverrideValueTypeDefaultsRule.cs
20305+++ b/gendarme/rules/Gendarme.Rules.Performance/OverrideValueTypeDefaultsRule.cs
20306@@ -27,6 +27,7 @@
20307 //
20308
20309 using System;
20310+using System.Globalization;
20311
20312 using Mono.Cecil;
20313
20314@@ -118,7 +119,7 @@ namespace Gendarme.Rules.Performance {
20315 // drop severity one level if only operators are missing (since overloading them
20316 // is not available in every language)
20317 Severity severity = (equals || gethashcode) ? Severity.Medium : Severity.Low;
20318- string msg = String.Format (MissingImplementationMessage,
20319+ string msg = String.Format (CultureInfo.InvariantCulture, MissingImplementationMessage,
20320 !equals && !gethashcode ? "Equals(object)' and 'GetHashCode()" : equals ? "GetHashCode()" : "Equals(object)",
20321 operators ? String.Empty : MissingOperatorsMessage);
20322
20323diff --git a/gendarme/rules/Gendarme.Rules.Performance/PreferCharOverloadRule.cs b/gendarme/rules/Gendarme.Rules.Performance/PreferCharOverloadRule.cs
20324index a81b773..84c84aa 100644
20325--- a/gendarme/rules/Gendarme.Rules.Performance/PreferCharOverloadRule.cs
20326+++ b/gendarme/rules/Gendarme.Rules.Performance/PreferCharOverloadRule.cs
20327@@ -28,6 +28,7 @@
20328
20329 using System;
20330 using System.Collections.Generic;
20331+using System.Globalization;
20332
20333 using Mono.Cecil;
20334 using Mono.Cecil.Cil;
20335@@ -93,7 +94,8 @@ namespace Gendarme.Rules.Performance {
20336
20337 void Report (MethodDefinition method, Instruction ins, Confidence confidence, MemberReference call, string parameter)
20338 {
20339- string msg = String.Format ("Prefer the use of: {0}('{1}'...);", call.Name, parameter);
20340+ string msg = String.Format (CultureInfo.InvariantCulture, "Prefer the use of: {0}('{1}'...);",
20341+ call.Name, parameter);
20342 Runner.Report (method, ins, Severity.Medium, confidence, msg);
20343 }
20344
20345@@ -106,7 +108,7 @@ namespace Gendarme.Rules.Performance {
20346
20347 IList<ParameterDefinition> pdc = call.Parameters;
20348 int last = pdc.Count;
20349- if (pdc [last - 1].ParameterType.FullName != "System.StringComparison") {
20350+ if (!pdc [last - 1].ParameterType.IsNamed ("System", "StringComparison")) {
20351 // confidence is normal because it's possible that the code expects a
20352 // culture sensitive comparison (but that will break in .NET 4).
20353 Report (method, ins, Confidence.Normal, call, p1);
20354@@ -140,14 +142,15 @@ namespace Gendarme.Rules.Performance {
20355 if (p2.Length != 1)
20356 return;
20357
20358- string msg = String.Format ("Prefer the use of: Replace('{0}','{1}');", p1, p2);
20359+ string msg = String.Format (CultureInfo.InvariantCulture,
20360+ "Prefer the use of: Replace('{0}','{1}');", p1, p2);
20361 // confidence is higher since there's no StringComparison to consider
20362 Runner.Report (method, ins, Severity.Medium, Confidence.High, msg);
20363 }
20364
20365 static bool CheckFirstParameterIsString (IMethodSignature method)
20366 {
20367- return (method.HasParameters && (method.Parameters [0].ParameterType.FullName == "System.String"));
20368+ return (method.HasParameters && method.Parameters [0].ParameterType.IsNamed ("System", "String"));
20369 }
20370
20371 public RuleResult CheckMethod (MethodDefinition method)
20372@@ -165,7 +168,7 @@ namespace Gendarme.Rules.Performance {
20373 continue;
20374
20375 MethodReference call = (ins.Operand as MethodReference);
20376- if (call.DeclaringType.FullName != "System.String")
20377+ if (!call.DeclaringType.IsNamed ("System", "String"))
20378 continue;
20379
20380 switch (call.Name) {
20381diff --git a/gendarme/rules/Gendarme.Rules.Performance/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule.cs b/gendarme/rules/Gendarme.Rules.Performance/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule.cs
20382index 2567025..6dac441 100644
20383--- a/gendarme/rules/Gendarme.Rules.Performance/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule.cs
20384+++ b/gendarme/rules/Gendarme.Rules.Performance/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule.cs
20385@@ -28,7 +28,10 @@
20386
20387 using System;
20388 using System.Collections.Generic;
20389+using System.Globalization;
20390+
20391 using Gendarme.Framework;
20392+using Gendarme.Framework.Rocks;
20393 using Mono.Cecil;
20394
20395 namespace Gendarme.Rules.Performance {
20396@@ -61,41 +64,49 @@ namespace Gendarme.Rules.Performance {
20397 [Solution("Replace the interface parameter with interface constraint on generic type parameter.")]
20398 public class PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule : Rule, IMethodRule {
20399
20400- private readonly HashSet<string> primitiveTypeInterfaces = new HashSet<string> ();
20401+ static bool CheckGenericArgument (GenericInstanceType git)
20402+ {
20403+ if ((git == null) || !git.HasGenericArguments)
20404+ return false; // should not happen with the '`1' but...
20405+
20406+ TypeReference arg = git.GenericArguments [0];
20407+ switch (arg.MetadataType) {
20408+ case MetadataType.MVar:
20409+ return (arg.IsGenericParameter && arg.IsNamed (String.Empty, "T"));
20410+ case MetadataType.ValueType:
20411+ return arg.IsNamed ("System", "Decimal");
20412+ case MetadataType.Boolean:
20413+ case MetadataType.Byte:
20414+ case MetadataType.Char:
20415+ case MetadataType.Double:
20416+ case MetadataType.Single:
20417+ case MetadataType.Int16:
20418+ case MetadataType.Int32:
20419+ case MetadataType.Int64:
20420+ case MetadataType.SByte:
20421+ case MetadataType.UInt16:
20422+ case MetadataType.UInt32:
20423+ case MetadataType.UInt64:
20424+ return true;
20425+ default:
20426+ return false;
20427+ }
20428+ }
20429
20430- public PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule ()
20431+ static bool IsPrimitiveInterface (MemberReference type)
20432 {
20433- primitiveTypeInterfaces.Add ("System.IComparable");
20434- primitiveTypeInterfaces.Add ("System.IComparable`1<T>");
20435- primitiveTypeInterfaces.Add ("System.IComparable`1<System.Boolean>");
20436- primitiveTypeInterfaces.Add ("System.IComparable`1<System.Byte>");
20437- primitiveTypeInterfaces.Add ("System.IComparable`1<System.Char>");
20438- primitiveTypeInterfaces.Add ("System.IComparable`1<System.Decimal>");
20439- primitiveTypeInterfaces.Add ("System.IComparable`1<System.Double>");
20440- primitiveTypeInterfaces.Add ("System.IComparable`1<System.Float>");
20441- primitiveTypeInterfaces.Add ("System.IComparable`1<System.Int32>");
20442- primitiveTypeInterfaces.Add ("System.IComparable`1<System.Int64>");
20443- primitiveTypeInterfaces.Add ("System.IComparable`1<System.SByte>");
20444- primitiveTypeInterfaces.Add ("System.IComparable`1<System.Short>");
20445- primitiveTypeInterfaces.Add ("System.IComparable`1<System.UInt16>");
20446- primitiveTypeInterfaces.Add ("System.IComparable`1<System.UInt32>");
20447- primitiveTypeInterfaces.Add ("System.IComparable`1<System.UInt64>");
20448- primitiveTypeInterfaces.Add ("System.IFormattable");
20449- primitiveTypeInterfaces.Add ("System.IConvertible");
20450- primitiveTypeInterfaces.Add ("System.IEquatable`1<T>");
20451- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.Boolean>");
20452- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.Byte>");
20453- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.Char>");
20454- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.Decimal>");
20455- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.Double>");
20456- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.Float>");
20457- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.Int32>");
20458- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.Int64>");
20459- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.SByte>");
20460- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.Short>");
20461- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.UInt16>");
20462- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.UInt32>");
20463- primitiveTypeInterfaces.Add ("System.IEquatable`1<System.UInt64>");
20464+ switch (type.Name) {
20465+ case "IComparable":
20466+ case "IFormattable":
20467+ case "IConvertible":
20468+ return true; // no doubt
20469+ case "IComparable`1":
20470+ case "IEquatable`1":
20471+ // maybe, check generic argument type
20472+ return CheckGenericArgument (type as GenericInstanceType);
20473+ default:
20474+ return false;
20475+ }
20476 }
20477
20478 public RuleResult CheckMethod (MethodDefinition method)
20479@@ -108,10 +119,10 @@ namespace Gendarme.Rules.Performance {
20480 if (type.Namespace != "System")
20481 continue;
20482
20483- string tname = type.FullName;
20484- if (primitiveTypeInterfaces.Contains (tname)) {
20485- string msg = String.Format ("You are using {0} as parameter, which cause boxing with value type as argument",
20486- tname);
20487+ if (IsPrimitiveInterface (type)) {
20488+ string msg = String.Format (CultureInfo.InvariantCulture,
20489+ "You are using {0} as parameter, which cause boxing with value type as argument",
20490+ type.GetFullName ());
20491 Runner.Report (method, Severity.Low, Confidence.Total, msg);
20492 }
20493 }
20494diff --git a/gendarme/rules/Gendarme.Rules.Performance/PreferLiteralOverInitOnlyFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/PreferLiteralOverInitOnlyFieldsRule.cs
20495index a28601b..31310f8 100644
20496--- a/gendarme/rules/Gendarme.Rules.Performance/PreferLiteralOverInitOnlyFieldsRule.cs
20497+++ b/gendarme/rules/Gendarme.Rules.Performance/PreferLiteralOverInitOnlyFieldsRule.cs
20498@@ -113,7 +113,7 @@ namespace Gendarme.Rules.Performance {
20499 // and report constant stuff
20500 if (Constant.Get (previous.OpCode.Code)) {
20501 // adjust severity based on the field visibility and it's type
20502- Severity s = (field.FieldType.FullName == "System.String" || !field.IsVisible ()) ?
20503+ Severity s = (field.FieldType.IsNamed ("System", "String") || !field.IsVisible ()) ?
20504 Severity.High : Severity.Medium;
20505 Runner.Report (field, s, Confidence.Normal);
20506 }
20507diff --git a/gendarme/rules/Gendarme.Rules.Performance/README.md b/gendarme/rules/Gendarme.Rules.Performance/README.md
20508new file mode 100644
20509index 0000000..5ef5f3b
20510--- /dev/null
20511+++ b/gendarme/rules/Gendarme.Rules.Performance/README.md
20512@@ -0,0 +1,9 @@
20513+# Gendarme.Rules.Performance Rules
20514+
20515+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Performance(git)]] pages.
20516+
20517+
20518+## Feedback
20519+
20520+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
20521+
20522diff --git a/gendarme/rules/Gendarme.Rules.Performance/RemoveUnusedLocalVariablesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/RemoveUnusedLocalVariablesRule.cs
20523index bf1cda5..ac4ece9 100644
20524--- a/gendarme/rules/Gendarme.Rules.Performance/RemoveUnusedLocalVariablesRule.cs
20525+++ b/gendarme/rules/Gendarme.Rules.Performance/RemoveUnusedLocalVariablesRule.cs
20526@@ -28,6 +28,7 @@
20527
20528 using System;
20529 using System.Collections;
20530+using System.Globalization;
20531
20532 using Mono.Cecil;
20533 using Mono.Cecil.Cil;
20534@@ -132,8 +133,8 @@ namespace Gendarme.Rules.Performance {
20535 if (variable.IsGeneratedName ())
20536 continue;
20537
20538- string s = String.Format ("Variable '{0}' of type '{1}'",
20539- variable.Name, variable.VariableType.FullName);
20540+ string s = String.Format (CultureInfo.InvariantCulture, "Variable '{0}' of type '{1}'",
20541+ variable.Name, variable.VariableType.GetFullName ());
20542 Runner.Report (method, Severity.Low, Confidence.Normal, s);
20543 }
20544 }
20545diff --git a/gendarme/rules/Gendarme.Rules.Performance/ReviewLinqMethodRule.cs b/gendarme/rules/Gendarme.Rules.Performance/ReviewLinqMethodRule.cs
20546index 0bef7c2..095c240 100644
20547--- a/gendarme/rules/Gendarme.Rules.Performance/ReviewLinqMethodRule.cs
20548+++ b/gendarme/rules/Gendarme.Rules.Performance/ReviewLinqMethodRule.cs
20549@@ -28,6 +28,7 @@
20550
20551 using System;
20552 using System.Collections.Generic;
20553+using System.Globalization;
20554
20555 using Mono.Cecil;
20556 using Mono.Cecil.Cil;
20557@@ -96,10 +97,6 @@ namespace Gendarme.Rules.Performance {
20558 [EngineDependency (typeof (OpCodeEngine))]
20559 public sealed class ReviewLinqMethodRule : Rule, IMethodRule {
20560
20561- private const string EnumerableName = "System.Linq.Enumerable";
20562-
20563- //private readonly OpCodeBitmask Comparisons = ComparisonsBitmask ();
20564- //private readonly OpCodeBitmask Conditions = ConditionsBitmask ();
20565 private readonly OpCodeBitmask Comparisons = new OpCodeBitmask (0x2801400000000000, 0x0, 0x0, 0xB);
20566 private readonly OpCodeBitmask Conditions = new OpCodeBitmask (0x300180000000000, 0x0, 0x0, 0x0);
20567
20568@@ -181,14 +178,16 @@ namespace Gendarme.Rules.Performance {
20569 private void CheckForSubscript (TypeReference type, MethodDefinition method, Instruction ins, string name)
20570 {
20571 if (type.IsArray) {
20572- string message = string.Format ("Use operator [] instead of the {0} method.", name);
20573+ string message = String.Format (CultureInfo.InvariantCulture,
20574+ "Use operator [] instead of the {0} method.", name);
20575 Log.WriteLine (this, "{0:X4} {1}", ins.Offset, message);
20576 Runner.Report (method, ins, Severity.Medium, Confidence.High, message);
20577
20578 } else {
20579 TypeDefinition td = type.Resolve (); // resolve of an array returns the element type...
20580 if (td != null && HasMethod (td, Subscript)) {
20581- string message = string.Format ("Use operator [] instead of the {0} method.", name);
20582+ string message = String.Format (CultureInfo.InvariantCulture,
20583+ "Use operator [] instead of the {0} method.", name);
20584 Log.WriteLine (this, "{0:X4} {1}", ins.Offset, message);
20585 Runner.Report (method, ins, Severity.Medium, Confidence.High, message);
20586 }
20587@@ -198,14 +197,16 @@ namespace Gendarme.Rules.Performance {
20588 private void CheckForSort (TypeReference type, MethodDefinition method, Instruction ins, string name)
20589 {
20590 if (type.IsArray) {
20591- string message = string.Format ("Use Array.Sort instead of the {0} method.", name);
20592+ string message = String.Format (CultureInfo.InvariantCulture,
20593+ "Use Array.Sort instead of the {0} method.", name);
20594 Log.WriteLine (this, "{0:X4} {1}", ins.Offset, message);
20595 Runner.Report (method, ins, Severity.Medium, Confidence.High, message);
20596
20597 } else {
20598 TypeDefinition td = type.Resolve (); // resolve of an array returns the element type...
20599 if (td != null && HasMethod (td, Sort)) {
20600- string message = string.Format ("Use Sort instead of the {0} method.", name);
20601+ string message = String.Format (CultureInfo.InvariantCulture,
20602+ "Use Sort instead of the {0} method.", name);
20603 Log.WriteLine (this, "{0:X4} {1}", ins.Offset, message);
20604 Runner.Report (method, ins, Severity.Medium, Confidence.High, message);
20605 }
20606@@ -251,7 +252,7 @@ namespace Gendarme.Rules.Performance {
20607
20608 // and the method is a System.Linq.Enumerable method then,
20609 var target = ins.Operand as MethodReference;
20610- if ((target == null) || (target.DeclaringType.FullName != EnumerableName))
20611+ if (!target.DeclaringType.IsNamed ("System.Linq", "Enumerable"))
20612 continue;
20613
20614 string tname = target.Name;
20615diff --git a/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidRepetitiveCallsToPropertiesTest.cs b/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidRepetitiveCallsToPropertiesTest.cs
20616index a82ddf4..fe00fcc 100644
20617--- a/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidRepetitiveCallsToPropertiesTest.cs
20618+++ b/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidRepetitiveCallsToPropertiesTest.cs
20619@@ -240,8 +240,8 @@ namespace Test.Rules.Performance {
20620 if ((source == null) || (target == null))
20621 return false;
20622
20623- int ss = source.GetSequence () - 1;
20624- int ts = target.GetSequence () - 1;
20625+ int ss = source.Index;
20626+ int ts = target.Index;
20627 if ((ss <= 0) || (ts <= 0))
20628 return false;
20629
20630diff --git a/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidUnusedPrivateFieldsTest.cs b/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidUnusedPrivateFieldsTest.cs
20631index 212bebf..98fbb3a 100644
20632--- a/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidUnusedPrivateFieldsTest.cs
20633+++ b/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidUnusedPrivateFieldsTest.cs
20634@@ -162,5 +162,46 @@ namespace Test.Rules.Performance {
20635 AssertRuleFailure<GenericUnused<int>> (1);
20636 AssertRuleSuccess<GenericUsed<int>> ();
20637 }
20638+
20639+ class FieldsUsedInNested {
20640+ private bool field;
20641+
20642+ private static string staticField;
20643+
20644+ class Nested {
20645+ public void Foo (FieldsUsedInNested parent)
20646+ {
20647+ FieldsUsedInNested.staticField = "bar";
20648+ parent.field = true;
20649+ }
20650+ }
20651+ }
20652+
20653+ [Test]
20654+ public void FieldsUsedInNestedType ()
20655+ {
20656+ AssertRuleSuccess<FieldsUsedInNested> ();
20657+ }
20658+
20659+ class CompilerGenerated {
20660+ public string Name { get; set; }
20661+ }
20662+
20663+ [Test]
20664+ public void ClassWithCompilerGeneratedFields ()
20665+ {
20666+ AssertRuleSuccess<CompilerGenerated> ();
20667+ }
20668+
20669+ class CompilerGeneratedAndUnused {
20670+ private int number;
20671+ public string Name { get; set; }
20672+ }
20673+
20674+ [Test]
20675+ public void ClassWithCompilerGeneratedFieldsAndUnusedPrivate ()
20676+ {
20677+ AssertRuleFailure<CompilerGeneratedAndUnused> (1);
20678+ }
20679 }
20680 }
20681diff --git a/gendarme/rules/Gendarme.Rules.Performance/Test/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceTest.cs b/gendarme/rules/Gendarme.Rules.Performance/Test/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceTest.cs
20682index 22200a8..76b1fc0 100644
20683--- a/gendarme/rules/Gendarme.Rules.Performance/Test/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceTest.cs
20684+++ b/gendarme/rules/Gendarme.Rules.Performance/Test/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceTest.cs
20685@@ -52,7 +52,17 @@ namespace Tests.Rules.Performance {
20686
20687 }
20688
20689- private void MethodWithGenericInterfaceOfBaseTypeParameter2 (IComparable<int> comparable)
20690+ private void MethodWithGenericInterfaceOfBaseTypeParameter2a (IComparable<int> comparable)
20691+ {
20692+
20693+ }
20694+
20695+ private void MethodWithGenericInterfaceOfBaseTypeParameter2b (IComparable<decimal> comparable)
20696+ {
20697+
20698+ }
20699+
20700+ private void MethodWithGenericInterfaceOfBaseTypeParameter2c (IComparable<object> comparable)
20701 {
20702
20703 }
20704@@ -101,25 +111,27 @@ namespace Tests.Rules.Performance {
20705 [Test]
20706 public void MethodWithInterfaceOfBaseTypeParameter ()
20707 {
20708- AssertRuleFailure<TestCase> ("MethodWithInterfaceOfBaseTypeParameter");
20709+ AssertRuleFailure<TestCase> ("MethodWithInterfaceOfBaseTypeParameter", 1);
20710 }
20711
20712 [Test]
20713 public void MethodWithGenericInterfaceOfBaseTypeParameter ()
20714 {
20715- AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter");
20716+ AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter", 1);
20717 }
20718
20719 [Test]
20720 public void MethodWithGenericInterfaceOfBaseTypeParameter2 ()
20721 {
20722- AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter2");
20723+ AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter2a", 1);
20724+ AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter2b", 1);
20725+ AssertRuleSuccess<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter2c");
20726 }
20727
20728 [Test]
20729 public void MethodWithMultipleParameters ()
20730 {
20731- AssertRuleFailure<TestCase> ("MethodWithMultipleParameters");
20732+ AssertRuleFailure<TestCase> ("MethodWithMultipleParameters", 1);
20733 }
20734
20735 [Test]
20736diff --git a/gendarme/rules/Gendarme.Rules.Performance/Test/Tests.Rules.Performance.csproj b/gendarme/rules/Gendarme.Rules.Performance/Test/Tests.Rules.Performance.csproj
20737index 16c7b64..531edcd 100755
20738--- a/gendarme/rules/Gendarme.Rules.Performance/Test/Tests.Rules.Performance.csproj
20739+++ b/gendarme/rules/Gendarme.Rules.Performance/Test/Tests.Rules.Performance.csproj
20740@@ -1,5 +1,5 @@
20741 <?xml version="1.0" encoding="utf-8"?>\r
20742-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
20743+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
20744 <PropertyGroup>\r
20745 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
20746 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
20747@@ -12,9 +12,11 @@
20748 <AssemblyName>Tests.Rules.Performance</AssemblyName>\r
20749 <FileUpgradeFlags>\r
20750 </FileUpgradeFlags>\r
20751- <OldToolsVersion>2.0</OldToolsVersion>\r
20752+ <OldToolsVersion>3.5</OldToolsVersion>\r
20753 <UpgradeBackupLocation>\r
20754 </UpgradeBackupLocation>\r
20755+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
20756+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
20757 <PublishUrl>http://localhost/Tests.Rules.Performance/</PublishUrl>\r
20758 <Install>true</Install>\r
20759 <InstallFrom>Web</InstallFrom>\r
20760@@ -27,10 +29,9 @@
20761 <MapFileExtensions>true</MapFileExtensions>\r
20762 <ApplicationRevision>0</ApplicationRevision>\r
20763 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
20764- <IsWebBootstrapper>true</IsWebBootstrapper>\r
20765 <UseApplicationTrust>false</UseApplicationTrust>\r
20766 <BootstrapperEnabled>true</BootstrapperEnabled>\r
20767- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
20768+ <TargetFrameworkProfile />\r
20769 </PropertyGroup>\r
20770 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
20771 <DebugSymbols>true</DebugSymbols>\r
20772@@ -41,6 +42,7 @@
20773 <ErrorReport>prompt</ErrorReport>\r
20774 <WarningLevel>4</WarningLevel>\r
20775 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
20776+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
20777 </PropertyGroup>\r
20778 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
20779 <DebugType>pdbonly</DebugType>\r
20780@@ -50,6 +52,7 @@
20781 <ErrorReport>prompt</ErrorReport>\r
20782 <WarningLevel>4</WarningLevel>\r
20783 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
20784+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
20785 </PropertyGroup>\r
20786 <ItemGroup>\r
20787 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
20788@@ -121,14 +124,33 @@
20789 </ProjectReference>\r
20790 </ItemGroup>\r
20791 <ItemGroup>\r
20792+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
20793+ <Visible>False</Visible>\r
20794+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
20795+ <Install>false</Install>\r
20796+ </BootstrapperPackage>\r
20797 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
20798 <Visible>False</Visible>\r
20799+ <ProductName>\r
20800+ </ProductName>\r
20801+ <Install>false</Install>\r
20802 </BootstrapperPackage>\r
20803 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
20804 <Visible>False</Visible>\r
20805+ <ProductName>\r
20806+ </ProductName>\r
20807+ <Install>false</Install>\r
20808 </BootstrapperPackage>\r
20809 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
20810 <Visible>False</Visible>\r
20811+ <ProductName>\r
20812+ </ProductName>\r
20813+ <Install>false</Install>\r
20814+ </BootstrapperPackage>\r
20815+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
20816+ <Visible>False</Visible>\r
20817+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
20818+ <Install>false</Install>\r
20819 </BootstrapperPackage>\r
20820 </ItemGroup>\r
20821 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
20822diff --git a/gendarme/rules/Gendarme.Rules.Performance/UseTypeEmptyTypesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/UseTypeEmptyTypesRule.cs
20823index 21b0879..92efb53 100644
20824--- a/gendarme/rules/Gendarme.Rules.Performance/UseTypeEmptyTypesRule.cs
20825+++ b/gendarme/rules/Gendarme.Rules.Performance/UseTypeEmptyTypesRule.cs
20826@@ -83,9 +83,7 @@ namespace Gendarme.Rules.Performance {
20827 if (ins.OpCode != OpCodes.Newarr)
20828 continue;
20829
20830- var type = (TypeReference) ins.Operand;
20831-
20832- if (type.FullName != "System.Type")
20833+ if (!(ins.Operand as TypeReference).IsNamed ("System", "Type"))
20834 continue;
20835
20836 if (ins.Previous.IsOperandZero ())
20837diff --git a/gendarme/rules/Gendarme.Rules.Portability/DoNotHardcodePathsRule.cs b/gendarme/rules/Gendarme.Rules.Portability/DoNotHardcodePathsRule.cs
20838index 009ebba..92b597a 100644
20839--- a/gendarme/rules/Gendarme.Rules.Portability/DoNotHardcodePathsRule.cs
20840+++ b/gendarme/rules/Gendarme.Rules.Portability/DoNotHardcodePathsRule.cs
20841@@ -28,6 +28,7 @@
20842
20843 using System;
20844 using System.Collections.Generic;
20845+using System.Globalization;
20846
20847 using Mono.Cecil;
20848 using Mono.Cecil.Cil;
20849@@ -363,11 +364,13 @@ namespace Gendarme.Rules.Portability {
20850
20851 // we can avoid some false positives by doing additional checks here
20852
20853+ TypeReference tr = target.DeclaringType;
20854+ string nameSpace = tr.Namespace;
20855+ string typeName = tr.Name;
20856 string methodName = target.Name;
20857- string typeName = target.DeclaringType.FullName;
20858
20859- if (typeName.StartsWith ("Microsoft.Win32.Registry", StringComparison.Ordinal) // registry keys
20860- || (typeName.StartsWith ("System.Xml", StringComparison.Ordinal) // xpath expressions
20861+ if (nameSpace == "Microsoft.Win32" && typeName.StartsWith ("Registry", StringComparison.Ordinal) // registry keys
20862+ || (nameSpace.StartsWith ("System.Xml", StringComparison.Ordinal) // xpath expressions
20863 && methodName.StartsWith ("Select", StringComparison.Ordinal))) {
20864 AddPoints (-42);
20865 return true; // handled
20866@@ -389,10 +392,8 @@ namespace Gendarme.Rules.Portability {
20867 case Code.Newobj:
20868 // this is a constructor call
20869 MethodReference ctor = (MethodReference) ins.Operand;
20870- string createdTypeName = ctor.DeclaringType.FullName;
20871-
20872 // avoid catching regular expressions
20873- if (createdTypeName == "System.Text.RegularExpressions.Regex")
20874+ if (ctor.DeclaringType.IsNamed ("System.Text.RegularExpressions", "Regex"))
20875 AddPoints (-42);
20876
20877 break;
20878@@ -494,7 +495,8 @@ namespace Gendarme.Rules.Portability {
20879 // if sure enough, report the problem with the candidate string
20880 // important as this allows a quick false positive check without checking the source code
20881 if (conf.HasValue) {
20882- string msg = String.Format ("string \"{0}\" looks quite like a filename.", candidate);
20883+ string msg = String.Format (CultureInfo.InvariantCulture,
20884+ "string \"{0}\" looks quite like a filename.", candidate);
20885 Runner.Report (method, ins, Severity.High, conf.Value, msg);
20886 }
20887 }
20888diff --git a/gendarme/rules/Gendarme.Rules.Portability/ExitCodeIsLimitedOnUnixRule.cs b/gendarme/rules/Gendarme.Rules.Portability/ExitCodeIsLimitedOnUnixRule.cs
20889index 29c63cd..5259d1d 100644
20890--- a/gendarme/rules/Gendarme.Rules.Portability/ExitCodeIsLimitedOnUnixRule.cs
20891+++ b/gendarme/rules/Gendarme.Rules.Portability/ExitCodeIsLimitedOnUnixRule.cs
20892@@ -107,7 +107,9 @@ namespace Gendarme.Rules.Portability {
20893 // but we want to avoid checking all methods if the Environment type
20894 // isn't referenced in a module (big performance difference)
20895 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
20896- Active = e.CurrentAssembly.MainModule.HasTypeReference ("System.Environment");
20897+ Active = e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
20898+ return tr.IsNamed ("System", "Environment");
20899+ });
20900 };
20901 }
20902
20903@@ -141,7 +143,7 @@ namespace Gendarme.Rules.Portability {
20904 // FIXME: entryPoint.ReturnType should not be null with void Main ()
20905 // either bad unit tests or bug in cecil
20906 TypeReference rt = entry_point.ReturnType;
20907- if (rt == null || rt.FullName != "System.Int32")
20908+ if (!rt.IsNamed ("System", "Int32"))
20909 return RuleResult.DoesNotApply;
20910
20911 Instruction previous = null;
20912@@ -188,7 +190,7 @@ namespace Gendarme.Rules.Portability {
20913 return (a >= 0 && a <= 255) ? InspectionResult.Good : InspectionResult.Bad;
20914 case Code.Call:
20915 case Code.Callvirt:
20916- if ((instruction.Operand as MethodReference).ReturnType.FullName == "System.Byte")
20917+ if ((instruction.Operand as MethodReference).ReturnType.IsNamed ("System", "Byte"))
20918 return InspectionResult.Good;
20919 else
20920 return InspectionResult.Unsure; // could be within 0-255 or not
20921@@ -217,7 +219,7 @@ namespace Gendarme.Rules.Portability {
20922 string name = calledMethod.Name;
20923 if ((name != "set_ExitCode") && (name != "Exit"))
20924 break;
20925- if (calledMethod.DeclaringType.FullName != "System.Environment")
20926+ if (!calledMethod.DeclaringType.IsNamed ("System", "Environment"))
20927 break;
20928
20929 InspectionResult result = CheckInstruction (previous);
20930diff --git a/gendarme/rules/Gendarme.Rules.Portability/FeatureRequiresRootPrivilegeOnUnixRule.cs b/gendarme/rules/Gendarme.Rules.Portability/FeatureRequiresRootPrivilegeOnUnixRule.cs
20931index 8de2f25..daeaf2c 100644
20932--- a/gendarme/rules/Gendarme.Rules.Portability/FeatureRequiresRootPrivilegeOnUnixRule.cs
20933+++ b/gendarme/rules/Gendarme.Rules.Portability/FeatureRequiresRootPrivilegeOnUnixRule.cs
20934@@ -84,10 +84,6 @@ namespace Gendarme.Rules.Portability {
20935 private const string ProcessMessage = "Setting Process.PriorityClass to something else than ProcessPriorityClass.Normal requires root privileges.";
20936 private const string PingMessage = "Usage of System.Net.NetworkInformation.Ping requires root privileges.";
20937
20938- // non-localizable
20939- private const string Ping = "System.Net.NetworkInformation.Ping";
20940- private const string Process = "System.Diagnostics.Process";
20941-
20942 private bool ping_present = true;
20943 private bool process_present = true;
20944
20945@@ -98,8 +94,13 @@ namespace Gendarme.Rules.Portability {
20946 // if the module does not reference either Ping or Process
20947 // then it's not being used inside it
20948 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
20949- ping_present = e.CurrentModule.HasTypeReference (Ping);
20950- process_present = e.CurrentModule.HasTypeReference (Process);
20951+ Active = e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
20952+ ping_present = tr.IsNamed ("System.Net.NetworkInformation", "Ping");
20953+ process_present = tr.IsNamed ("System.Diagnostics", "Process");
20954+ // return true to stop looping when both Ping and Process are found
20955+ return (ping_present && process_present);
20956+ });
20957+ // activate the rule if any (or both) is/are present(s)
20958 Active = (ping_present || process_present);
20959 };
20960 // note: this ignores on purpose System.dll since there's
20961@@ -112,7 +113,7 @@ namespace Gendarme.Rules.Portability {
20962 MethodReference method = (ins.Operand as MethodReference);
20963 if ((method == null) || (method.Name != "set_PriorityClass"))
20964 return false;
20965- if (method.DeclaringType.FullName != "System.Diagnostics.Process")
20966+ if (!method.DeclaringType.IsNamed ("System.Diagnostics", "Process"))
20967 return false;
20968
20969 Instruction prev = ins.Previous; //check stack
20970@@ -132,7 +133,7 @@ namespace Gendarme.Rules.Portability {
20971 private static bool CheckPing (Instruction ins)
20972 {
20973 MethodReference method = (ins.Operand as MethodReference);
20974- return ((method != null) && (method.DeclaringType.FullName == Ping));
20975+ return ((method != null) && (method.DeclaringType.IsNamed ("System.Net.NetworkInformation", "Ping")));
20976 }
20977
20978 public RuleResult CheckMethod (MethodDefinition method)
20979diff --git a/gendarme/rules/Gendarme.Rules.Portability/Gendarme.Rules.Portability.csproj b/gendarme/rules/Gendarme.Rules.Portability/Gendarme.Rules.Portability.csproj
20980index 1528411..283e5d5 100755
20981--- a/gendarme/rules/Gendarme.Rules.Portability/Gendarme.Rules.Portability.csproj
20982+++ b/gendarme/rules/Gendarme.Rules.Portability/Gendarme.Rules.Portability.csproj
20983@@ -1,5 +1,5 @@
20984 <?xml version="1.0" encoding="utf-8"?>\r
20985-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
20986+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
20987 <PropertyGroup>\r
20988 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
20989 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
20990@@ -12,9 +12,11 @@
20991 <AssemblyName>Gendarme.Rules.Portability</AssemblyName>\r
20992 <FileUpgradeFlags>\r
20993 </FileUpgradeFlags>\r
20994- <OldToolsVersion>2.0</OldToolsVersion>\r
20995+ <OldToolsVersion>3.5</OldToolsVersion>\r
20996 <UpgradeBackupLocation>\r
20997 </UpgradeBackupLocation>\r
20998+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
20999+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
21000 <PublishUrl>http://localhost/Gendarme.Rules.Portability/</PublishUrl>\r
21001 <Install>true</Install>\r
21002 <InstallFrom>Web</InstallFrom>\r
21003@@ -27,10 +29,9 @@
21004 <MapFileExtensions>true</MapFileExtensions>\r
21005 <ApplicationRevision>0</ApplicationRevision>\r
21006 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
21007- <IsWebBootstrapper>true</IsWebBootstrapper>\r
21008 <UseApplicationTrust>false</UseApplicationTrust>\r
21009 <BootstrapperEnabled>true</BootstrapperEnabled>\r
21010- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
21011+ <TargetFrameworkProfile />\r
21012 </PropertyGroup>\r
21013 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
21014 <DebugSymbols>true</DebugSymbols>\r
21015@@ -43,6 +44,7 @@
21016 <NoWarn>1591</NoWarn>\r
21017 <WarningsAsErrors>1570</WarningsAsErrors>\r
21018 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Portability.xml</DocumentationFile>\r
21019+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21020 </PropertyGroup>\r
21021 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
21022 <DebugType>pdbonly</DebugType>\r
21023@@ -54,6 +56,7 @@
21024 <NoWarn>1591</NoWarn>\r
21025 <WarningsAsErrors>1570</WarningsAsErrors>\r
21026 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Portability.xml</DocumentationFile>\r
21027+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21028 </PropertyGroup>\r
21029 <ItemGroup>\r
21030 <Reference Include="ICSharpCode.SharpZipLib, Version=2.84.0.0, Culture=neutral, PublicKeyToken=1b03e6acf1164f73, processorArchitecture=MSIL">\r
21031@@ -94,14 +97,33 @@
21032 <None Include="ChangeLog" />\r
21033 </ItemGroup>\r
21034 <ItemGroup>\r
21035+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
21036+ <Visible>False</Visible>\r
21037+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
21038+ <Install>false</Install>\r
21039+ </BootstrapperPackage>\r
21040 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
21041 <Visible>False</Visible>\r
21042+ <ProductName>\r
21043+ </ProductName>\r
21044+ <Install>false</Install>\r
21045 </BootstrapperPackage>\r
21046 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
21047 <Visible>False</Visible>\r
21048+ <ProductName>\r
21049+ </ProductName>\r
21050+ <Install>false</Install>\r
21051 </BootstrapperPackage>\r
21052 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
21053 <Visible>False</Visible>\r
21054+ <ProductName>\r
21055+ </ProductName>\r
21056+ <Install>false</Install>\r
21057+ </BootstrapperPackage>\r
21058+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
21059+ <Visible>False</Visible>\r
21060+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
21061+ <Install>false</Install>\r
21062 </BootstrapperPackage>\r
21063 </ItemGroup>\r
21064 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
21065diff --git a/gendarme/rules/Gendarme.Rules.Portability/MonoCompatibilityReviewRule.cs b/gendarme/rules/Gendarme.Rules.Portability/MonoCompatibilityReviewRule.cs
21066index 141323f..e3a5d3b 100644
21067--- a/gendarme/rules/Gendarme.Rules.Portability/MonoCompatibilityReviewRule.cs
21068+++ b/gendarme/rules/Gendarme.Rules.Portability/MonoCompatibilityReviewRule.cs
21069@@ -6,7 +6,7 @@
21070 // Sebastien Pouliot <sebastien@ximian.com>
21071 //
21072 // (C) 2007 Andreas Noever
21073-// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
21074+// Copyright (C) 2009, 2011 Novell, Inc (http://www.novell.com)
21075 //
21076 // Permission is hereby granted, free of charge, to any person obtaining
21077 // a copy of this software and associated documentation files (the
21078@@ -31,6 +31,7 @@
21079 using System;
21080 using System.Collections.Generic;
21081 using System.ComponentModel;
21082+using System.Globalization;
21083 using System.IO;
21084 using System.Net;
21085
21086@@ -40,6 +41,7 @@ using Mono.Cecil.Cil;
21087 using Gendarme.Framework;
21088 using Gendarme.Framework.Engines;
21089 using Gendarme.Framework.Helpers;
21090+using Gendarme.Framework.Rocks;
21091
21092 using ICSharpCode.SharpZipLib.Zip;
21093
21094@@ -126,7 +128,7 @@ namespace Gendarme.Rules.Portability {
21095
21096 private string GetFileName (Version v)
21097 {
21098- return Path.Combine (DefinitionsFolder, String.Format ("definitions-{0}.zip", v));
21099+ return Path.Combine (DefinitionsFolder, String.Format (CultureInfo.InvariantCulture, "definitions-{0}.zip", v));
21100 }
21101
21102 private Version FindLastestLocalVersion ()
21103@@ -139,7 +141,7 @@ namespace Gendarme.Rules.Portability {
21104
21105 try {
21106 string latest = def_files [def_files.Length - 1];
21107- int s = latest.LastIndexOf ("definitions-") + 12;
21108+ int s = latest.LastIndexOf ("definitions-", StringComparison.Ordinal) + 12;
21109 return new Version (latest.Substring (s, latest.Length - s - 4)); // remove .zip
21110 }
21111 catch (FormatException) {
21112@@ -175,7 +177,7 @@ namespace Gendarme.Rules.Portability {
21113
21114 using (FileStream fs = File.OpenRead (filename))
21115 using (ZipInputStream zs = new ZipInputStream (fs))
21116- using (StreamReader sr = new StreamReader (zs)) {
21117+ using (StreamLineReader sr = new StreamLineReader (zs)) {
21118 ZipEntry ze;
21119 while ((ze = zs.GetNextEntry ()) != null) {
21120 switch (ze.Name) {
21121@@ -291,29 +293,28 @@ namespace Gendarme.Rules.Portability {
21122 return v;
21123 }
21124
21125- private static Dictionary<string, string> ReadWithComments (TextReader reader)
21126+ static char [] buffer = new char [4096];
21127+
21128+ private static Dictionary<string, string> ReadWithComments (StreamLineReader reader)
21129 {
21130 Dictionary<string, string> dict = new Dictionary<string, string> ();
21131- string line;
21132- while ((line = reader.ReadLine ()) != null) {
21133- int split = line.IndexOf ('-');
21134- string target = line.Substring (0, split);
21135- // are there comments ? (many entries don't have any)
21136- if (split == line.Length - 1) {
21137- dict.Add (target, null);
21138- } else {
21139- dict.Add (target, line.Substring (split + 1));
21140- }
21141+ while (!reader.EndOfStream) {
21142+ int length = reader.ReadLine (buffer, 0, buffer.Length);
21143+ int pos = Array.IndexOf (buffer, '-');
21144+ string key = new string (buffer, 0, pos);
21145+ string comment = (buffer [length - 1] == '-') ? null :
21146+ new string (buffer, pos + 1, length - pos - 1);
21147+ dict.Add (key, comment);
21148 }
21149 return dict;
21150 }
21151
21152- private static HashSet<string> Read (TextReader reader)
21153+ private static HashSet<string> Read (StreamLineReader reader)
21154 {
21155 HashSet<string> set = new HashSet<string> ();
21156- string line;
21157- while ((line = reader.ReadLine ()) != null) {
21158- set.Add (line);
21159+ while (!reader.EndOfStream) {
21160+ int length = reader.ReadLine (buffer, 0, buffer.Length);
21161+ set.Add (new string (buffer, 0, length));
21162 }
21163 return set;
21164 }
21165@@ -344,18 +345,18 @@ namespace Gendarme.Rules.Portability {
21166 continue;
21167
21168 // MethodReference.ToString is costly so we do it once for the three checks
21169- string callee = mr.ToString ();
21170+ string callee = mr.GetFullName ();
21171
21172 // calling not implemented method is very likely not to work == High
21173 if ((NotImplemented != null) && NotImplementedInternal.Contains (callee)) {
21174- string message = String.Format (NotImplementedMessage, callee);
21175+ string message = String.Format (CultureInfo.InvariantCulture, NotImplementedMessage, callee);
21176 // confidence is Normal since we can't be sure if MoMA data is up to date
21177 Runner.Report (method, ins, Severity.High, Confidence.Normal, message);
21178 }
21179
21180 // calling missing methods can't work == Critical
21181 if ((Missing != null) && Missing.Contains (callee)) {
21182- string message = String.Format (MissingMessage, callee);
21183+ string message = String.Format (CultureInfo.InvariantCulture, MissingMessage, callee);
21184 Runner.Report (method, ins, Severity.Critical, Confidence.Normal, message);
21185 }
21186
21187@@ -363,7 +364,7 @@ namespace Gendarme.Rules.Portability {
21188 if (ToDo != null) {
21189 string value;
21190 if (ToDo.TryGetValue (callee, out value)) {
21191- string message = String.Format (TodoMessage, callee, value);
21192+ string message = String.Format (CultureInfo.InvariantCulture, TodoMessage, callee, value);
21193 Runner.Report (method, ins, Severity.Medium, Confidence.Normal, message);
21194 }
21195 }
21196diff --git a/gendarme/rules/Gendarme.Rules.Portability/NewLineLiteralRule.cs b/gendarme/rules/Gendarme.Rules.Portability/NewLineLiteralRule.cs
21197index 40345c9..1e3afa3 100644
21198--- a/gendarme/rules/Gendarme.Rules.Portability/NewLineLiteralRule.cs
21199+++ b/gendarme/rules/Gendarme.Rules.Portability/NewLineLiteralRule.cs
21200@@ -27,6 +27,7 @@
21201 //
21202
21203 using System;
21204+using System.Globalization;
21205 using System.Text;
21206
21207 using Mono.Cecil;
21208@@ -115,7 +116,7 @@ namespace Gendarme.Rules.Portability {
21209 else if (c == '\t')
21210 result.Append ("\\t");
21211 else
21212- result.AppendFormat ("\\x").Append (((short) c).ToString ("x"));
21213+ result.Append ("\\x").Append (((short) c).ToString ("x", CultureInfo.InvariantCulture));
21214 }
21215 return result.Append ("\".").ToString ();
21216 }
21217diff --git a/gendarme/rules/Gendarme.Rules.Portability/README.md b/gendarme/rules/Gendarme.Rules.Portability/README.md
21218new file mode 100644
21219index 0000000..ffe7609
21220--- /dev/null
21221+++ b/gendarme/rules/Gendarme.Rules.Portability/README.md
21222@@ -0,0 +1,9 @@
21223+# Gendarme.Rules.Portability Rules
21224+
21225+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Portability(git)]] pages.
21226+
21227+
21228+## Feedback
21229+
21230+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
21231+
21232diff --git a/gendarme/rules/Gendarme.Rules.Portability/Test/Tests.Rules.Portability.csproj b/gendarme/rules/Gendarme.Rules.Portability/Test/Tests.Rules.Portability.csproj
21233index 0787fd3..fcd8220 100755
21234--- a/gendarme/rules/Gendarme.Rules.Portability/Test/Tests.Rules.Portability.csproj
21235+++ b/gendarme/rules/Gendarme.Rules.Portability/Test/Tests.Rules.Portability.csproj
21236@@ -1,5 +1,5 @@
21237 <?xml version="1.0" encoding="utf-8"?>\r
21238-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
21239+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
21240 <PropertyGroup>\r
21241 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
21242 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
21243@@ -12,9 +12,11 @@
21244 <AssemblyName>Tests.Rules.Portability</AssemblyName>\r
21245 <FileUpgradeFlags>\r
21246 </FileUpgradeFlags>\r
21247- <OldToolsVersion>2.0</OldToolsVersion>\r
21248+ <OldToolsVersion>3.5</OldToolsVersion>\r
21249 <UpgradeBackupLocation>\r
21250 </UpgradeBackupLocation>\r
21251+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
21252+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
21253 <PublishUrl>http://localhost/Tests.Rules.Portability/</PublishUrl>\r
21254 <Install>true</Install>\r
21255 <InstallFrom>Web</InstallFrom>\r
21256@@ -27,10 +29,9 @@
21257 <MapFileExtensions>true</MapFileExtensions>\r
21258 <ApplicationRevision>0</ApplicationRevision>\r
21259 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
21260- <IsWebBootstrapper>true</IsWebBootstrapper>\r
21261 <UseApplicationTrust>false</UseApplicationTrust>\r
21262 <BootstrapperEnabled>true</BootstrapperEnabled>\r
21263- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
21264+ <TargetFrameworkProfile />\r
21265 </PropertyGroup>\r
21266 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
21267 <DebugSymbols>true</DebugSymbols>\r
21268@@ -40,6 +41,7 @@
21269 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
21270 <ErrorReport>prompt</ErrorReport>\r
21271 <WarningLevel>4</WarningLevel>\r
21272+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21273 </PropertyGroup>\r
21274 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
21275 <DebugType>pdbonly</DebugType>\r
21276@@ -48,6 +50,7 @@
21277 <DefineConstants>TRACE</DefineConstants>\r
21278 <ErrorReport>prompt</ErrorReport>\r
21279 <WarningLevel>4</WarningLevel>\r
21280+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21281 </PropertyGroup>\r
21282 <ItemGroup>\r
21283 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
21284@@ -90,14 +93,33 @@
21285 </ProjectReference>\r
21286 </ItemGroup>\r
21287 <ItemGroup>\r
21288+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
21289+ <Visible>False</Visible>\r
21290+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
21291+ <Install>false</Install>\r
21292+ </BootstrapperPackage>\r
21293 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
21294 <Visible>False</Visible>\r
21295+ <ProductName>\r
21296+ </ProductName>\r
21297+ <Install>false</Install>\r
21298 </BootstrapperPackage>\r
21299 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
21300 <Visible>False</Visible>\r
21301+ <ProductName>\r
21302+ </ProductName>\r
21303+ <Install>false</Install>\r
21304 </BootstrapperPackage>\r
21305 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
21306 <Visible>False</Visible>\r
21307+ <ProductName>\r
21308+ </ProductName>\r
21309+ <Install>false</Install>\r
21310+ </BootstrapperPackage>\r
21311+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
21312+ <Visible>False</Visible>\r
21313+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
21314+ <Install>false</Install>\r
21315 </BootstrapperPackage>\r
21316 </ItemGroup>\r
21317 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
21318diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/Gendarme.Rules.Security.Cas.csproj b/gendarme/rules/Gendarme.Rules.Security.Cas/Gendarme.Rules.Security.Cas.csproj
21319index 436c7cc..91cc467 100644
21320--- a/gendarme/rules/Gendarme.Rules.Security.Cas/Gendarme.Rules.Security.Cas.csproj
21321+++ b/gendarme/rules/Gendarme.Rules.Security.Cas/Gendarme.Rules.Security.Cas.csproj
21322@@ -1,5 +1,5 @@
21323 <?xml version="1.0" encoding="utf-8"?>\r
21324-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
21325+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
21326 <PropertyGroup>\r
21327 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
21328 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
21329@@ -10,8 +10,28 @@
21330 <AppDesignerFolder>Properties</AppDesignerFolder>\r
21331 <RootNamespace>Gendarme.Rules.Security.Cas</RootNamespace>\r
21332 <AssemblyName>Gendarme.Rules.Security.Cas</AssemblyName>\r
21333- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
21334+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
21335 <FileAlignment>512</FileAlignment>\r
21336+ <FileUpgradeFlags>\r
21337+ </FileUpgradeFlags>\r
21338+ <OldToolsVersion>3.5</OldToolsVersion>\r
21339+ <UpgradeBackupLocation />\r
21340+ <PublishUrl>publish\</PublishUrl>\r
21341+ <Install>true</Install>\r
21342+ <InstallFrom>Disk</InstallFrom>\r
21343+ <UpdateEnabled>false</UpdateEnabled>\r
21344+ <UpdateMode>Foreground</UpdateMode>\r
21345+ <UpdateInterval>7</UpdateInterval>\r
21346+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
21347+ <UpdatePeriodically>false</UpdatePeriodically>\r
21348+ <UpdateRequired>false</UpdateRequired>\r
21349+ <MapFileExtensions>true</MapFileExtensions>\r
21350+ <ApplicationRevision>0</ApplicationRevision>\r
21351+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
21352+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
21353+ <UseApplicationTrust>false</UseApplicationTrust>\r
21354+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
21355+ <TargetFrameworkProfile />\r
21356 </PropertyGroup>\r
21357 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
21358 <DebugSymbols>true</DebugSymbols>\r
21359@@ -24,6 +44,7 @@
21360 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Security.Cas.xml</DocumentationFile>\r
21361 <NoWarn>1591</NoWarn>\r
21362 <WarningsAsErrors>1570</WarningsAsErrors>\r
21363+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21364 </PropertyGroup>\r
21365 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
21366 <DebugType>pdbonly</DebugType>\r
21367@@ -35,6 +56,7 @@
21368 <NoWarn>1591</NoWarn>\r
21369 <WarningsAsErrors>1570</WarningsAsErrors>\r
21370 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Security.Cas.xml</DocumentationFile>\r
21371+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21372 </PropertyGroup>\r
21373 <ItemGroup>\r
21374 <Reference Include="System" />\r
21375@@ -66,6 +88,23 @@
21376 <Name>Gendarme.Framework</Name>\r
21377 </ProjectReference>\r
21378 </ItemGroup>\r
21379+ <ItemGroup>\r
21380+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
21381+ <Visible>False</Visible>\r
21382+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
21383+ <Install>false</Install>\r
21384+ </BootstrapperPackage>\r
21385+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
21386+ <Visible>False</Visible>\r
21387+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
21388+ <Install>true</Install>\r
21389+ </BootstrapperPackage>\r
21390+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
21391+ <Visible>False</Visible>\r
21392+ <ProductName>Windows Installer 3.1</ProductName>\r
21393+ <Install>true</Install>\r
21394+ </BootstrapperPackage>\r
21395+ </ItemGroup>\r
21396 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
21397 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
21398 Other similar extension points exist, see Microsoft.Common.targets.
21399diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/README.md b/gendarme/rules/Gendarme.Rules.Security.Cas/README.md
21400new file mode 100644
21401index 0000000..7fb8880
21402--- /dev/null
21403+++ b/gendarme/rules/Gendarme.Rules.Security.Cas/README.md
21404@@ -0,0 +1,9 @@
21405+# Gendarme.Rules.Security.Cas Rules
21406+
21407+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Security.Cas(git)]] pages.
21408+
21409+
21410+## Feedback
21411+
21412+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
21413+
21414diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/ReviewSuppressUnmanagedCodeSecurityUsageRule.cs b/gendarme/rules/Gendarme.Rules.Security.Cas/ReviewSuppressUnmanagedCodeSecurityUsageRule.cs
21415index 8f0d3de..fc03231 100644
21416--- a/gendarme/rules/Gendarme.Rules.Security.Cas/ReviewSuppressUnmanagedCodeSecurityUsageRule.cs
21417+++ b/gendarme/rules/Gendarme.Rules.Security.Cas/ReviewSuppressUnmanagedCodeSecurityUsageRule.cs
21418@@ -56,8 +56,6 @@ namespace Gendarme.Rules.Security.Cas {
21419 [FxCopCompatibility ("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
21420 public class ReviewSuppressUnmanagedCodeSecurityUsageRule : Rule, ITypeRule, IMethodRule {
21421
21422- private const string SUCS = "System.Security.SuppressUnmanagedCodeSecurityAttribute";
21423-
21424 public override void Initialize (IRunner runner)
21425 {
21426 base.Initialize (runner);
21427@@ -65,8 +63,10 @@ namespace Gendarme.Rules.Security.Cas {
21428 // if the module does not reference [SuppressUnmanagedCodeSecurityAttribute]
21429 // then it's not being used inside it
21430 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
21431- Active = (e.CurrentAssembly.Name.Name == "mscorlib"
21432- || e.CurrentModule.HasTypeReference (SUCS));
21433+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
21434+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
21435+ return tr.IsNamed ("System.Security", "SuppressUnmanagedCodeSecurityAttribute");
21436+ }));
21437 };
21438 }
21439
21440@@ -78,7 +78,7 @@ namespace Gendarme.Rules.Security.Cas {
21441 if (type.IsEnum)
21442 return RuleResult.DoesNotApply;
21443
21444- if (!type.HasAttribute (SUCS))
21445+ if (!type.HasAttribute ("System.Security", "SuppressUnmanagedCodeSecurityAttribute"))
21446 return RuleResult.Success;
21447
21448 Runner.Report (type, Severity.Audit, Confidence.Total);
21449@@ -87,7 +87,7 @@ namespace Gendarme.Rules.Security.Cas {
21450
21451 public RuleResult CheckMethod (MethodDefinition method)
21452 {
21453- if (!method.HasAttribute (SUCS))
21454+ if (!method.HasAttribute ("System.Security", "SuppressUnmanagedCodeSecurityAttribute"))
21455 return RuleResult.Success;
21456
21457 Runner.Report (method, Severity.Audit, Confidence.Total);
21458diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/SecureGetObjectDataOverridesRule.cs b/gendarme/rules/Gendarme.Rules.Security.Cas/SecureGetObjectDataOverridesRule.cs
21459index 481e95e..79831bd 100644
21460--- a/gendarme/rules/Gendarme.Rules.Security.Cas/SecureGetObjectDataOverridesRule.cs
21461+++ b/gendarme/rules/Gendarme.Rules.Security.Cas/SecureGetObjectDataOverridesRule.cs
21462@@ -27,6 +27,7 @@
21463 //
21464
21465 using System;
21466+using System.Globalization;
21467 using System.Security;
21468 using System.Security.Permissions;
21469
21470@@ -87,7 +88,7 @@ namespace Gendarme.Rules.Security.Cas {
21471 public RuleResult CheckType (TypeDefinition type)
21472 {
21473 // rule applies only to types that implements ISerializable
21474- if (!type.Implements ("System.Runtime.Serialization.ISerializable"))
21475+ if (!type.Implements ("System.Runtime.Serialization", "ISerializable"))
21476 return RuleResult.DoesNotApply;
21477
21478 MethodDefinition method = type.GetMethod (MethodSignatures.GetObjectData);
21479@@ -112,7 +113,8 @@ namespace Gendarme.Rules.Security.Cas {
21480 case Mono.Cecil.SecurityAction.NonCasLinkDemand:
21481 demand = true;
21482 if (!RuleSet.IsSubsetOf (declsec.ToPermissionSet ())) {
21483- string message = String.Format ("{0} is not a subset of {1} permission set",
21484+ string message = String.Format (CultureInfo.InvariantCulture,
21485+ "{0} is not a subset of {1} permission set",
21486 "SerializationFormatter", declsec.Action);
21487 Runner.Report (method, Severity.High, Confidence.Total, message);
21488 }
21489diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/SecurityDeclarationRocks.cs b/gendarme/rules/Gendarme.Rules.Security.Cas/SecurityDeclarationRocks.cs
21490index ee136e9..ba56671 100644
21491--- a/gendarme/rules/Gendarme.Rules.Security.Cas/SecurityDeclarationRocks.cs
21492+++ b/gendarme/rules/Gendarme.Rules.Security.Cas/SecurityDeclarationRocks.cs
21493@@ -31,6 +31,7 @@ using System.Security;
21494 using SSP = System.Security.Permissions;
21495
21496 using Mono.Cecil;
21497+using Gendarme.Framework.Rocks;
21498
21499 namespace Gendarme.Rules.Security.Cas {
21500
21501diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/Test/Tests.Rules.Security.Cas.csproj b/gendarme/rules/Gendarme.Rules.Security.Cas/Test/Tests.Rules.Security.Cas.csproj
21502index b9cd34a..8d2eec5 100644
21503--- a/gendarme/rules/Gendarme.Rules.Security.Cas/Test/Tests.Rules.Security.Cas.csproj
21504+++ b/gendarme/rules/Gendarme.Rules.Security.Cas/Test/Tests.Rules.Security.Cas.csproj
21505@@ -1,5 +1,5 @@
21506 <?xml version="1.0" encoding="utf-8"?>\r
21507-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
21508+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
21509 <PropertyGroup>\r
21510 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
21511 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
21512@@ -10,8 +10,28 @@
21513 <AppDesignerFolder>Properties</AppDesignerFolder>\r
21514 <RootNamespace>Tests.Rules.Security.Cas</RootNamespace>\r
21515 <AssemblyName>Tests.Rules.Security.Cas</AssemblyName>\r
21516- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
21517+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
21518 <FileAlignment>512</FileAlignment>\r
21519+ <FileUpgradeFlags>\r
21520+ </FileUpgradeFlags>\r
21521+ <OldToolsVersion>3.5</OldToolsVersion>\r
21522+ <UpgradeBackupLocation />\r
21523+ <PublishUrl>publish\</PublishUrl>\r
21524+ <Install>true</Install>\r
21525+ <InstallFrom>Disk</InstallFrom>\r
21526+ <UpdateEnabled>false</UpdateEnabled>\r
21527+ <UpdateMode>Foreground</UpdateMode>\r
21528+ <UpdateInterval>7</UpdateInterval>\r
21529+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
21530+ <UpdatePeriodically>false</UpdatePeriodically>\r
21531+ <UpdateRequired>false</UpdateRequired>\r
21532+ <MapFileExtensions>true</MapFileExtensions>\r
21533+ <ApplicationRevision>0</ApplicationRevision>\r
21534+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
21535+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
21536+ <UseApplicationTrust>false</UseApplicationTrust>\r
21537+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
21538+ <TargetFrameworkProfile />\r
21539 </PropertyGroup>\r
21540 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
21541 <DebugSymbols>true</DebugSymbols>\r
21542@@ -21,6 +41,7 @@
21543 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
21544 <ErrorReport>prompt</ErrorReport>\r
21545 <WarningLevel>4</WarningLevel>\r
21546+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21547 </PropertyGroup>\r
21548 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
21549 <DebugType>pdbonly</DebugType>\r
21550@@ -29,6 +50,7 @@
21551 <DefineConstants>TRACE</DefineConstants>\r
21552 <ErrorReport>prompt</ErrorReport>\r
21553 <WarningLevel>4</WarningLevel>\r
21554+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21555 </PropertyGroup>\r
21556 <ItemGroup>\r
21557 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
21558@@ -72,6 +94,23 @@
21559 <ItemGroup>\r
21560 <Folder Include="Properties\" />\r
21561 </ItemGroup>\r
21562+ <ItemGroup>\r
21563+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
21564+ <Visible>False</Visible>\r
21565+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
21566+ <Install>false</Install>\r
21567+ </BootstrapperPackage>\r
21568+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
21569+ <Visible>False</Visible>\r
21570+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
21571+ <Install>true</Install>\r
21572+ </BootstrapperPackage>\r
21573+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
21574+ <Visible>False</Visible>\r
21575+ <ProductName>Windows Installer 3.1</ProductName>\r
21576+ <Install>true</Install>\r
21577+ </BootstrapperPackage>\r
21578+ </ItemGroup>\r
21579 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
21580 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
21581 Other similar extension points exist, see Microsoft.Common.targets.
21582diff --git a/gendarme/rules/Gendarme.Rules.Security/DoNotShortCircuitCertificateCheckRule.cs b/gendarme/rules/Gendarme.Rules.Security/DoNotShortCircuitCertificateCheckRule.cs
21583index 31f51cf..3323b85 100644
21584--- a/gendarme/rules/Gendarme.Rules.Security/DoNotShortCircuitCertificateCheckRule.cs
21585+++ b/gendarme/rules/Gendarme.Rules.Security/DoNotShortCircuitCertificateCheckRule.cs
21586@@ -122,8 +122,11 @@ namespace Gendarme.Rules.Security {
21587 // if the module does not reference System.Math then
21588 // none of its method is being called with constants
21589 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
21590- Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
21591- e.CurrentModule.HasTypeReference ("System.Net.ICertificatePolicy");
21592+ Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
21593+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
21594+ return tr.IsNamed ("System.Net", "ICertificatePolicy");
21595+ })
21596+ );
21597 };
21598 }
21599
21600@@ -138,11 +141,11 @@ namespace Gendarme.Rules.Security {
21601 if (pd == null)
21602 continue;
21603
21604- switch (pd.GetSequence ()) {
21605- case 2:
21606- case 4:
21607- return RuleResult.Success;
21608+ switch (pd.Index) {
21609+ case 1:
21610 case 3:
21611+ return RuleResult.Success;
21612+ case 2:
21613 if (third)
21614 return RuleResult.Success;
21615 break;
21616@@ -160,7 +163,7 @@ namespace Gendarme.Rules.Security {
21617 // since ICertificatePolicy is an interface we need to check its name
21618 string name = method.Name;
21619 if (name == "CheckValidationResult") {
21620- if (!method.DeclaringType.Implements ("System.Net.ICertificatePolicy"))
21621+ if (!method.DeclaringType.Implements ("System.Net", "ICertificatePolicy"))
21622 return RuleResult.Success;
21623 } else if (name != "System.Net.ICertificatePolicy.CheckValidationResult")
21624 return RuleResult.Success;
21625@@ -187,7 +190,7 @@ namespace Gendarme.Rules.Security {
21626
21627 IList<ParameterDefinition> pdc = method.Parameters;
21628 int count = pdc.Count;
21629- if ((count != 4) || (method.ReturnType.FullName != "System.Boolean"))
21630+ if ((count != 4) || !method.ReturnType.IsNamed ("System", "Boolean"))
21631 return RuleResult.DoesNotApply;
21632
21633 // this method could be a candidate for both policy or callback
21634@@ -195,10 +198,10 @@ namespace Gendarme.Rules.Security {
21635 bool callback = true;
21636 // if all the parameters match
21637 for (int i = 0; i < count; i++) {
21638- string name = pdc [i].ParameterType.FullName;
21639- if (policy && (name != CertificatePolicyParameters [i]))
21640+ TypeReference ptype = pdc [i].ParameterType;
21641+ if (policy && !ptype.IsNamed (CertificatePolicyParameters [i]))
21642 policy = false;
21643- if (callback && (name != RemoteCertificateValidationParameters [i]))
21644+ if (callback && !ptype.IsNamed (RemoteCertificateValidationParameters [i]))
21645 callback = false;
21646 }
21647
21648diff --git a/gendarme/rules/Gendarme.Rules.Security/Gendarme.Rules.Security.csproj b/gendarme/rules/Gendarme.Rules.Security/Gendarme.Rules.Security.csproj
21649index 7cec633..62fc565 100755
21650--- a/gendarme/rules/Gendarme.Rules.Security/Gendarme.Rules.Security.csproj
21651+++ b/gendarme/rules/Gendarme.Rules.Security/Gendarme.Rules.Security.csproj
21652@@ -1,5 +1,5 @@
21653 <?xml version="1.0" encoding="utf-8"?>\r
21654-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
21655+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
21656 <PropertyGroup>\r
21657 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
21658 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
21659@@ -12,9 +12,11 @@
21660 <AssemblyName>Gendarme.Rules.Security</AssemblyName>\r
21661 <FileUpgradeFlags>\r
21662 </FileUpgradeFlags>\r
21663- <OldToolsVersion>2.0</OldToolsVersion>\r
21664+ <OldToolsVersion>3.5</OldToolsVersion>\r
21665 <UpgradeBackupLocation>\r
21666 </UpgradeBackupLocation>\r
21667+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
21668+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
21669 <PublishUrl>http://localhost/Gendarme.Rules.Security/</PublishUrl>\r
21670 <Install>true</Install>\r
21671 <InstallFrom>Web</InstallFrom>\r
21672@@ -27,10 +29,9 @@
21673 <MapFileExtensions>true</MapFileExtensions>\r
21674 <ApplicationRevision>0</ApplicationRevision>\r
21675 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
21676- <IsWebBootstrapper>true</IsWebBootstrapper>\r
21677 <UseApplicationTrust>false</UseApplicationTrust>\r
21678 <BootstrapperEnabled>true</BootstrapperEnabled>\r
21679- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
21680+ <TargetFrameworkProfile />\r
21681 </PropertyGroup>\r
21682 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
21683 <DebugSymbols>true</DebugSymbols>\r
21684@@ -43,6 +44,7 @@
21685 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Security.xml</DocumentationFile>\r
21686 <NoWarn>1591</NoWarn>\r
21687 <WarningsAsErrors>1570</WarningsAsErrors>\r
21688+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21689 </PropertyGroup>\r
21690 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
21691 <DebugType>pdbonly</DebugType>\r
21692@@ -54,6 +56,7 @@
21693 <NoWarn>1591</NoWarn>\r
21694 <WarningsAsErrors>1570</WarningsAsErrors>\r
21695 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Security.xml</DocumentationFile>\r
21696+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21697 </PropertyGroup>\r
21698 <ItemGroup>\r
21699 <Reference Include="System" />\r
21700@@ -84,14 +87,33 @@
21701 <None Include="ChangeLog" />\r
21702 </ItemGroup>\r
21703 <ItemGroup>\r
21704+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
21705+ <Visible>False</Visible>\r
21706+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
21707+ <Install>false</Install>\r
21708+ </BootstrapperPackage>\r
21709 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
21710 <Visible>False</Visible>\r
21711+ <ProductName>\r
21712+ </ProductName>\r
21713+ <Install>false</Install>\r
21714 </BootstrapperPackage>\r
21715 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
21716 <Visible>False</Visible>\r
21717+ <ProductName>\r
21718+ </ProductName>\r
21719+ <Install>false</Install>\r
21720 </BootstrapperPackage>\r
21721 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
21722 <Visible>False</Visible>\r
21723+ <ProductName>\r
21724+ </ProductName>\r
21725+ <Install>false</Install>\r
21726+ </BootstrapperPackage>\r
21727+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
21728+ <Visible>False</Visible>\r
21729+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
21730+ <Install>false</Install>\r
21731 </BootstrapperPackage>\r
21732 </ItemGroup>\r
21733 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
21734diff --git a/gendarme/rules/Gendarme.Rules.Security/README.md b/gendarme/rules/Gendarme.Rules.Security/README.md
21735new file mode 100644
21736index 0000000..d0b7430
21737--- /dev/null
21738+++ b/gendarme/rules/Gendarme.Rules.Security/README.md
21739@@ -0,0 +1,9 @@
21740+# Gendarme.Rules.Security Rules
21741+
21742+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Security(git)]] pages.
21743+
21744+
21745+## Feedback
21746+
21747+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
21748+
21749diff --git a/gendarme/rules/Gendarme.Rules.Security/Test/Tests.Rules.Security.csproj b/gendarme/rules/Gendarme.Rules.Security/Test/Tests.Rules.Security.csproj
21750index ce04b1c..2568557 100755
21751--- a/gendarme/rules/Gendarme.Rules.Security/Test/Tests.Rules.Security.csproj
21752+++ b/gendarme/rules/Gendarme.Rules.Security/Test/Tests.Rules.Security.csproj
21753@@ -1,5 +1,5 @@
21754 <?xml version="1.0" encoding="utf-8"?>\r
21755-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
21756+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
21757 <PropertyGroup>\r
21758 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
21759 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
21760@@ -12,9 +12,11 @@
21761 <AssemblyName>Tests.Rules.Security</AssemblyName>\r
21762 <FileUpgradeFlags>\r
21763 </FileUpgradeFlags>\r
21764- <OldToolsVersion>2.0</OldToolsVersion>\r
21765+ <OldToolsVersion>3.5</OldToolsVersion>\r
21766 <UpgradeBackupLocation>\r
21767 </UpgradeBackupLocation>\r
21768+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
21769+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
21770 <PublishUrl>http://localhost/Tests.Rules.Security/</PublishUrl>\r
21771 <Install>true</Install>\r
21772 <InstallFrom>Web</InstallFrom>\r
21773@@ -27,10 +29,9 @@
21774 <MapFileExtensions>true</MapFileExtensions>\r
21775 <ApplicationRevision>0</ApplicationRevision>\r
21776 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
21777- <IsWebBootstrapper>true</IsWebBootstrapper>\r
21778 <UseApplicationTrust>false</UseApplicationTrust>\r
21779 <BootstrapperEnabled>true</BootstrapperEnabled>\r
21780- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
21781+ <TargetFrameworkProfile />\r
21782 </PropertyGroup>\r
21783 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
21784 <DebugSymbols>true</DebugSymbols>\r
21785@@ -40,6 +41,7 @@
21786 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
21787 <ErrorReport>prompt</ErrorReport>\r
21788 <WarningLevel>4</WarningLevel>\r
21789+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21790 </PropertyGroup>\r
21791 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
21792 <DebugType>pdbonly</DebugType>\r
21793@@ -48,6 +50,7 @@
21794 <DefineConstants>TRACE</DefineConstants>\r
21795 <ErrorReport>prompt</ErrorReport>\r
21796 <WarningLevel>4</WarningLevel>\r
21797+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21798 </PropertyGroup>\r
21799 <ItemGroup>\r
21800 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
21801@@ -86,14 +89,33 @@
21802 </ProjectReference>\r
21803 </ItemGroup>\r
21804 <ItemGroup>\r
21805+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
21806+ <Visible>False</Visible>\r
21807+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
21808+ <Install>false</Install>\r
21809+ </BootstrapperPackage>\r
21810 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
21811 <Visible>False</Visible>\r
21812+ <ProductName>\r
21813+ </ProductName>\r
21814+ <Install>false</Install>\r
21815 </BootstrapperPackage>\r
21816 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
21817 <Visible>False</Visible>\r
21818+ <ProductName>\r
21819+ </ProductName>\r
21820+ <Install>false</Install>\r
21821 </BootstrapperPackage>\r
21822 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
21823 <Visible>False</Visible>\r
21824+ <ProductName>\r
21825+ </ProductName>\r
21826+ <Install>false</Install>\r
21827+ </BootstrapperPackage>\r
21828+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
21829+ <Visible>False</Visible>\r
21830+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
21831+ <Install>false</Install>\r
21832 </BootstrapperPackage>\r
21833 </ItemGroup>\r
21834 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
21835diff --git a/gendarme/rules/Gendarme.Rules.Serialization/CallBaseMethodsOnISerializableTypesRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/CallBaseMethodsOnISerializableTypesRule.cs
21836index 640b093..bd7eb7c 100644
21837--- a/gendarme/rules/Gendarme.Rules.Serialization/CallBaseMethodsOnISerializableTypesRule.cs
21838+++ b/gendarme/rules/Gendarme.Rules.Serialization/CallBaseMethodsOnISerializableTypesRule.cs
21839@@ -102,9 +102,9 @@ namespace Gendarme.Rules.Serialization {
21840 private static bool InheritsFromISerializableImplementation (TypeDefinition type)
21841 {
21842 TypeDefinition current = type.BaseType != null ? type.BaseType.Resolve () : null;
21843- if (current == null || current.FullName == "System.Object")
21844+ if (current == null || current.IsNamed ("System", "Object"))
21845 return false;
21846- if (current.IsSerializable && current.Implements ("System.Runtime.Serialization.ISerializable"))
21847+ if (current.IsSerializable && current.Implements ("System.Runtime.Serialization", "ISerializable"))
21848 return true;
21849
21850 return InheritsFromISerializableImplementation (current);
21851@@ -124,7 +124,8 @@ namespace Gendarme.Rules.Serialization {
21852 continue;
21853
21854 MethodReference operand = (MethodReference) instruction.Operand;
21855- if (methodSignature.Matches (operand) && type.Inherits (operand.DeclaringType.FullName))
21856+ TypeReference tr = operand.DeclaringType;
21857+ if (methodSignature.Matches (operand) && type.Inherits (tr.Namespace, tr.Name))
21858 return;
21859 }
21860 }
21861diff --git a/gendarme/rules/Gendarme.Rules.Serialization/DeserializeOptionalFieldRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/DeserializeOptionalFieldRule.cs
21862index 217384b..5fdbd75 100644
21863--- a/gendarme/rules/Gendarme.Rules.Serialization/DeserializeOptionalFieldRule.cs
21864+++ b/gendarme/rules/Gendarme.Rules.Serialization/DeserializeOptionalFieldRule.cs
21865@@ -26,6 +26,7 @@
21866
21867 using System;
21868 using System.Collections.Generic;
21869+using System.Globalization;
21870
21871 using Mono.Cecil;
21872
21873@@ -85,10 +86,6 @@ namespace Gendarme.Rules.Serialization {
21874 private const string MessageOptional = "Optional fields '{0}' is not deserialized.";
21875 private const string MessageSerializable = "Optional fields '{0}' in non-serializable type.";
21876
21877- private const string OptionalFieldAttribute = "System.Runtime.Serialization.OptionalFieldAttribute";
21878- private const string OnDeserializedAttribute = "System.Runtime.Serialization.OnDeserializedAttribute";
21879- private const string OnDeserializingAttribute = "System.Runtime.Serialization.OnDeserializingAttribute";
21880-
21881 public override void Initialize (IRunner runner)
21882 {
21883 base.Initialize (runner);
21884@@ -103,7 +100,10 @@ namespace Gendarme.Rules.Serialization {
21885 // if the module does not have a reference to System.Runtime.Serialization.OptionalFieldAttribute
21886 // then nothing will be reported by this rule
21887 (e.CurrentAssembly.Name.Name == "mscorlib" ||
21888- e.CurrentModule.HasTypeReference (OptionalFieldAttribute));
21889+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
21890+ return tr.IsNamed ("System.Runtime.Serialization", "OptionalFieldAttribute");
21891+ })
21892+ );
21893 };
21894 }
21895
21896@@ -121,9 +121,9 @@ namespace Gendarme.Rules.Serialization {
21897 if (method.IsConstructor || !method.HasCustomAttributes)
21898 continue;
21899
21900- if (method.HasAttribute (OnDeserializedAttribute))
21901+ if (method.HasAttribute ("System.Runtime.Serialization", "OnDeserializedAttribute"))
21902 deserialized_candidate = true;
21903- if (method.HasAttribute (OnDeserializingAttribute))
21904+ if (method.HasAttribute ("System.Runtime.Serialization", "OnDeserializingAttribute"))
21905 deserializing_candidate = true;
21906
21907 if (deserialized_candidate && deserializing_candidate)
21908@@ -133,19 +133,17 @@ namespace Gendarme.Rules.Serialization {
21909
21910 // check if we found some optional fields, if none then it's all ok
21911 foreach (FieldDefinition field in type.Fields) {
21912- if (!field.HasCustomAttributes)
21913- continue;
21914- if (field.CustomAttributes.ContainsType (OptionalFieldAttribute)) {
21915+ if (field.HasAttribute ("System.Runtime.Serialization", "OptionalFieldAttribute")) {
21916 if (type.IsSerializable) {
21917 // report if we didn't find a deserialization method
21918 if (!deserialized_candidate || !deserializing_candidate) {
21919 // Medium since it's possible that the optional fields don't need to be re-computed
21920- string s = String.Format (MessageOptional, field.Name);
21921+ string s = String.Format (CultureInfo.InvariantCulture, MessageOptional, field.Name);
21922 Runner.Report (field, Severity.Medium, Confidence.High, s);
21923 }
21924 } else {
21925 // [OptionalField] without [Serializable] is a bigger problem
21926- string s = String.Format (MessageSerializable, field.Name);
21927+ string s = String.Format (CultureInfo.InvariantCulture, MessageSerializable, field.Name);
21928 Runner.Report (field, Severity.Critical, Confidence.High, s);
21929 }
21930 }
21931diff --git a/gendarme/rules/Gendarme.Rules.Serialization/Gendarme.Rules.Serialization.csproj b/gendarme/rules/Gendarme.Rules.Serialization/Gendarme.Rules.Serialization.csproj
21932index 06d1196..c8a0661 100755
21933--- a/gendarme/rules/Gendarme.Rules.Serialization/Gendarme.Rules.Serialization.csproj
21934+++ b/gendarme/rules/Gendarme.Rules.Serialization/Gendarme.Rules.Serialization.csproj
21935@@ -1,5 +1,5 @@
21936 <?xml version="1.0" encoding="utf-8"?>\r
21937-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
21938+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
21939 <PropertyGroup>\r
21940 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
21941 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
21942@@ -10,8 +10,28 @@
21943 <AppDesignerFolder>Properties</AppDesignerFolder>\r
21944 <RootNamespace>Gendarme.Rules.Serialization</RootNamespace>\r
21945 <AssemblyName>Gendarme.Rules.Serialization</AssemblyName>\r
21946- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
21947+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
21948 <FileAlignment>512</FileAlignment>\r
21949+ <FileUpgradeFlags>\r
21950+ </FileUpgradeFlags>\r
21951+ <OldToolsVersion>3.5</OldToolsVersion>\r
21952+ <UpgradeBackupLocation />\r
21953+ <PublishUrl>publish\</PublishUrl>\r
21954+ <Install>true</Install>\r
21955+ <InstallFrom>Disk</InstallFrom>\r
21956+ <UpdateEnabled>false</UpdateEnabled>\r
21957+ <UpdateMode>Foreground</UpdateMode>\r
21958+ <UpdateInterval>7</UpdateInterval>\r
21959+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
21960+ <UpdatePeriodically>false</UpdatePeriodically>\r
21961+ <UpdateRequired>false</UpdateRequired>\r
21962+ <MapFileExtensions>true</MapFileExtensions>\r
21963+ <ApplicationRevision>0</ApplicationRevision>\r
21964+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
21965+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
21966+ <UseApplicationTrust>false</UseApplicationTrust>\r
21967+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
21968+ <TargetFrameworkProfile />\r
21969 </PropertyGroup>\r
21970 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
21971 <DebugSymbols>true</DebugSymbols>\r
21972@@ -24,6 +44,7 @@
21973 <NoWarn>1591</NoWarn>\r
21974 <WarningsAsErrors>1570</WarningsAsErrors>\r
21975 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Serialization.xml</DocumentationFile>\r
21976+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21977 </PropertyGroup>\r
21978 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
21979 <DebugType>pdbonly</DebugType>\r
21980@@ -35,6 +56,7 @@
21981 <NoWarn>1591</NoWarn>\r
21982 <WarningsAsErrors>1570</WarningsAsErrors>\r
21983 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Serialization.xml</DocumentationFile>\r
21984+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
21985 </PropertyGroup>\r
21986 <ItemGroup>\r
21987 <Reference Include="System" />\r
21988@@ -65,6 +87,23 @@
21989 <Name>Gendarme.Framework</Name>\r
21990 </ProjectReference>\r
21991 </ItemGroup>\r
21992+ <ItemGroup>\r
21993+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
21994+ <Visible>False</Visible>\r
21995+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
21996+ <Install>false</Install>\r
21997+ </BootstrapperPackage>\r
21998+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
21999+ <Visible>False</Visible>\r
22000+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
22001+ <Install>true</Install>\r
22002+ </BootstrapperPackage>\r
22003+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
22004+ <Visible>False</Visible>\r
22005+ <ProductName>Windows Installer 3.1</ProductName>\r
22006+ <Install>true</Install>\r
22007+ </BootstrapperPackage>\r
22008+ </ItemGroup>\r
22009 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
22010 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
22011 Other similar extension points exist, see Microsoft.Common.targets.\r
22012diff --git a/gendarme/rules/Gendarme.Rules.Serialization/ImplementISerializableCorrectlyRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/ImplementISerializableCorrectlyRule.cs
22013index 553853b..2059795 100644
22014--- a/gendarme/rules/Gendarme.Rules.Serialization/ImplementISerializableCorrectlyRule.cs
22015+++ b/gendarme/rules/Gendarme.Rules.Serialization/ImplementISerializableCorrectlyRule.cs
22016@@ -122,12 +122,12 @@ namespace Gendarme.Rules.Serialization {
22017
22018 static private FieldDefinition CheckProperty (MethodDefinition getter)
22019 {
22020- string return_type = getter.ReturnType.FullName;
22021+ TypeReference return_type = getter.ReturnType;
22022 foreach (Instruction ins in getter.Body.Instructions) {
22023 if (ins.OpCode.OperandType != OperandType.InlineField)
22024 continue;
22025 FieldDefinition field = (ins.Operand as FieldDefinition);
22026- if ((field != null) && (field.FieldType.FullName == return_type))
22027+ if ((field != null) && field.FieldType.IsNamed (return_type.Namespace, return_type.Name))
22028 return field;
22029 }
22030 return null;
22031@@ -143,7 +143,7 @@ namespace Gendarme.Rules.Serialization {
22032 if (!mr.HasParameters || (mr.Name != "AddValue") || (mr.Parameters.Count < 2))
22033 continue;
22034 // type is sealed so this check is ok
22035- if (mr.DeclaringType.FullName != "System.Runtime.Serialization.SerializationInfo")
22036+ if (!mr.DeclaringType.IsNamed ("System.Runtime.Serialization", "SerializationInfo"))
22037 continue;
22038
22039 // look at the second parameter, which should be (or return) the field
22040@@ -189,7 +189,7 @@ namespace Gendarme.Rules.Serialization {
22041
22042 public RuleResult CheckType (TypeDefinition type)
22043 {
22044- if (!type.IsSerializable || !type.Implements ("System.Runtime.Serialization.ISerializable"))
22045+ if (!type.IsSerializable || !type.Implements ("System.Runtime.Serialization", "ISerializable"))
22046 return RuleResult.DoesNotApply;
22047
22048 MethodDefinition getObjectData = type.GetMethod (MethodSignatures.GetObjectData);
22049diff --git a/gendarme/rules/Gendarme.Rules.Serialization/MarkAllNonSerializableFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/MarkAllNonSerializableFieldsRule.cs
22050index 75d3a89..bfa7bf1 100644
22051--- a/gendarme/rules/Gendarme.Rules.Serialization/MarkAllNonSerializableFieldsRule.cs
22052+++ b/gendarme/rules/Gendarme.Rules.Serialization/MarkAllNonSerializableFieldsRule.cs
22053@@ -27,6 +27,7 @@
22054 //
22055
22056 using System;
22057+using System.Globalization;
22058 using Gendarme.Framework;
22059 using Gendarme.Framework.Rocks;
22060 using Mono.Cecil;
22061@@ -75,7 +76,7 @@ namespace Gendarme.Rules.Serialization {
22062 public RuleResult CheckType (TypeDefinition type)
22063 {
22064 // if type is not serializable or has not any fields or does not implements a custom serialization
22065- if (!type.IsSerializable || !type.HasFields || type.Implements ("System.Runtime.Serialization.ISerializable"))
22066+ if (!type.IsSerializable || !type.HasFields || type.Implements ("System.Runtime.Serialization", "ISerializable"))
22067 return RuleResult.DoesNotApply;
22068
22069 foreach (FieldDefinition field in type.Fields) {
22070@@ -85,11 +86,17 @@ namespace Gendarme.Rules.Serialization {
22071 continue;
22072
22073 if (fieldType.IsInterface) {
22074- Runner.Report (field, Severity.Critical, Confidence.Low, String.Format ("Serialization of interface {0} as field {1} unknown until runtime", fieldType, field.Name));
22075+ string msg = String.Format (CultureInfo.InvariantCulture,
22076+ "Serialization of interface {0} as field {1} unknown until runtime",
22077+ fieldType, field.Name);
22078+ Runner.Report (field, Severity.Critical, Confidence.Low, msg);
22079 continue;
22080 }
22081- if (!fieldType.IsEnum && !fieldType.IsSerializable)
22082- Runner.Report (field, Severity.Critical, Confidence.High, String.Format ("The field {0} isn't serializable.", field.Name));
22083+ if (!fieldType.IsEnum && !fieldType.IsSerializable) {
22084+ string msg = String.Format (CultureInfo.InvariantCulture,
22085+ "The field {0} isn't serializable.", field.Name);
22086+ Runner.Report (field, Severity.Critical, Confidence.High, msg);
22087+ }
22088 }
22089 }
22090
22091diff --git a/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializableAttributeOnISerializableTypeRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializableAttributeOnISerializableTypeRule.cs
22092index 24f0b00..74be9db 100644
22093--- a/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializableAttributeOnISerializableTypeRule.cs
22094+++ b/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializableAttributeOnISerializableTypeRule.cs
22095@@ -64,8 +64,6 @@ namespace Gendarme.Rules.Serialization {
22096 [FxCopCompatibility ("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable")]
22097 public class MissingSerializableAttributeOnISerializableTypeRule : Rule, ITypeRule {
22098
22099- private const string ISerializable = "System.Runtime.Serialization.ISerializable";
22100-
22101 public RuleResult CheckType (TypeDefinition type)
22102 {
22103 // rule does not apply to interface (since [Serializable] is not applicable to interfaces)
22104@@ -74,11 +72,11 @@ namespace Gendarme.Rules.Serialization {
22105 return RuleResult.DoesNotApply;
22106
22107 // rule does not apply if the type does not implements ISerializable
22108- if (!type.Implements (ISerializable))
22109+ if (!type.Implements ("System.Runtime.Serialization", "ISerializable"))
22110 return RuleResult.DoesNotApply;
22111
22112 // rule applies only if base type is serializable
22113- if (type.BaseType.FullName != "System.Object") {
22114+ if (!type.BaseType.IsNamed ("System", "Object")) {
22115 TypeDefinition base_type = type.BaseType.Resolve ();
22116 // in doubt don't report
22117 if ((base_type == null) || !base_type.IsSerializable)
22118diff --git a/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializationConstructorRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializationConstructorRule.cs
22119index 36115b0..e80ffe7 100644
22120--- a/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializationConstructorRule.cs
22121+++ b/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializationConstructorRule.cs
22122@@ -89,9 +89,6 @@ namespace Gendarme.Rules.Serialization {
22123 [FxCopCompatibility ("Microsoft.Usage", "CA2229:ImplementSerializationConstructors")]
22124 public class MissingSerializationConstructorRule : Rule, ITypeRule {
22125
22126- // non-localizable
22127- private const string ISerializable = "System.Runtime.Serialization.ISerializable";
22128-
22129 // localizable
22130 private const string NoSerializationCtorText = "The required constructor for ISerializable is not present in this type.";
22131 private const string CtorSealedTypeText = "The serialization constructor should be private since this type is sealed.";
22132@@ -100,7 +97,7 @@ namespace Gendarme.Rules.Serialization {
22133 public RuleResult CheckType (TypeDefinition type)
22134 {
22135 // rule does not apply to interfaces, delegates or types that does not implement ISerializable
22136- if (type.IsInterface || type.IsDelegate () || !type.Implements (ISerializable))
22137+ if (type.IsInterface || type.IsDelegate () || !type.Implements ("System.Runtime.Serialization", "ISerializable"))
22138 return RuleResult.DoesNotApply;
22139
22140 // rule applies, only Success or Failure from the point on
22141diff --git a/gendarme/rules/Gendarme.Rules.Serialization/README.md b/gendarme/rules/Gendarme.Rules.Serialization/README.md
22142new file mode 100644
22143index 0000000..e236c99
22144--- /dev/null
22145+++ b/gendarme/rules/Gendarme.Rules.Serialization/README.md
22146@@ -0,0 +1,9 @@
22147+# Gendarme.Rules.Serialization Rules
22148+
22149+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Serialization(git)]] pages.
22150+
22151+
22152+## Feedback
22153+
22154+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
22155+
22156diff --git a/gendarme/rules/Gendarme.Rules.Serialization/Test/Tests.Rules.Serialization.csproj b/gendarme/rules/Gendarme.Rules.Serialization/Test/Tests.Rules.Serialization.csproj
22157index 5a92892..090910b 100755
22158--- a/gendarme/rules/Gendarme.Rules.Serialization/Test/Tests.Rules.Serialization.csproj
22159+++ b/gendarme/rules/Gendarme.Rules.Serialization/Test/Tests.Rules.Serialization.csproj
22160@@ -1,5 +1,5 @@
22161 <?xml version="1.0" encoding="utf-8"?>\r
22162-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
22163+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
22164 <PropertyGroup>\r
22165 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
22166 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
22167@@ -10,8 +10,28 @@
22168 <AppDesignerFolder>Properties</AppDesignerFolder>\r
22169 <RootNamespace>Tests.Rules.Serialization</RootNamespace>\r
22170 <AssemblyName>Tests.Rules.Serialization</AssemblyName>\r
22171- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
22172+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
22173 <FileAlignment>512</FileAlignment>\r
22174+ <FileUpgradeFlags>\r
22175+ </FileUpgradeFlags>\r
22176+ <OldToolsVersion>3.5</OldToolsVersion>\r
22177+ <UpgradeBackupLocation />\r
22178+ <PublishUrl>publish\</PublishUrl>\r
22179+ <Install>true</Install>\r
22180+ <InstallFrom>Disk</InstallFrom>\r
22181+ <UpdateEnabled>false</UpdateEnabled>\r
22182+ <UpdateMode>Foreground</UpdateMode>\r
22183+ <UpdateInterval>7</UpdateInterval>\r
22184+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
22185+ <UpdatePeriodically>false</UpdatePeriodically>\r
22186+ <UpdateRequired>false</UpdateRequired>\r
22187+ <MapFileExtensions>true</MapFileExtensions>\r
22188+ <ApplicationRevision>0</ApplicationRevision>\r
22189+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
22190+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
22191+ <UseApplicationTrust>false</UseApplicationTrust>\r
22192+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
22193+ <TargetFrameworkProfile />\r
22194 </PropertyGroup>\r
22195 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
22196 <DebugSymbols>true</DebugSymbols>\r
22197@@ -21,6 +41,7 @@
22198 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
22199 <ErrorReport>prompt</ErrorReport>\r
22200 <WarningLevel>4</WarningLevel>\r
22201+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
22202 </PropertyGroup>\r
22203 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
22204 <DebugType>pdbonly</DebugType>\r
22205@@ -29,6 +50,7 @@
22206 <DefineConstants>TRACE</DefineConstants>\r
22207 <ErrorReport>prompt</ErrorReport>\r
22208 <WarningLevel>4</WarningLevel>\r
22209+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
22210 </PropertyGroup>\r
22211 <ItemGroup>\r
22212 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
22213@@ -70,6 +92,23 @@
22214 <ItemGroup>\r
22215 <Folder Include="Properties\" />\r
22216 </ItemGroup>\r
22217+ <ItemGroup>\r
22218+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
22219+ <Visible>False</Visible>\r
22220+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
22221+ <Install>false</Install>\r
22222+ </BootstrapperPackage>\r
22223+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
22224+ <Visible>False</Visible>\r
22225+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
22226+ <Install>true</Install>\r
22227+ </BootstrapperPackage>\r
22228+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
22229+ <Visible>False</Visible>\r
22230+ <ProductName>Windows Installer 3.1</ProductName>\r
22231+ <Install>true</Install>\r
22232+ </BootstrapperPackage>\r
22233+ </ItemGroup>\r
22234 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
22235 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
22236 Other similar extension points exist, see Microsoft.Common.targets.\r
22237diff --git a/gendarme/rules/Gendarme.Rules.Serialization/UseCorrectSignatureForSerializationMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/UseCorrectSignatureForSerializationMethodsRule.cs
22238index bf69c3a..eed6f2c 100644
22239--- a/gendarme/rules/Gendarme.Rules.Serialization/UseCorrectSignatureForSerializationMethodsRule.cs
22240+++ b/gendarme/rules/Gendarme.Rules.Serialization/UseCorrectSignatureForSerializationMethodsRule.cs
22241@@ -76,13 +76,6 @@ namespace Gendarme.Rules.Serialization {
22242 private const string NotSerializableText = "The type of this method is not marked as [Serializable].";
22243 private const string WrongSignatureText = "The method has the wrong signature, it should return System.Void and have a single parameter of type 'System.Runtime.Serialization.StreamingContext' and be private.";
22244
22245- static string [] Attributes = {
22246- "System.Runtime.Serialization.OnSerializingAttribute",
22247- "System.Runtime.Serialization.OnSerializedAttribute",
22248- "System.Runtime.Serialization.OnDeserializingAttribute",
22249- "System.Runtime.Serialization.OnDeserializedAttribute"
22250- };
22251-
22252 public override void Initialize (IRunner runner)
22253 {
22254 base.Initialize (runner);
22255@@ -97,10 +90,40 @@ namespace Gendarme.Rules.Serialization {
22256 // if the module does not have a reference to any of the attributes
22257 // then nothing will be reported by this rule
22258 (e.CurrentAssembly.Name.Name == "mscorlib" ||
22259- e.CurrentModule.HasAnyTypeReference (Attributes));
22260+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
22261+ return IsSerializationAttribute (tr);
22262+ }));
22263 };
22264 }
22265
22266+ static bool IsSerializationAttribute (TypeReference type)
22267+ {
22268+ if (type.Namespace != "System.Runtime.Serialization")
22269+ return false;
22270+
22271+ switch (type.Name) {
22272+ case "OnSerializingAttribute":
22273+ case "OnSerializedAttribute":
22274+ case "OnDeserializingAttribute":
22275+ case "OnDeserializedAttribute":
22276+ return true;
22277+ default:
22278+ return false;
22279+ }
22280+ }
22281+
22282+ static bool HasAnySerializationAttribute (ICustomAttributeProvider method)
22283+ {
22284+ if (!method.HasCustomAttributes)
22285+ return false;
22286+
22287+ foreach (CustomAttribute ca in method.CustomAttributes) {
22288+ if (IsSerializationAttribute (ca.AttributeType))
22289+ return true;
22290+ }
22291+ return false;
22292+ }
22293+
22294 public RuleResult CheckMethod (MethodDefinition method)
22295 {
22296 // rule does not apply to constructor or to methods without custom attributes
22297@@ -108,7 +131,7 @@ namespace Gendarme.Rules.Serialization {
22298 return RuleResult.DoesNotApply;
22299
22300 // marked with any of On[Des|S]erializ[ed|ing]Attribute ?
22301- if (!method.CustomAttributes.ContainsAnyType (Attributes))
22302+ if (!HasAnySerializationAttribute (method))
22303 return RuleResult.DoesNotApply;
22304
22305 // rule apply!
22306diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidLargeClassesRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidLargeClassesRule.cs
22307index 25519b4..947bd6a 100644
22308--- a/gendarme/rules/Gendarme.Rules.Smells/AvoidLargeClassesRule.cs
22309+++ b/gendarme/rules/Gendarme.Rules.Smells/AvoidLargeClassesRule.cs
22310@@ -28,6 +28,7 @@
22311
22312 using System;
22313 using System.Collections.Generic;
22314+using System.Globalization;
22315
22316 using Mono.Cecil;
22317
22318@@ -108,7 +109,7 @@ namespace Gendarme.Rules.Smells {
22319 int counter = 1; // include self
22320 for (int i = fields.Count - 1; i > start; i--) {
22321 FieldDefinition field = fields [i];
22322- if (field.Name.StartsWith (prefix)) {
22323+ if (field.Name.StartsWith (prefix, StringComparison.Ordinal)) {
22324 fields.RemoveAt (i);
22325 counter++;
22326 }
22327@@ -167,7 +168,8 @@ namespace Gendarme.Rules.Smells {
22328 continue;
22329 int count = CountPrefixedFields (prefix, i);
22330 if (count > 1) {
22331- string msg = String.Format ("This type contains fields common prefixes: {0} fields prefixed with '{1}'.",
22332+ string msg = String.Format (CultureInfo.InvariantCulture,
22333+ "This type contains fields common prefixes: {0} fields prefixed with '{1}'.",
22334 count, prefix);
22335 Runner.Report (type, Severity.Medium, Confidence.High, msg);
22336 }
22337@@ -182,7 +184,8 @@ namespace Gendarme.Rules.Smells {
22338
22339 int fcount = GetNonConstantFieldsCount (type);
22340 if (fcount > MaxFields) {
22341- string msg = String.Format ("This type contains a lot of fields ({0} versus maximum of {1}).",
22342+ string msg = String.Format (CultureInfo.InvariantCulture,
22343+ "This type contains a lot of fields ({0} versus maximum of {1}).",
22344 fcount, MaxFields);
22345 Runner.Report (type, Severity.High, Confidence.High, msg);
22346 }
22347diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidLongMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidLongMethodsRule.cs
22348index 67cb274..1ef115b 100644
22349--- a/gendarme/rules/Gendarme.Rules.Smells/AvoidLongMethodsRule.cs
22350+++ b/gendarme/rules/Gendarme.Rules.Smells/AvoidLongMethodsRule.cs
22351@@ -28,6 +28,7 @@
22352
22353 using System;
22354 using System.Collections.Generic;
22355+using System.Globalization;
22356
22357 using Mono.Cecil;
22358 using Mono.Cecil.Cil;
22359@@ -181,19 +182,6 @@ namespace Gendarme.Rules.Smells {
22360
22361 const int AssignationRatio = 7;
22362 const int DefaultAmountOfElements = 13;
22363- static Dictionary<string, string> typeMethodDictionary;
22364-
22365- static AvoidLongMethodsRule ()
22366- {
22367- typeMethodDictionary = new Dictionary<string,string> (4);
22368- typeMethodDictionary.Add ("Gtk.Bin", "Build");
22369- typeMethodDictionary.Add ("Gtk.Window", "Build");
22370- typeMethodDictionary.Add ("Gtk.Dialog", "Build");
22371- typeMethodDictionary.Add ("System.Windows.Forms.Form", "InitializeComponent");
22372- typeMethodDictionary.Add ("System.Workflow.Activities.SequentialWorkflowActivity", "InitializeComponent");
22373- typeMethodDictionary.Add ("System.Workflow.Activities.StateMachineWorkflowActivity", "InitializeComponent");
22374- typeMethodDictionary.Add ("System.Windows.Controls.UserControl", "InitializeComponent");
22375- }
22376
22377 public AvoidLongMethodsRule ()
22378 {
22379@@ -215,12 +203,31 @@ namespace Gendarme.Rules.Smells {
22380 if (method.HasParameters)
22381 return false;
22382
22383+ string name = method.Name;
22384+ if ((name != "Build") && (name != "InitializeComponent"))
22385+ return false;
22386+
22387 TypeDefinition type = method.DeclaringType.Resolve ();
22388- if ((type != null) && (type.BaseType != null)) {
22389- string method_name;
22390- if (typeMethodDictionary.TryGetValue (type.BaseType.FullName, out method_name)) {
22391- return (method_name == method.Name);
22392+ if ((type == null) || (type.BaseType == null))
22393+ return false;
22394+
22395+ string nspace = type.BaseType.Namespace;
22396+ string tname = type.BaseType.Name;
22397+ switch (name) {
22398+ case "Build":
22399+ if (nspace != "Gtk")
22400+ return false;
22401+ return (tname == "Bin" || tname == "Window" || tname == "Dialog");
22402+ case "InitializeComponent":
22403+ switch (nspace) {
22404+ case "System.Windows.Forms":
22405+ return tname == "Form";
22406+ case "System.Workflow.Activities":
22407+ return tname == "SequentialWorkflowActivity" || tname == "StateMachineWorkflowActivity";
22408+ case "System.Windows.Controls":
22409+ return tname == "UserControl";
22410 }
22411+ break;
22412 }
22413 return false;
22414 }
22415@@ -326,7 +333,8 @@ namespace Gendarme.Rules.Smells {
22416 if (sloc <= max)
22417 return RuleResult.Success;
22418
22419- string message = String.Format ("Logical SLOC: {0}. Maximum : {1}", sloc, max);
22420+ string message = String.Format (CultureInfo.CurrentCulture,
22421+ "Logical SLOC: {0}. Maximum : {1}", sloc, max);
22422 Runner.Report (method, Severity.High, Confidence.High, message);
22423 } else {
22424 // success if the instruction count is below the defined threshold
22425@@ -336,7 +344,8 @@ namespace Gendarme.Rules.Smells {
22426 if (count <= max)
22427 return RuleResult.Success;
22428
22429- string message = String.Format ("Method IL Size: {0}. Maximum Size: {1}", count, max);
22430+ string message = String.Format (CultureInfo.CurrentCulture,
22431+ "Method IL Size: {0}. Maximum Size: {1}", count, max);
22432 Runner.Report (method, Severity.High, Confidence.Normal, message);
22433 }
22434
22435diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidLongParameterListsRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidLongParameterListsRule.cs
22436index bd5ff4f..a76ec28 100644
22437--- a/gendarme/rules/Gendarme.Rules.Smells/AvoidLongParameterListsRule.cs
22438+++ b/gendarme/rules/Gendarme.Rules.Smells/AvoidLongParameterListsRule.cs
22439@@ -131,13 +131,13 @@ namespace Gendarme.Rules.Smells {
22440 if (constructor == null)
22441 return;
22442 if (HasMoreParametersThanAllowed (constructor))
22443- Runner.Report (constructor, Severity.Medium, Confidence.Normal, "This constructor contains a long parameter list.");
22444+ Runner.Report (constructor, Severity.Medium, Confidence.High, "This constructor contains a long parameter list.");
22445 }
22446
22447 private void CheckMethod (IMethodSignature method)
22448 {
22449 if (HasMoreParametersThanAllowed (method))
22450- Runner.Report (method, Severity.Medium, Confidence.Normal, "This method contains a long parameter list.");
22451+ Runner.Report (method, Severity.Medium, Confidence.High, "This method contains a long parameter list.");
22452 }
22453
22454 //TODO: Perhaps we can perform this action with linq instead of
22455@@ -182,7 +182,7 @@ namespace Gendarme.Rules.Smells {
22456 MethodDefinition method = type.GetMethod ("Invoke");
22457 // MulticastDelegate inherits from Delegate without overriding Invoke
22458 if ((method != null) && HasMoreParametersThanAllowed (method))
22459- Runner.Report (type, Severity.Medium, Confidence.Normal, "This delegate contains a long parameter list.");
22460+ Runner.Report (type, Severity.Medium, Confidence.High, "This delegate contains a long parameter list.");
22461 return Runner.CurrentRuleResult;
22462 }
22463
22464diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidMessageChainsRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidMessageChainsRule.cs
22465index 8d79e77..f786cb7 100644
22466--- a/gendarme/rules/Gendarme.Rules.Smells/AvoidMessageChainsRule.cs
22467+++ b/gendarme/rules/Gendarme.Rules.Smells/AvoidMessageChainsRule.cs
22468@@ -31,6 +31,7 @@
22469 using System;
22470 using System.Collections.Generic;
22471 using System.Diagnostics;
22472+using System.Globalization;
22473
22474 using Mono.Cecil;
22475 using Mono.Cecil.Cil;
22476@@ -116,7 +117,7 @@ namespace Gendarme.Rules.Smells {
22477
22478 // operators "break" chains
22479 MethodReference mr = (ins.Operand as MethodReference);
22480- if (mr.Name.StartsWith ("op_"))
22481+ if (mr.Name.StartsWith ("op_", StringComparison.Ordinal))
22482 continue;
22483
22484 int counter = 1;
22485@@ -131,7 +132,8 @@ namespace Gendarme.Rules.Smells {
22486 Log.WriteLine (this, "chain of length {0} at {1:X4}", counter, ins.Offset);
22487
22488 if (counter > MaxChainLength) {
22489- string msg = String.Format ("Chain length {0} versus maximum of {1}.", counter, MaxChainLength);
22490+ string msg = String.Format (CultureInfo.CurrentCulture,
22491+ "Chain length {0} versus maximum of {1}.", counter, MaxChainLength);
22492 Runner.Report (method, ins, Severity.Medium, Confidence.Normal, msg);
22493 }
22494 }
22495diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidSpeculativeGeneralityRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidSpeculativeGeneralityRule.cs
22496index 7228572..1393c22 100644
22497--- a/gendarme/rules/Gendarme.Rules.Smells/AvoidSpeculativeGeneralityRule.cs
22498+++ b/gendarme/rules/Gendarme.Rules.Smells/AvoidSpeculativeGeneralityRule.cs
22499@@ -117,15 +117,14 @@ namespace Gendarme.Rules.Smells {
22500 [EngineDependency (typeof (OpCodeEngine))]
22501 public class AvoidSpeculativeGeneralityRule : Rule, ITypeRule {
22502
22503- private bool HasExpectedInheritedTypeCount (MemberReference baseType, int expected)
22504+ private bool HasExpectedInheritedTypeCount (TypeReference baseType, int expected)
22505 {
22506 int count = 0;
22507- string base_name = baseType.FullName;
22508 foreach (AssemblyDefinition assembly in Runner.Assemblies) {
22509 foreach (ModuleDefinition module in assembly.Modules) {
22510 foreach (TypeDefinition type in module.GetAllTypes ()) {
22511 if ((baseType == type.BaseType) || (type.BaseType != null &&
22512- (base_name == type.BaseType.FullName))) {
22513+ type.BaseType.IsNamed (baseType.Namespace, baseType.Name))) {
22514 if (++count > expected)
22515 return false;
22516 }
22517@@ -168,7 +167,7 @@ namespace Gendarme.Rules.Smells {
22518
22519 private static bool InheritsOnlyFromObject (TypeDefinition type)
22520 {
22521- return !type.HasInterfaces && type.BaseType.FullName == "System.Object";
22522+ return !type.HasInterfaces && type.BaseType.IsNamed ("System", "Object");
22523 }
22524
22525 private static bool MostlyMethodsDelegatesCall (TypeDefinition type)
22526diff --git a/gendarme/rules/Gendarme.Rules.Smells/CodeDuplicatedLocator.cs b/gendarme/rules/Gendarme.Rules.Smells/CodeDuplicatedLocator.cs
22527index 621c22c..1e9790e 100644
22528--- a/gendarme/rules/Gendarme.Rules.Smells/CodeDuplicatedLocator.cs
22529+++ b/gendarme/rules/Gendarme.Rules.Smells/CodeDuplicatedLocator.cs
22530@@ -30,6 +30,7 @@ using System;
22531 using System.Collections.Generic;
22532 using System.Collections.ObjectModel;
22533 using System.Diagnostics;
22534+using System.Globalization;
22535
22536 using Mono.Cecil;
22537 using Mono.Cecil.Cil;
22538@@ -81,8 +82,10 @@ namespace Gendarme.Rules.Smells {
22539 continue;
22540
22541 Pattern duplicated = GetDuplicatedCode (current, target);
22542- if (duplicated != null && duplicated.Count > 0)
22543- parent_rule.Runner.Report (current, duplicated[0], Severity.High, Confidence.Normal, String.Format ("Duplicated code with {0}", target));
22544+ if (duplicated != null && duplicated.Count > 0) {
22545+ parent_rule.Runner.Report (current, duplicated[0], Severity.High, Confidence.Normal,
22546+ String.Format (CultureInfo.InvariantCulture, "Duplicated code with {0}", target.GetFullName ()));
22547+ }
22548 }
22549 }
22550
22551diff --git a/gendarme/rules/Gendarme.Rules.Smells/Gendarme.Rules.Smells.csproj b/gendarme/rules/Gendarme.Rules.Smells/Gendarme.Rules.Smells.csproj
22552index e3d68f2..bdad8ae 100755
22553--- a/gendarme/rules/Gendarme.Rules.Smells/Gendarme.Rules.Smells.csproj
22554+++ b/gendarme/rules/Gendarme.Rules.Smells/Gendarme.Rules.Smells.csproj
22555@@ -1,5 +1,5 @@
22556 <?xml version="1.0" encoding="utf-8"?>\r
22557-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
22558+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
22559 <PropertyGroup>\r
22560 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
22561 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
22562@@ -10,8 +10,28 @@
22563 <AppDesignerFolder>Properties</AppDesignerFolder>\r
22564 <RootNamespace>Gendarme.Rules.Smells</RootNamespace>\r
22565 <AssemblyName>Gendarme.Rules.Smells</AssemblyName>\r
22566- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
22567+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
22568 <FileAlignment>512</FileAlignment>\r
22569+ <FileUpgradeFlags>\r
22570+ </FileUpgradeFlags>\r
22571+ <OldToolsVersion>3.5</OldToolsVersion>\r
22572+ <UpgradeBackupLocation />\r
22573+ <PublishUrl>publish\</PublishUrl>\r
22574+ <Install>true</Install>\r
22575+ <InstallFrom>Disk</InstallFrom>\r
22576+ <UpdateEnabled>false</UpdateEnabled>\r
22577+ <UpdateMode>Foreground</UpdateMode>\r
22578+ <UpdateInterval>7</UpdateInterval>\r
22579+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
22580+ <UpdatePeriodically>false</UpdatePeriodically>\r
22581+ <UpdateRequired>false</UpdateRequired>\r
22582+ <MapFileExtensions>true</MapFileExtensions>\r
22583+ <ApplicationRevision>0</ApplicationRevision>\r
22584+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
22585+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
22586+ <UseApplicationTrust>false</UseApplicationTrust>\r
22587+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
22588+ <TargetFrameworkProfile />\r
22589 </PropertyGroup>\r
22590 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
22591 <DebugSymbols>true</DebugSymbols>\r
22592@@ -24,6 +44,7 @@
22593 <NoWarn>1591</NoWarn>\r
22594 <WarningsAsErrors>1570</WarningsAsErrors>\r
22595 <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Smells.xml</DocumentationFile>\r
22596+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
22597 </PropertyGroup>\r
22598 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
22599 <DebugType>pdbonly</DebugType>\r
22600@@ -35,6 +56,7 @@
22601 <NoWarn>1591</NoWarn>\r
22602 <WarningsAsErrors>1570</WarningsAsErrors>\r
22603 <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Smells.xml</DocumentationFile>\r
22604+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
22605 </PropertyGroup>\r
22606 <ItemGroup>\r
22607 <Reference Include="System" />\r
22608@@ -72,6 +94,23 @@
22609 <Name>Gendarme.Rules.Performance</Name>\r
22610 </ProjectReference>\r
22611 </ItemGroup>\r
22612+ <ItemGroup>\r
22613+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
22614+ <Visible>False</Visible>\r
22615+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
22616+ <Install>false</Install>\r
22617+ </BootstrapperPackage>\r
22618+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
22619+ <Visible>False</Visible>\r
22620+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
22621+ <Install>true</Install>\r
22622+ </BootstrapperPackage>\r
22623+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
22624+ <Visible>False</Visible>\r
22625+ <ProductName>Windows Installer 3.1</ProductName>\r
22626+ <Install>true</Install>\r
22627+ </BootstrapperPackage>\r
22628+ </ItemGroup>\r
22629 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
22630 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
22631 Other similar extension points exist, see Microsoft.Common.targets.
22632diff --git a/gendarme/rules/Gendarme.Rules.Smells/InstructionMatcher.cs b/gendarme/rules/Gendarme.Rules.Smells/InstructionMatcher.cs
22633index 21fee89..34891d6 100644
22634--- a/gendarme/rules/Gendarme.Rules.Smells/InstructionMatcher.cs
22635+++ b/gendarme/rules/Gendarme.Rules.Smells/InstructionMatcher.cs
22636@@ -51,8 +51,8 @@ namespace Gendarme.Rules.Smells {
22637 if ((source == null) || (target == null))
22638 return false;
22639
22640- int ss = source.GetSequence () - 1;
22641- int ts = target.GetSequence () - 1;
22642+ int ss = source.Index;
22643+ int ts = target.Index;
22644 if ((ss <= 0) || (ts <= 0))
22645 return false;
22646
22647diff --git a/gendarme/rules/Gendarme.Rules.Smells/Pattern.cs b/gendarme/rules/Gendarme.Rules.Smells/Pattern.cs
22648index c0c37e4..17b5afb 100644
22649--- a/gendarme/rules/Gendarme.Rules.Smells/Pattern.cs
22650+++ b/gendarme/rules/Gendarme.Rules.Smells/Pattern.cs
22651@@ -52,16 +52,7 @@ namespace Gendarme.Rules.Smells {
22652 {
22653 if (ins.OpCode.Code != Code.Isinst)
22654 return false;
22655- return ((ins.Operand as TypeReference).FullName == "System.IDisposable");
22656- }
22657-
22658- // look for a virtual call to a specific method
22659- static bool IsCallVirt (Instruction ins, string typeName, string methodName)
22660- {
22661- if (ins.OpCode.Code != Code.Callvirt)
22662- return false;
22663- MethodReference mr = (ins.Operand as MethodReference);
22664- return ((mr != null) && (mr.Name == methodName) && (mr.DeclaringType.FullName == typeName));
22665+ return (ins.Operand as TypeReference).IsNamed ("System", "IDisposable");
22666 }
22667
22668 // look for:
22669@@ -69,7 +60,9 @@ namespace Gendarme.Rules.Smells {
22670 // endfinally
22671 static bool IsIDisposableDisposePattern (Instruction ins)
22672 {
22673- if (!IsCallVirt (ins, "System.IDisposable", "Dispose"))
22674+ if (ins.OpCode.Code != Code.Callvirt)
22675+ return false;
22676+ if (!(ins.Operand as MethodReference).IsNamed ("System", "IDisposable", "Dispose"))
22677 return false;
22678 return ins.Next.Is (Code.Endfinally);
22679 }
22680@@ -89,10 +82,13 @@ namespace Gendarme.Rules.Smells {
22681 for (int i = 0; i < Count; i++) {
22682 Instruction ins = instructions [i];
22683 // foreach
22684- if (IsCallVirt (ins, "System.Collections.IEnumerator", "get_Current"))
22685- return true;
22686- if (IsCallVirt (ins, "System.Collections.IEnumerator", "MoveNext"))
22687- return !call;
22688+ if (ins.OpCode.Code == Code.Callvirt) {
22689+ MethodReference mr = (ins.Operand as MethodReference);
22690+ if (mr.IsNamed ("System.Collections", "IEnumerator", "get_Current"))
22691+ return true;
22692+ if (mr.IsNamed ("System.Collections", "IEnumerator", "MoveNext"))
22693+ return !call;
22694+ }
22695 // if there's a unknown call then it's likely not (totally) compiler generated
22696 call |= (ins.OpCode.FlowControl == FlowControl.Call);
22697 // foreach
22698diff --git a/gendarme/rules/Gendarme.Rules.Smells/README.md b/gendarme/rules/Gendarme.Rules.Smells/README.md
22699new file mode 100644
22700index 0000000..b02c441
22701--- /dev/null
22702+++ b/gendarme/rules/Gendarme.Rules.Smells/README.md
22703@@ -0,0 +1,9 @@
22704+# Gendarme.Rules.Smells Rules
22705+
22706+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Smells(git)]] pages.
22707+
22708+
22709+## Feedback
22710+
22711+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
22712+
22713diff --git a/gendarme/rules/Gendarme.Rules.Smells/Test/AvoidCodeDuplicatedInSameClassTest.cs b/gendarme/rules/Gendarme.Rules.Smells/Test/AvoidCodeDuplicatedInSameClassTest.cs
22714index f88d4ed..11dcfa6 100644
22715--- a/gendarme/rules/Gendarme.Rules.Smells/Test/AvoidCodeDuplicatedInSameClassTest.cs
22716+++ b/gendarme/rules/Gendarme.Rules.Smells/Test/AvoidCodeDuplicatedInSameClassTest.cs
22717@@ -686,20 +686,20 @@ namespace Test.Rules.Smells {
22718 class NonDuplicatedComparingAndReturningNull {
22719 string CheckTwoOptions (TypeReference type)
22720 {
22721- if (type.Implements ("System.Collections.IDictionary") || type.Implements ("System.Collections.Generic.IDictionary`2"))
22722+ if (type.Implements ("System.Collections", "IDictionary") || type.Implements ("System.Collections.Generic", "IDictionary`2"))
22723 return null;
22724 return "'Dictionary' should only be used for types implementing IDictionary and IDictionary<TKey,TValue>.";
22725 }
22726
22727 string CheckThreeOptions (TypeReference type)
22728 {
22729- if (type.Implements ("System.Collections.ICollection") ||
22730- type.Implements ("System.Collections.IEnumerable") ||
22731- type.Implements ("System.Collections.Generic.ICollection`1"))
22732+ if (type.Implements ("System.Collections", "ICollection") ||
22733+ type.Implements ("System.Collections", "IEnumerable") ||
22734+ type.Implements ("System.Collections.Generic", "ICollection`1"))
22735 return null;
22736
22737- if (type.Inherits ("System.Collections.Queue") || type.Inherits ("System.Collections.Stack") ||
22738- type.Inherits ("System.Data.DataSet") || type.Inherits ("System.Data.DataTable"))
22739+ if (type.Inherits ("System.Collections", "Queue") || type.Inherits ("System.Collections", "Stack") ||
22740+ type.Inherits ("System.Data", "DataSet") || type.Inherits ("System.Data", "DataTable"))
22741 return null;
22742
22743 return "'Collection' should only be used for implementing ICollection or IEnumerable or inheriting from Queue, Stack, DataSet and DataTable.";
22744diff --git a/gendarme/rules/Gendarme.Rules.Smells/Test/Tests.Rules.Smells.csproj b/gendarme/rules/Gendarme.Rules.Smells/Test/Tests.Rules.Smells.csproj
22745index a67869a..eb69c1d 100755
22746--- a/gendarme/rules/Gendarme.Rules.Smells/Test/Tests.Rules.Smells.csproj
22747+++ b/gendarme/rules/Gendarme.Rules.Smells/Test/Tests.Rules.Smells.csproj
22748@@ -1,5 +1,5 @@
22749 <?xml version="1.0" encoding="utf-8"?>\r
22750-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
22751+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
22752 <PropertyGroup>\r
22753 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
22754 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
22755@@ -10,8 +10,28 @@
22756 <AppDesignerFolder>Properties</AppDesignerFolder>\r
22757 <RootNamespace>Tests.Rules.Smells</RootNamespace>\r
22758 <AssemblyName>Tests.Rules.Smells</AssemblyName>\r
22759- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
22760+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
22761 <FileAlignment>512</FileAlignment>\r
22762+ <FileUpgradeFlags>\r
22763+ </FileUpgradeFlags>\r
22764+ <OldToolsVersion>3.5</OldToolsVersion>\r
22765+ <UpgradeBackupLocation />\r
22766+ <PublishUrl>publish\</PublishUrl>\r
22767+ <Install>true</Install>\r
22768+ <InstallFrom>Disk</InstallFrom>\r
22769+ <UpdateEnabled>false</UpdateEnabled>\r
22770+ <UpdateMode>Foreground</UpdateMode>\r
22771+ <UpdateInterval>7</UpdateInterval>\r
22772+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
22773+ <UpdatePeriodically>false</UpdatePeriodically>\r
22774+ <UpdateRequired>false</UpdateRequired>\r
22775+ <MapFileExtensions>true</MapFileExtensions>\r
22776+ <ApplicationRevision>0</ApplicationRevision>\r
22777+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
22778+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
22779+ <UseApplicationTrust>false</UseApplicationTrust>\r
22780+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
22781+ <TargetFrameworkProfile />\r
22782 </PropertyGroup>\r
22783 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
22784 <DebugSymbols>true</DebugSymbols>\r
22785@@ -21,6 +41,7 @@
22786 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
22787 <ErrorReport>prompt</ErrorReport>\r
22788 <WarningLevel>4</WarningLevel>\r
22789+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
22790 </PropertyGroup>\r
22791 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
22792 <DebugType>pdbonly</DebugType>\r
22793@@ -29,6 +50,7 @@
22794 <DefineConstants>TRACE</DefineConstants>\r
22795 <ErrorReport>prompt</ErrorReport>\r
22796 <WarningLevel>4</WarningLevel>\r
22797+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
22798 </PropertyGroup>\r
22799 <ItemGroup>\r
22800 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
22801@@ -75,6 +97,23 @@
22802 <ItemGroup>\r
22803 <Folder Include="Properties\" />\r
22804 </ItemGroup>\r
22805+ <ItemGroup>\r
22806+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
22807+ <Visible>False</Visible>\r
22808+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
22809+ <Install>false</Install>\r
22810+ </BootstrapperPackage>\r
22811+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
22812+ <Visible>False</Visible>\r
22813+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
22814+ <Install>true</Install>\r
22815+ </BootstrapperPackage>\r
22816+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
22817+ <Visible>False</Visible>\r
22818+ <ProductName>Windows Installer 3.1</ProductName>\r
22819+ <Install>true</Install>\r
22820+ </BootstrapperPackage>\r
22821+ </ItemGroup>\r
22822 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
22823 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
22824 Other similar extension points exist, see Microsoft.Common.targets.
22825diff --git a/gendarme/rules/Gendarme.Rules.Ui/AddMatchingArrangeMeasureOverrideRule.cs b/gendarme/rules/Gendarme.Rules.Ui/AddMatchingArrangeMeasureOverrideRule.cs
22826index aaf21fe..b288e10 100644
22827--- a/gendarme/rules/Gendarme.Rules.Ui/AddMatchingArrangeMeasureOverrideRule.cs
22828+++ b/gendarme/rules/Gendarme.Rules.Ui/AddMatchingArrangeMeasureOverrideRule.cs
22829@@ -81,15 +81,18 @@ namespace Gendarme.Rules.UI {
22830 // if the module does not reference System.Windows.Size,
22831 // then it will not be using the overrides
22832 Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
22833- Active = ((e.CurrentAssembly.Name.Name == "WindowsBase" ||
22834- e.CurrentAssembly.Name.Name == "System.Windows") ||
22835- e.CurrentModule.HasTypeReference (Size));
22836+ string assembly_name = e.CurrentAssembly.Name.Name;
22837+ Active = ((assembly_name == "WindowsBase" || assembly_name == "System.Windows") ||
22838+ e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
22839+ return tr.IsNamed ("System.Windows", "Size");
22840+ })
22841+ );
22842 };
22843 }
22844
22845 public RuleResult CheckType (TypeDefinition type)
22846 {
22847- if (!type.IsClass || !type.HasMethods || !type.Inherits ("System.Windows.FrameworkElement"))
22848+ if (!type.IsClass || !type.HasMethods || !type.Inherits ("System.Windows", "FrameworkElement"))
22849 return RuleResult.DoesNotApply;
22850 var arrangeOverride = type.GetMethod (arrangeSignature);
22851 var measureOverride = type.GetMethod (measureSignature);
22852diff --git a/gendarme/rules/Gendarme.Rules.Ui/Gendarme.Rules.Ui.csproj b/gendarme/rules/Gendarme.Rules.Ui/Gendarme.Rules.Ui.csproj
22853index 379050c..dd0ff7a 100644
22854--- a/gendarme/rules/Gendarme.Rules.Ui/Gendarme.Rules.Ui.csproj
22855+++ b/gendarme/rules/Gendarme.Rules.Ui/Gendarme.Rules.Ui.csproj
22856@@ -1,119 +1,141 @@
22857-<?xml version="1.0" encoding="utf-8"?>
22858-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
22859- <PropertyGroup>
22860- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
22861- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
22862- <ProductVersion>9.0.30729</ProductVersion>
22863- <SchemaVersion>2.0</SchemaVersion>
22864- <ProjectGuid>{949C4D51-4581-402A-AC18-B1B41F395FDA}</ProjectGuid>
22865- <OutputType>Library</OutputType>
22866- <AppDesignerFolder>Properties</AppDesignerFolder>
22867- <RootNamespace>Gendarme.Rules.Ui</RootNamespace>
22868- <AssemblyName>Gendarme.Rules.Ui</AssemblyName>
22869- <FileUpgradeFlags>
22870- </FileUpgradeFlags>
22871- <OldToolsVersion>2.0</OldToolsVersion>
22872- <UpgradeBackupLocation>
22873- </UpgradeBackupLocation>
22874- <PublishUrl>http://localhost/Gendarme.Rules.Ui/</PublishUrl>
22875- <Install>true</Install>
22876- <InstallFrom>Web</InstallFrom>
22877- <UpdateEnabled>true</UpdateEnabled>
22878- <UpdateMode>Foreground</UpdateMode>
22879- <UpdateInterval>7</UpdateInterval>
22880- <UpdateIntervalUnits>Days</UpdateIntervalUnits>
22881- <UpdatePeriodically>false</UpdatePeriodically>
22882- <UpdateRequired>false</UpdateRequired>
22883- <MapFileExtensions>true</MapFileExtensions>
22884- <ApplicationRevision>0</ApplicationRevision>
22885- <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
22886- <IsWebBootstrapper>true</IsWebBootstrapper>
22887- <UseApplicationTrust>false</UseApplicationTrust>
22888- <BootstrapperEnabled>true</BootstrapperEnabled>
22889- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
22890- </PropertyGroup>
22891- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
22892- <DebugSymbols>true</DebugSymbols>
22893- <DebugType>full</DebugType>
22894- <Optimize>false</Optimize>
22895- <OutputPath>..\..\console\bin\Debug\</OutputPath>
22896- <DefineConstants>DEBUG;TRACE</DefineConstants>
22897- <ErrorReport>prompt</ErrorReport>
22898- <WarningLevel>4</WarningLevel>
22899- <NoWarn>1590</NoWarn>
22900- <WarningsAsErrors>1571</WarningsAsErrors>
22901- <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Ui.xml</DocumentationFile>
22902- </PropertyGroup>
22903- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
22904- <DebugType>pdbonly</DebugType>
22905- <Optimize>true</Optimize>
22906- <OutputPath>..\..\console\bin\Release\</OutputPath>
22907- <DefineConstants>TRACE;RELEASE</DefineConstants>
22908- <ErrorReport>prompt</ErrorReport>
22909- <WarningLevel>4</WarningLevel>
22910- <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Ui.xml</DocumentationFile>
22911- <NoWarn>1591</NoWarn>
22912- <WarningsAsErrors>1570</WarningsAsErrors>
22913- </PropertyGroup>
22914- <ItemGroup>
22915- <Reference Include="System" />
22916- <Reference Include="System.Core">
22917- <RequiredTargetFramework>3.5</RequiredTargetFramework>
22918- </Reference>
22919- </ItemGroup>
22920- <ItemGroup>
22921- <Compile Include="..\..\AssemblyStaticInfo.cs">
22922- <Link>AssemblyStaticInfo.cs</Link>
22923- </Compile>
22924- <Compile Include="AddMatchingArrangeMeasureOverrideRule.cs" />
22925- <Compile Include="ExecutableTargetRule.cs" />
22926- <Compile Include="GtkSharpExecutableTargetRule.cs" />
22927- <Compile Include="SystemWindowsFormsExecutableTargetRule.cs" />
22928- <Compile Include="UseSTAThreadAttributeOnSWFEntryPointsRule.cs" />
22929- </ItemGroup>
22930- <ItemGroup>
22931- <ProjectReference Include="..\..\..\..\cecil\Mono.Cecil.csproj">
22932- <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>
22933- <Name>Mono.Cecil</Name>
22934- </ProjectReference>
22935- <ProjectReference Include="..\..\framework\Gendarme.Framework.csproj">
22936- <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>
22937- <Name>Gendarme.Framework</Name>
22938- </ProjectReference>
22939- </ItemGroup>
22940- <ItemGroup>
22941- <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">
22942- <Visible>False</Visible>
22943- </BootstrapperPackage>
22944- <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
22945- <Visible>False</Visible>
22946- </BootstrapperPackage>
22947- <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
22948- <Visible>False</Visible>
22949- </BootstrapperPackage>
22950- </ItemGroup>
22951- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
22952+<?xml version="1.0" encoding="utf-8"?>\r
22953+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
22954+ <PropertyGroup>\r
22955+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
22956+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
22957+ <ProductVersion>9.0.30729</ProductVersion>\r
22958+ <SchemaVersion>2.0</SchemaVersion>\r
22959+ <ProjectGuid>{949C4D51-4581-402A-AC18-B1B41F395FDA}</ProjectGuid>\r
22960+ <OutputType>Library</OutputType>\r
22961+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
22962+ <RootNamespace>Gendarme.Rules.Ui</RootNamespace>\r
22963+ <AssemblyName>Gendarme.Rules.Ui</AssemblyName>\r
22964+ <FileUpgradeFlags>\r
22965+ </FileUpgradeFlags>\r
22966+ <OldToolsVersion>3.5</OldToolsVersion>\r
22967+ <UpgradeBackupLocation>\r
22968+ </UpgradeBackupLocation>\r
22969+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
22970+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
22971+ <PublishUrl>http://localhost/Gendarme.Rules.Ui/</PublishUrl>\r
22972+ <Install>true</Install>\r
22973+ <InstallFrom>Web</InstallFrom>\r
22974+ <UpdateEnabled>true</UpdateEnabled>\r
22975+ <UpdateMode>Foreground</UpdateMode>\r
22976+ <UpdateInterval>7</UpdateInterval>\r
22977+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
22978+ <UpdatePeriodically>false</UpdatePeriodically>\r
22979+ <UpdateRequired>false</UpdateRequired>\r
22980+ <MapFileExtensions>true</MapFileExtensions>\r
22981+ <ApplicationRevision>0</ApplicationRevision>\r
22982+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
22983+ <UseApplicationTrust>false</UseApplicationTrust>\r
22984+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
22985+ <TargetFrameworkProfile />\r
22986+ </PropertyGroup>\r
22987+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
22988+ <DebugSymbols>true</DebugSymbols>\r
22989+ <DebugType>full</DebugType>\r
22990+ <Optimize>false</Optimize>\r
22991+ <OutputPath>..\..\console\bin\Debug\</OutputPath>\r
22992+ <DefineConstants>DEBUG;TRACE</DefineConstants>\r
22993+ <ErrorReport>prompt</ErrorReport>\r
22994+ <WarningLevel>4</WarningLevel>\r
22995+ <NoWarn>1590</NoWarn>\r
22996+ <WarningsAsErrors>1571</WarningsAsErrors>\r
22997+ <DocumentationFile>..\..\console\bin\Debug\Gendarme.Rules.Ui.xml</DocumentationFile>\r
22998+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
22999+ </PropertyGroup>\r
23000+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
23001+ <DebugType>pdbonly</DebugType>\r
23002+ <Optimize>true</Optimize>\r
23003+ <OutputPath>..\..\console\bin\Release\</OutputPath>\r
23004+ <DefineConstants>TRACE;RELEASE</DefineConstants>\r
23005+ <ErrorReport>prompt</ErrorReport>\r
23006+ <WarningLevel>4</WarningLevel>\r
23007+ <DocumentationFile>..\..\console\bin\Release\Gendarme.Rules.Ui.xml</DocumentationFile>\r
23008+ <NoWarn>1591</NoWarn>\r
23009+ <WarningsAsErrors>1570</WarningsAsErrors>\r
23010+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
23011+ </PropertyGroup>\r
23012+ <ItemGroup>\r
23013+ <Reference Include="System" />\r
23014+ <Reference Include="System.Core">\r
23015+ <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
23016+ </Reference>\r
23017+ </ItemGroup>\r
23018+ <ItemGroup>\r
23019+ <Compile Include="..\..\AssemblyStaticInfo.cs">\r
23020+ <Link>AssemblyStaticInfo.cs</Link>\r
23021+ </Compile>\r
23022+ <Compile Include="AddMatchingArrangeMeasureOverrideRule.cs" />\r
23023+ <Compile Include="ExecutableTargetRule.cs" />\r
23024+ <Compile Include="GtkSharpExecutableTargetRule.cs" />\r
23025+ <Compile Include="SystemWindowsFormsExecutableTargetRule.cs" />\r
23026+ <Compile Include="UseSTAThreadAttributeOnSWFEntryPointsRule.cs" />\r
23027+ </ItemGroup>\r
23028+ <ItemGroup>\r
23029+ <ProjectReference Include="..\..\..\..\cecil\Mono.Cecil.csproj">\r
23030+ <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
23031+ <Name>Mono.Cecil</Name>\r
23032+ </ProjectReference>\r
23033+ <ProjectReference Include="..\..\framework\Gendarme.Framework.csproj">\r
23034+ <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>\r
23035+ <Name>Gendarme.Framework</Name>\r
23036+ </ProjectReference>\r
23037+ </ItemGroup>\r
23038+ <ItemGroup>\r
23039+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
23040+ <Visible>False</Visible>\r
23041+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
23042+ <Install>false</Install>\r
23043+ </BootstrapperPackage>\r
23044+ <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
23045+ <Visible>False</Visible>\r
23046+ <ProductName>\r
23047+ </ProductName>\r
23048+ <Install>false</Install>\r
23049+ </BootstrapperPackage>\r
23050+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
23051+ <Visible>False</Visible>\r
23052+ <ProductName>\r
23053+ </ProductName>\r
23054+ <Install>false</Install>\r
23055+ </BootstrapperPackage>\r
23056+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
23057+ <Visible>False</Visible>\r
23058+ <ProductName>\r
23059+ </ProductName>\r
23060+ <Install>false</Install>\r
23061+ </BootstrapperPackage>\r
23062+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
23063+ <Visible>False</Visible>\r
23064+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
23065+ <Install>false</Install>\r
23066+ </BootstrapperPackage>\r
23067+ </ItemGroup>\r
23068+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
23069 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
23070 Other similar extension points exist, see Microsoft.Common.targets.
23071 <Target Name="BeforeBuild">
23072 </Target>
23073 <Target Name="AfterBuild">
23074 </Target>
23075- -->
23076- <ProjectExtensions>
23077- <MonoDevelop>
23078- <Properties>
23079- <MonoDevelop.Autotools.MakefileInfo IntegrationEnabled="true" RelativeMakefileName="Makefile.am" IsAutotoolsProject="true" RelativeConfigureInPath="../../..">
23080- <BuildFilesVar Sync="true" Name="rules_sources" />
23081- <DeployFilesVar />
23082- <ResourcesVar />
23083- <OthersVar />
23084- <GacRefVar />
23085- <AsmRefVar />
23086- <ProjectRefVar />
23087- </MonoDevelop.Autotools.MakefileInfo>
23088- </Properties>
23089- </MonoDevelop>
23090- <VisualStudio />
23091- </ProjectExtensions>
23092+ -->\r
23093+ <ProjectExtensions>\r
23094+ <MonoDevelop>\r
23095+ <Properties>\r
23096+ <MonoDevelop.Autotools.MakefileInfo IntegrationEnabled="true" RelativeMakefileName="Makefile.am" IsAutotoolsProject="true" RelativeConfigureInPath="../../..">\r
23097+ <BuildFilesVar Sync="true" Name="rules_sources" />\r
23098+ <DeployFilesVar />\r
23099+ <ResourcesVar />\r
23100+ <OthersVar />\r
23101+ <GacRefVar />\r
23102+ <AsmRefVar />\r
23103+ <ProjectRefVar />\r
23104+ </MonoDevelop.Autotools.MakefileInfo>\r
23105+ </Properties>\r
23106+ </MonoDevelop>\r
23107+ <VisualStudio />\r
23108+ </ProjectExtensions>\r
23109 </Project>
23110\ No newline at end of file
23111diff --git a/gendarme/rules/Gendarme.Rules.Ui/README.md b/gendarme/rules/Gendarme.Rules.Ui/README.md
23112new file mode 100644
23113index 0000000..b107d14
23114--- /dev/null
23115+++ b/gendarme/rules/Gendarme.Rules.Ui/README.md
23116@@ -0,0 +1,9 @@
23117+# Gendarme.Rules.Ui Rules
23118+
23119+You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Ui(git)]] pages.
23120+
23121+
23122+## Feedback
23123+
23124+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
23125+
23126diff --git a/gendarme/rules/Gendarme.Rules.Ui/Test/Tests.Rules.Ui.csproj b/gendarme/rules/Gendarme.Rules.Ui/Test/Tests.Rules.Ui.csproj
23127index 1122d10..902d880 100644
23128--- a/gendarme/rules/Gendarme.Rules.Ui/Test/Tests.Rules.Ui.csproj
23129+++ b/gendarme/rules/Gendarme.Rules.Ui/Test/Tests.Rules.Ui.csproj
23130@@ -1,5 +1,5 @@
23131 <?xml version="1.0" encoding="utf-8"?>\r
23132-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\r
23133+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">\r
23134 <PropertyGroup>\r
23135 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
23136 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
23137@@ -12,9 +12,11 @@
23138 <AssemblyName>Tests.Rules.Ui</AssemblyName>\r
23139 <FileUpgradeFlags>\r
23140 </FileUpgradeFlags>\r
23141- <OldToolsVersion>2.0</OldToolsVersion>\r
23142+ <OldToolsVersion>3.5</OldToolsVersion>\r
23143 <UpgradeBackupLocation>\r
23144 </UpgradeBackupLocation>\r
23145+ <IsWebBootstrapper>true</IsWebBootstrapper>\r
23146+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
23147 <PublishUrl>http://localhost/Tests.Rules.Ui/</PublishUrl>\r
23148 <Install>true</Install>\r
23149 <InstallFrom>Web</InstallFrom>\r
23150@@ -27,10 +29,9 @@
23151 <MapFileExtensions>true</MapFileExtensions>\r
23152 <ApplicationRevision>0</ApplicationRevision>\r
23153 <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
23154- <IsWebBootstrapper>true</IsWebBootstrapper>\r
23155 <UseApplicationTrust>false</UseApplicationTrust>\r
23156 <BootstrapperEnabled>true</BootstrapperEnabled>\r
23157- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
23158+ <TargetFrameworkProfile />\r
23159 </PropertyGroup>\r
23160 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
23161 <DebugSymbols>true</DebugSymbols>\r
23162@@ -40,6 +41,7 @@
23163 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
23164 <ErrorReport>prompt</ErrorReport>\r
23165 <WarningLevel>4</WarningLevel>\r
23166+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
23167 </PropertyGroup>\r
23168 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
23169 <DebugType>pdbonly</DebugType>\r
23170@@ -48,6 +50,7 @@
23171 <DefineConstants>TRACE</DefineConstants>\r
23172 <ErrorReport>prompt</ErrorReport>\r
23173 <WarningLevel>4</WarningLevel>\r
23174+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
23175 </PropertyGroup>\r
23176 <ItemGroup>\r
23177 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
23178@@ -64,6 +67,7 @@
23179 <Reference Include="System.Core">\r
23180 <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
23181 </Reference>\r
23182+ <Reference Include="System.Xaml" />\r
23183 <Reference Include="WindowsBase">\r
23184 <RequiredTargetFramework>3.0</RequiredTargetFramework>\r
23185 </Reference>\r
23186@@ -94,14 +98,33 @@
23187 </ProjectReference>\r
23188 </ItemGroup>\r
23189 <ItemGroup>\r
23190+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
23191+ <Visible>False</Visible>\r
23192+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
23193+ <Install>false</Install>\r
23194+ </BootstrapperPackage>\r
23195 <BootstrapperPackage Include="Microsoft.Net.Framework.2.0">\r
23196 <Visible>False</Visible>\r
23197+ <ProductName>\r
23198+ </ProductName>\r
23199+ <Install>false</Install>\r
23200 </BootstrapperPackage>\r
23201 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">\r
23202 <Visible>False</Visible>\r
23203+ <ProductName>\r
23204+ </ProductName>\r
23205+ <Install>false</Install>\r
23206 </BootstrapperPackage>\r
23207 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">\r
23208 <Visible>False</Visible>\r
23209+ <ProductName>\r
23210+ </ProductName>\r
23211+ <Install>false</Install>\r
23212+ </BootstrapperPackage>\r
23213+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
23214+ <Visible>False</Visible>\r
23215+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
23216+ <Install>false</Install>\r
23217 </BootstrapperPackage>\r
23218 </ItemGroup>\r
23219 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
23220diff --git a/gendarme/rules/Gendarme.Rules.Ui/UseSTAThreadAttributeOnSWFEntryPointsRule.cs b/gendarme/rules/Gendarme.Rules.Ui/UseSTAThreadAttributeOnSWFEntryPointsRule.cs
23221index 5d0cf60..7460b54 100644
23222--- a/gendarme/rules/Gendarme.Rules.Ui/UseSTAThreadAttributeOnSWFEntryPointsRule.cs
23223+++ b/gendarme/rules/Gendarme.Rules.Ui/UseSTAThreadAttributeOnSWFEntryPointsRule.cs
23224@@ -92,9 +92,6 @@ namespace Gendarme.Rules.UI {
23225
23226 private const string SystemWindowsForms = "System.Windows.Forms";
23227
23228- private const string STAThread = "System.STAThreadAttribute";
23229- private const string MTAThread = "System.MTAThreadAttribute";
23230-
23231 public RuleResult CheckAssembly (AssemblyDefinition assembly)
23232 {
23233 MethodDefinition entry_point = assembly.EntryPoint;
23234@@ -115,8 +112,8 @@ namespace Gendarme.Rules.UI {
23235 if (!referencesSWF)
23236 return RuleResult.DoesNotApply;
23237
23238- bool hasSTA = entry_point.HasAttribute (STAThread);
23239- bool hasMTA = entry_point.HasAttribute (MTAThread);
23240+ bool hasSTA = entry_point.HasAttribute ("System", "STAThreadAttribute");
23241+ bool hasMTA = entry_point.HasAttribute ("System", "MTAThreadAttribute");
23242
23243 // success if only [STAThread] attribute is present
23244 if (hasSTA && !hasMTA)
23245diff --git a/gendarme/rules/README.md b/gendarme/rules/README.md
23246new file mode 100644
23247index 0000000..30a91a3
23248--- /dev/null
23249+++ b/gendarme/rules/README.md
23250@@ -0,0 +1,31 @@
23251+# Gendarme Rules Assemblies
23252+
23253+Documentation for each assembly is available on [[Gendarme|http://www.mono-project.com/Gendarme]]'s wiki.
23254+
23255+* [[Gendarme.Rules.BadPractice|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.BadPractice(git)]]
23256+* [[Gendarme.Rules.Concurrency|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Concurrency(git)]]
23257+* [[Gendarme.Rules.Correctness|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Correctness(git)]]
23258+* [[Gendarme.Rules.Design|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design(git)]]
23259+* [[Gendarme.Rules.Design.Generic|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design.Generic(git)]]
23260+* [[Gendarme.Rules.Design.Linq|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design.Linq(git)]]
23261+* [[Gendarme.Rules.Exceptions|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Exceptions(git)]]
23262+* [[Gendarme.Rules.Gendarme|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Gendarme(git)]]
23263+* [[Gendarme.Rules.Globalization|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Globalization(git)]]
23264+* [[Gendarme.Rules.Interoperability|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Interoperability(git)]]
23265+* [[Gendarme.Rules.Interoperability.Com|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Interoperability.Com(git)]]
23266+* [[Gendarme.Rules.Maintainability|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Maintainability(git)]]
23267+* [[Gendarme.Rules.NUnit|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.NUnit(git)]]
23268+* [[Gendarme.Rules.Naming|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Naming(git)]]
23269+* [[Gendarme.Rules.Performance|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Performance(git)]]
23270+* [[Gendarme.Rules.Portability|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Portability(git)]]
23271+* [[Gendarme.Rules.Security|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Security(git)]]
23272+* [[Gendarme.Rules.Security.Cas|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Security.Cas(git)]]
23273+* [[Gendarme.Rules.Serialization|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Serialization(git)]]
23274+* [[Gendarme.Rules.Smells|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Smells(git)]]
23275+* [[Gendarme.Rules.Ui|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Ui(git)]]
23276+
23277+
23278+## Feedback
23279+
23280+Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
23281+
23282diff --git a/gendarme/rules/Test.Rules/Makefile.am b/gendarme/rules/Test.Rules/Makefile.am
23283index 428350d..e3f3ae4 100644
23284--- a/gendarme/rules/Test.Rules/Makefile.am
23285+++ b/gendarme/rules/Test.Rules/Makefile.am
23286@@ -5,7 +5,7 @@ test_SCRIPTS =
23287 test_DATA =
23288
23289 framework=../../bin/Gendarme.Framework.dll
23290-common_tests=../Test.Rules/Test.Rules.dll
23291+common_tests=Test.Rules.dll
23292
23293 EXTRA_DIST = $(test_sources) Test.Rules.csproj
23294 CLEANFILES = Test.Rules.dll Test.Rules.dll.mdb $(common_tests)
23295@@ -24,8 +24,8 @@ test_sources = \
23296
23297 test_build_sources = $(addprefix $(srcdir)/, $(test_sources))
23298
23299-$(common_tests): $(test_build_sources)
23300- $(GMCS) -target:library $(TESTS_OPTIONS) -pkg:mono-nunit -r:$(CECIL_ASM) -r:$(framework) -out:$@ $(test_build_sources)
23301+$(common_tests): $(test_build_sources) $(framework)
23302+ $(MCS) -target:library $(TESTS_OPTIONS) -pkg:mono-nunit -r:$(CECIL_ASM) -r:$(framework) -out:$@ $(test_build_sources)
23303
23304 all: $(common_tests)
23305
23306diff --git a/gendarme/rules/Test.Rules/Test.Rules.csproj b/gendarme/rules/Test.Rules/Test.Rules.csproj
23307index 8da60d8..9ee6d88 100755
23308--- a/gendarme/rules/Test.Rules/Test.Rules.csproj
23309+++ b/gendarme/rules/Test.Rules/Test.Rules.csproj
23310@@ -1,5 +1,5 @@
23311 <?xml version="1.0" encoding="utf-8"?>\r
23312-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
23313+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
23314 <PropertyGroup>\r
23315 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
23316 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
23317@@ -10,8 +10,28 @@
23318 <AppDesignerFolder>Properties</AppDesignerFolder>\r
23319 <RootNamespace>Test.Rules</RootNamespace>\r
23320 <AssemblyName>Test.Rules</AssemblyName>\r
23321- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
23322+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
23323 <FileAlignment>512</FileAlignment>\r
23324+ <FileUpgradeFlags>\r
23325+ </FileUpgradeFlags>\r
23326+ <OldToolsVersion>3.5</OldToolsVersion>\r
23327+ <UpgradeBackupLocation />\r
23328+ <PublishUrl>publish\</PublishUrl>\r
23329+ <Install>true</Install>\r
23330+ <InstallFrom>Disk</InstallFrom>\r
23331+ <UpdateEnabled>false</UpdateEnabled>\r
23332+ <UpdateMode>Foreground</UpdateMode>\r
23333+ <UpdateInterval>7</UpdateInterval>\r
23334+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
23335+ <UpdatePeriodically>false</UpdatePeriodically>\r
23336+ <UpdateRequired>false</UpdateRequired>\r
23337+ <MapFileExtensions>true</MapFileExtensions>\r
23338+ <ApplicationRevision>0</ApplicationRevision>\r
23339+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
23340+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
23341+ <UseApplicationTrust>false</UseApplicationTrust>\r
23342+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
23343+ <TargetFrameworkProfile />\r
23344 </PropertyGroup>\r
23345 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
23346 <DebugSymbols>true</DebugSymbols>\r
23347@@ -21,6 +41,7 @@
23348 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
23349 <ErrorReport>prompt</ErrorReport>\r
23350 <WarningLevel>4</WarningLevel>\r
23351+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
23352 </PropertyGroup>\r
23353 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
23354 <DebugType>pdbonly</DebugType>\r
23355@@ -29,6 +50,7 @@
23356 <DefineConstants>TRACE</DefineConstants>\r
23357 <ErrorReport>prompt</ErrorReport>\r
23358 <WarningLevel>4</WarningLevel>\r
23359+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
23360 </PropertyGroup>\r
23361 <ItemGroup>\r
23362 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">\r
23363@@ -61,6 +83,23 @@
23364 <Name>Gendarme.Framework</Name>\r
23365 </ProjectReference>\r
23366 </ItemGroup>\r
23367+ <ItemGroup>\r
23368+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
23369+ <Visible>False</Visible>\r
23370+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
23371+ <Install>false</Install>\r
23372+ </BootstrapperPackage>\r
23373+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
23374+ <Visible>False</Visible>\r
23375+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
23376+ <Install>true</Install>\r
23377+ </BootstrapperPackage>\r
23378+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
23379+ <Visible>False</Visible>\r
23380+ <ProductName>Windows Installer 3.1</ProductName>\r
23381+ <Install>true</Install>\r
23382+ </BootstrapperPackage>\r
23383+ </ItemGroup>\r
23384 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
23385 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
23386 Other similar extension points exist, see Microsoft.Common.targets.\r
23387diff --git a/gendarme/rules/common.make b/gendarme/rules/common.make
23388index 5e864e4..05eb8dd 100644
23389--- a/gendarme/rules/common.make
23390+++ b/gendarme/rules/common.make
23391@@ -39,13 +39,13 @@ rules_doc = $(rules_doc_zip) $(rules_doc_source) $(rules_doc_tree)
23392 generated_doc = doc/generated/index.xml
23393
23394 $(rules_dll): $(rules_build_sources) $(framework)
23395- $(GMCS) -target:library $(EXTRA_RULES_OPTIONS) -nowarn:1591 -doc:$(rules_dll).doc \
23396+ $(MCS) -target:library $(EXTRA_RULES_OPTIONS) -nowarn:1591 -doc:$(rules_dll).doc \
23397 -r:$(CECIL_ASM) -r:$(framework) -out:$@ $(rules_build_sources)
23398
23399 tests_build_sources = $(addprefix $(srcdir)/Test/, $(tests_sources))
23400
23401 $(tests_dll): $(tests_build_sources) $(rules_dll) $(EXTRA_TESTS_DEPS)
23402- $(GMCS) -target:library $(EXTRA_TESTS_OPTIONS) -r:$(CECIL_ASM) -r:$(framework) \
23403+ $(MCS) -target:library $(EXTRA_TESTS_OPTIONS) -r:$(CECIL_ASM) -r:$(framework) \
23404 -r:$(rules_dll) -r:$(common_tests) -pkg:mono-nunit -out:$@ $(tests_build_sources)
23405
23406 rule: $(rules_dll)
23407@@ -54,7 +54,7 @@ test: $(tests_dll)
23408
23409 run-test: test
23410 cp ../../bin/gendarme.exe.config $(tests_dll).config
23411- MONO_PATH=../../bin/:../Test.Rules/:$(MONO_PATH) nunit-console2 $(tests_dll)
23412+ MONO_PATH=../../bin/:../Test.Rules/:$(MONO_PATH) $(prefix)/bin/mono $(prefix)/lib/mono/4.0/nunit-console.exe $(tests_dll)
23413
23414 self-test: $(rules_dll)
23415 mono --debug $(console_runner) $(rules_dll)
23416diff --git a/gendarme/self-test.ignore b/gendarme/self-test.ignore
23417index 0bf06ca..3daebf3 100644
23418--- a/gendarme/self-test.ignore
23419+++ b/gendarme/self-test.ignore
23420@@ -24,12 +24,14 @@ M: System.Void Gendarme.Rules.Concurrency.DoNotLockOnWeakIdentityObjectsRule::An
23421 # all > 200 rules expose a Check* method that does not check for null (by contract) but we need code contracts to show this
23422 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.AvoidAssemblyVersionMismatchRule::CheckAssembly(Mono.Cecil.AssemblyDefinition)
23423 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.AvoidCallingProblematicMethodsRule::CheckMethod(Mono.Cecil.MethodDefinition)
23424+M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.AvoidNullCheckWithAsOperatorRule::CheckMethod(Mono.Cecil.MethodDefinition)
23425 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.AvoidVisibleConstantFieldRule::CheckType(Mono.Cecil.TypeDefinition)
23426 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.CheckNewExceptionWithoutThrowingRule::CheckMethod(Mono.Cecil.MethodDefinition)
23427 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.CheckNewThreadWithoutStartRule::CheckMethod(Mono.Cecil.MethodDefinition)
23428 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.CloneMethodShouldNotReturnNullRule::CheckMethod(Mono.Cecil.MethodDefinition)
23429 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.ConstructorShouldNotCallVirtualMethodsRule::CheckType(Mono.Cecil.TypeDefinition)
23430 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.DisableDebuggingCodeRule::CheckMethod(Mono.Cecil.MethodDefinition)
23431+M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.DoNotDecreaseVisibilityRule::CheckMethod(Mono.Cecil.MethodDefinition)
23432 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.DoNotForgetNotImplementedMethodsRule::CheckMethod(Mono.Cecil.MethodDefinition)
23433 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.DoNotUseEnumIsAssignableFromRule::CheckMethod(Mono.Cecil.MethodDefinition)
23434 M: Gendarme.Framework.RuleResult Gendarme.Rules.BadPractice.DoNotUseGetInterfaceToCheckAssignabilityRule::CheckMethod(Mono.Cecil.MethodDefinition)
23435@@ -58,6 +60,7 @@ M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.DoNotRecurseInEquali
23436 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.BadRecursiveInvocationRule::CheckMethod(Mono.Cecil.MethodDefinition)
23437 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.CallingEqualsWithNullArgRule::CheckMethod(Mono.Cecil.MethodDefinition)
23438 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.CheckParametersNullityInVisibleMethodsRule::CheckMethod(Mono.Cecil.MethodDefinition)
23439+M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.DeclareEventsExplicitlyRule::CheckType(Mono.Cecil.TypeDefinition)
23440 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.DisposableFieldsShouldBeDisposedRule::CheckType(Mono.Cecil.TypeDefinition)
23441 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.DoNotRoundIntegersRule::CheckMethod(Mono.Cecil.MethodDefinition)
23442 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.EnsureLocalDisposalRule::CheckMethod(Mono.Cecil.MethodDefinition)
23443@@ -75,6 +78,9 @@ M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.ReviewSelfAssignment
23444 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.ReviewUselessControlFlowRule::CheckMethod(Mono.Cecil.MethodDefinition)
23445 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.ReviewUseOfInt64BitsToDoubleRule::CheckMethod(Mono.Cecil.MethodDefinition)
23446 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.ReviewUseOfModuloOneOnIntegersRule::CheckMethod(Mono.Cecil.MethodDefinition)
23447+M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.TypesShouldBeDisposableBaseRule::CheckType(Mono.Cecil.TypeDefinition)
23448+M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.TypesWithDisposableFieldsShouldBeDisposableRule::CheckType(Mono.Cecil.TypeDefinition)
23449+M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.TypesWithNativeFieldsShouldBeDisposableRule::CheckType(Mono.Cecil.TypeDefinition)
23450 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.UseNoInliningWithGetCallingAssemblyRule::CheckMethod(Mono.Cecil.MethodDefinition)
23451 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.UseValueInPropertySetterRule::CheckMethod(Mono.Cecil.MethodDefinition)
23452 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.AbstractTypesShouldNotHavePublicConstructorsRule::CheckType(Mono.Cecil.TypeDefinition)
23453@@ -91,6 +97,7 @@ M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.ConsiderConvertingMethodT
23454 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.ConsiderUsingStaticTypeRule::CheckType(Mono.Cecil.TypeDefinition)
23455 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.DeclareEventHandlersCorrectlyRule::CheckType(Mono.Cecil.TypeDefinition)
23456 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.DisposableTypesShouldHaveFinalizerRule::CheckType(Mono.Cecil.TypeDefinition)
23457+M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.DoNotDeclareSettersOnCollectionPropertiesRule::CheckType(Mono.Cecil.TypeDefinition)
23458 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.DoNotDeclareVirtualMethodsInSealedTypeRule::CheckType(Mono.Cecil.TypeDefinition)
23459 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.DoNotDeclareProtectedMembersInSealedTypeRule::CheckType(Mono.Cecil.TypeDefinition)
23460 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.EnsureSymmetryForOverloadedOperatorsRule::CheckType(Mono.Cecil.TypeDefinition)
23461@@ -109,8 +116,6 @@ M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.ProvideAlternativeNamesFo
23462 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.ProvideTryParseAlternativeRule::CheckType(Mono.Cecil.TypeDefinition)
23463 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.StronglyTypedRule::CheckType(Mono.Cecil.TypeDefinition)
23464 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.TypesShouldBeInsideNamespacesRule::CheckType(Mono.Cecil.TypeDefinition)
23465-M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.TypesWithDisposableFieldsShouldBeDisposableRule::CheckType(Mono.Cecil.TypeDefinition)
23466-M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.TypesWithNativeFieldsShouldBeDisposableRule::CheckType(Mono.Cecil.TypeDefinition)
23467 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.UseFlagsAttributeRule::CheckType(Mono.Cecil.TypeDefinition)
23468 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.UseCorrectDisposeSignaturesRule::CheckType(Mono.Cecil.TypeDefinition)
23469 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.Generic.AvoidExcessiveParametersOnGenericTypesRule::CheckType(Mono.Cecil.TypeDefinition)
23470@@ -119,9 +124,9 @@ M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.Generic.DoNotDeclareStati
23471 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.Generic.DoNotExposeGenericListsRule::CheckType(Mono.Cecil.TypeDefinition)
23472 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.Generic.ImplementGenericCollectionInterfacesRule::CheckType(Mono.Cecil.TypeDefinition)
23473 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.Generic.PreferGenericsOverRefObjectRule::CheckMethod(Mono.Cecil.MethodDefinition)
23474-M: Gendarme.Framework.RuleResult Gendarme.Rules.Globalization.SatelliteResourceMismatchRule::CheckAssembly(Mono.Cecil.AssemblyDefinition)
23475 M: Gendarme.Framework.RuleResult Gendarme.Rules.Exceptions.AvoidArgumentExceptionDefaultConstructorRule::CheckMethod(Mono.Cecil.MethodDefinition)
23476 M: Gendarme.Framework.RuleResult Gendarme.Rules.Exceptions.DoNotDestroyStackTraceRule::CheckMethod(Mono.Cecil.MethodDefinition)
23477+M: Gendarme.Framework.RuleResult Gendarme.Rules.Exceptions.DoNotThrowInNonCatchClausesRule::CheckMethod(Mono.Cecil.MethodDefinition)
23478 M: Gendarme.Framework.RuleResult Gendarme.Rules.Exceptions.DoNotThrowInUnexpectedLocationRule::CheckMethod(Mono.Cecil.MethodDefinition)
23479 M: Gendarme.Framework.RuleResult Gendarme.Rules.Exceptions.DoNotSwallowErrorsCatchingNonSpecificExceptionsRule::CheckMethod(Mono.Cecil.MethodDefinition)
23480 M: Gendarme.Framework.RuleResult Gendarme.Rules.Exceptions.ExceptionShouldBeVisibleRule::CheckType(Mono.Cecil.TypeDefinition)
23481@@ -132,6 +137,8 @@ M: Gendarme.Framework.RuleResult Gendarme.Rules.Gendarme.DefectsMustBeReportedRu
23482 M: Gendarme.Framework.RuleResult Gendarme.Rules.Gendarme.DoNotThrowExceptionRule::CheckMethod(Mono.Cecil.MethodDefinition)
23483 M: Gendarme.Framework.RuleResult Gendarme.Rules.Gendarme.MissingEngineDependencyRule::CheckType(Mono.Cecil.TypeDefinition)
23484 M: Gendarme.Framework.RuleResult Gendarme.Rules.Gendarme.UseCorrectSuffixRule::CheckType(Mono.Cecil.TypeDefinition)
23485+M: Gendarme.Framework.RuleResult Gendarme.Rules.Globalization.PreferOverrideBaseRule::CheckMethod(Mono.Cecil.MethodDefinition)
23486+M: Gendarme.Framework.RuleResult Gendarme.Rules.Globalization.SatelliteResourceMismatchRule::CheckAssembly(Mono.Cecil.AssemblyDefinition)
23487 M: Gendarme.Framework.RuleResult Gendarme.Rules.Interoperability.CentralizePInvokesIntoNativeMethodsTypeRule::CheckType(Mono.Cecil.TypeDefinition)
23488 M: Gendarme.Framework.RuleResult Gendarme.Rules.Interoperability.CentralizePInvokesIntoNativeMethodsTypeRule::CheckMethod(Mono.Cecil.MethodDefinition)
23489 M: Gendarme.Framework.RuleResult Gendarme.Rules.Interoperability.DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule::CheckMethod(Mono.Cecil.MethodDefinition)
23490@@ -279,6 +286,7 @@ M: System.Void Gendarme.Rules.Concurrency.DoNotLockOnWeakIdentityObjectsRule::An
23491 # different code path / switch
23492 M: System.Void Gendarme.Rules.Correctness.ProvideValidXmlStringRule::CheckCall(Mono.Cecil.MethodDefinition,Mono.Cecil.Cil.Instruction,Mono.Cecil.MethodReference)
23493 M: System.Void Gendarme.Rules.Correctness.ProvideValidXPathExpressionRule::CheckCall(Mono.Cecil.MethodDefinition,Mono.Cecil.Cil.Instruction,Mono.Cecil.MethodReference)
23494+M: System.Boolean Gendarme.Rules.Concurrency.DoNotLockOnWeakIdentityObjectsRule::IsWeakSealedType(Mono.Cecil.TypeReference)
23495
23496 # mono bug wrt metatoken id with generics
23497 R: Gendarme.Rules.Performance.AvoidUncalledPrivateCodeRule
23498@@ -298,7 +306,7 @@ M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.AvoidSmallNamespaceRule::
23499 M: System.Void Gendarme.Rules.Design.AvoidSmallNamespaceRule::TearDown()
23500 M: Gendarme.Framework.RuleResult Gendarme.Rules.Design.InternalNamespacesShouldNotExposeTypesRule::CheckAssembly(Mono.Cecil.AssemblyDefinition)
23501 M: System.Void Gendarme.Rules.Interoperability.Com.MarkComSourceInterfacesAsIDispatchRule::FindInterfaces()
23502-M: System.Boolean Gendarme.Rules.Smells.AvoidSpeculativeGeneralityRule::HasExpectedInheritedTypeCount(Mono.Cecil.MemberReference,System.Int32)
23503+M: System.Boolean Gendarme.Rules.Smells.AvoidSpeculativeGeneralityRule::HasExpectedInheritedTypeCount(Mono.Cecil.TypeReference,System.Int32)
23504 M: System.Void Gendarme.XmlResultWriter::CreateDefects()
23505 M: System.Boolean Gendarme.Wizard::UpdateActiveRules()
23506 M: System.Void Gendarme.Framework.Engines.SuppressMessageEngine::AddIgnore(Mono.Cecil.IMetadataTokenProvider,System.Collections.Generic.IEnumerable`1<System.String>)
23507@@ -344,6 +352,9 @@ T: Gendarme.Rules.Performance.ReviewLinqMethodRule
23508 T: Gendarme.Rules.Design.StronglyTypedRule
23509 # 2.8+
23510 M: System.String Gendarme.Rules.Maintainability.PreferStringIsNullOrEmptyRule::GetName(Mono.Cecil.MethodDefinition,Mono.Cecil.Cil.Instruction)
23511+# ParseSeverity(System.String) and ParseConfidence(System.String) are very similar
23512+T: Gendarme.ConsoleRunner
23513+
23514 R: Gendarme.Rules.Smells.AvoidCodeDuplicatedInSiblingClassesRule
23515 M: Gendarme.Framework.RuleResult Gendarme.Rules.Correctness.AvoidFloatingPointEqualityRule::CheckMethod(Mono.Cecil.MethodDefinition)
23516 # CheckType and GetEngineDependencyValue
23517@@ -354,6 +365,7 @@ T: Gendarme.Rules.Gendarme.GendarmeRule
23518 R: Gendarme.Rules.Smells.AvoidSpeculativeGeneralityRule
23519 T: Gendarme.Framework.EngineController
23520 T: Gendarme.Framework.Helpers.MethodSignatures
23521+T: Gendarme.Framework.Rocks.ParameterRocks
23522
23523 # FIXME - note: some seems to be related to an xMCS bug
23524 R: Gendarme.Rules.Performance.AvoidMethodWithLargeMaximumStackSizeRule
23525@@ -414,6 +426,7 @@ R: Gendarme.Rules.Maintainability.AvoidUnnecessarySpecializationRule
23526 M: System.Boolean Gendarme.Rules.Interoperability.Com.ComRocks::IsTypeComVisible(Mono.Cecil.TypeDefinition)
23527 M: System.Boolean Gendarme.Rules.Performance.AvoidUnnecessaryOverridesRule::IsBase(Mono.Cecil.MethodReference,Mono.Cecil.MethodReference)
23528 M: System.Boolean Gendarme.Rules.Correctness.BadRecursiveInvocationRule::CompareMethods(Mono.Cecil.MethodReference,Mono.Cecil.MethodReference,System.Boolean)
23529+M: System.Boolean Gendarme.Rules.Naming.ParameterNamesShouldMatchOverriddenMethodRule::SignatureMatches(Mono.Cecil.MethodReference,Mono.Cecil.MethodReference,System.Boolean)
23530
23531 # ---------------------------------------------------------
23532 # These are all OK.
23533@@ -458,11 +471,6 @@ M: Gendarme.Framework.RuleResult Gendarme.Rules.Interoperability.DelegatesPassed
23534 # FIXME the last one needs validation
23535 M: System.Boolean Gendarme.Wizard::CouldCopyReport(System.String&,System.String)
23536
23537-# OK - Version and Guid sadly do not provide a TryParse method (at least they did not before FX4.0 - FIXME once we update)
23538-R: Gendarme.Rules.Performance.DoNotIgnoreMethodResultRule
23539-M: System.Boolean Gendarme.Rules.Correctness.AttributeStringLiteralsShouldParseCorrectlyRule::TryParseVersion(System.String)
23540-M: System.Boolean Gendarme.Rules.Correctness.AttributeStringLiteralsShouldParseCorrectlyRule::TryParseGuid(System.String)
23541-
23542 # OK - MethodSignatures use the CLR names for operators that starts with "op_"
23543 R: Gendarme.Rules.Naming.AvoidNonAlphanumericIdentifierRule
23544 T: Gendarme.Framework.Helpers.MethodSignatures
23545@@ -527,12 +535,6 @@ R: Gendarme.Rules.Smells.AvoidCodeDuplicatedInSameClassRule
23546 # OK - (CSC only) GetLoadSlot and GetStoreSlot are identical except for the switch/case (load versus store instructions) - delegating calls won't change defect
23547 T: Gendarme.Framework.Helpers.StackEntryAnalysis
23548
23549-# FX4 related - will be fixed once we move to FX4 (likely for Gendarme 3.0)
23550-R: Gendarme.Rules.Maintainability.AvoidUnnecessarySpecializationRule
23551-# use ISet<H>
23552-M: System.Void Gendarme.Rules.Performance.AvoidUninstantiatedInternalClassesRule::AddType(System.Collections.Generic.HashSet`1<Mono.Cecil.TypeReference>,Mono.Cecil.TypeReference)
23553-M: System.Void Gendarme.Rules.Performance.AvoidUncalledPrivateCodeRule::BuildMethodUsage(System.Collections.Generic.HashSet`1<System.UInt32>,Mono.Cecil.MethodDefinition)
23554-
23555 # OK
23556 R: Gendarme.Rules.Naming.AvoidRedundancyInTypeNameRule
23557 # ComRocks is not directly used
23558@@ -566,3 +568,12 @@ T: Gendarme.Rules.UI.GtkSharpExecutableTargetRule
23559 # OK - Gendarme.Framework.Rule may throw exceptions as it is not a real rule
23560 R: Gendarme.Rules.Gendarme.DoNotThrowExceptionRule
23561 T: Gendarme.Framework.Rule
23562+
23563+# Type::op_[Ine|e]quality is new and marked as MonoTODO but it does (at least) the same job as the earlier FX provided
23564+R: Gendarme.Rules.Portability.MonoCompatibilityReviewRule
23565+M: System.Void Gendarme.Framework.Rocks.ModuleRocks::LoadDebuggingSymbols(Mono.Cecil.ModuleDefinition)
23566+M: System.Void Gendarme.Framework.Rocks.ModuleRocks::.cctor()
23567+M: System.Void Gendarme.Framework.EngineDependencyAttribute::.ctor(System.Type)
23568+M: System.Type Gendarme.Framework.Rule::get_Type()
23569+M: System.Security.IPermission Gendarme.Rules.Security.Cas.SecurityDeclarationRocks::CreatePermission(Mono.Cecil.SecurityDeclaration,Mono.Cecil.SecurityAttribute)
23570+
23571diff --git a/gendarme/swf-wizard-runner/GuiRunner.cs b/gendarme/swf-wizard-runner/GuiRunner.cs
23572index 385406e..b34d5cb 100644
23573--- a/gendarme/swf-wizard-runner/GuiRunner.cs
23574+++ b/gendarme/swf-wizard-runner/GuiRunner.cs
23575@@ -28,6 +28,7 @@
23576
23577 using System;
23578 using System.Collections.Generic;
23579+using System.Globalization;
23580 using System.IO;
23581 using System.Reflection;
23582 using System.Text;
23583@@ -110,11 +111,11 @@ namespace Gendarme {
23584 TearDown ();
23585 }
23586 catch (Exception e) {
23587- if (CurrentRule != null)
23588- unexpected.AppendFormat ("Rule:\t{0}{1}{1}", CurrentRule, Environment.NewLine);
23589+ if (CurrentRule != null)
23590+ unexpected.Append ("Rule:\t").Append (CurrentRule).AppendLine ().AppendLine ();
23591 if (CurrentTarget != null)
23592- unexpected.AppendFormat ("Target:\t{0}{1}{1}", CurrentTarget, Environment.NewLine);
23593- unexpected.AppendFormat ("Stack trace: {0}", e);
23594+ unexpected.Append ("Target:\t").Append (CurrentTarget).AppendLine ().AppendLine ();
23595+ unexpected.Append ("Stack trace: ").Append (e);
23596 }
23597 }
23598
23599diff --git a/gendarme/swf-wizard-runner/Properties/Resources.Designer.cs b/gendarme/swf-wizard-runner/Properties/Resources.Designer.cs
23600old mode 100644
23601new mode 100755
23602index c588026..9a1518f
23603--- a/gendarme/swf-wizard-runner/Properties/Resources.Designer.cs
23604+++ b/gendarme/swf-wizard-runner/Properties/Resources.Designer.cs
23605@@ -1,7 +1,7 @@
23606-//------------------------------------------------------------------------------
23607+//------------------------------------------------------------------------------
23608 // <auto-generated>
23609 // This code was generated by a tool.
23610-// Runtime Version:2.0.50727.1433
23611+// Runtime Version:4.0.30319.1
23612 //
23613 // Changes to this file may cause incorrect behavior and will be lost if
23614 // the code is regenerated.
23615@@ -19,7 +19,7 @@ namespace Gendarme.Properties {
23616 // class via a tool like ResGen or Visual Studio.
23617 // To add or remove a member, edit your .ResX file then rerun ResGen
23618 // with the /str option, or rebuild your VS project.
23619- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
23620+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23621 [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
23622 [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
23623 internal class Resources {
23624diff --git a/gendarme/swf-wizard-runner/Properties/Settings.Designer.cs b/gendarme/swf-wizard-runner/Properties/Settings.Designer.cs
23625old mode 100644
23626new mode 100755
23627index c7479ed..ad7c2d2
23628--- a/gendarme/swf-wizard-runner/Properties/Settings.Designer.cs
23629+++ b/gendarme/swf-wizard-runner/Properties/Settings.Designer.cs
23630@@ -1,7 +1,7 @@
23631 //------------------------------------------------------------------------------
23632 // <auto-generated>
23633 // This code was generated by a tool.
23634-// Runtime Version:2.0.50727.3053
23635+// Runtime Version:4.0.30319.1
23636 //
23637 // Changes to this file may cause incorrect behavior and will be lost if
23638 // the code is regenerated.
23639@@ -12,7 +12,7 @@ namespace Gendarme.Properties {
23640
23641
23642 [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
23643- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
23644+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
23645 internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
23646
23647 private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
23648diff --git a/gendarme/swf-wizard-runner/Wizard.Designer.cs b/gendarme/swf-wizard-runner/Wizard.Designer.cs
23649index c92554a..9977480 100644
23650--- a/gendarme/swf-wizard-runner/Wizard.Designer.cs
23651+++ b/gendarme/swf-wizard-runner/Wizard.Designer.cs
23652@@ -146,7 +146,7 @@ namespace Gendarme {
23653 this.label1.Padding = new System.Windows.Forms.Padding (12, 0, 0, 1);
23654 this.label1.Size = new System.Drawing.Size (265, 14);
23655 this.label1.TabIndex = 1;
23656- this.label1.Text = "Copyright © 2005-2010 Novell, Inc. and contributors";
23657+ this.label1.Text = "Copyright © 2005-2011 Novell, Inc. and contributors";
23658 //
23659 // welcome_link_label
23660 //
23661diff --git a/gendarme/swf-wizard-runner/Wizard.cs b/gendarme/swf-wizard-runner/Wizard.cs
23662index 0739ca1..7465b19 100644
23663--- a/gendarme/swf-wizard-runner/Wizard.cs
23664+++ b/gendarme/swf-wizard-runner/Wizard.cs
23665@@ -30,6 +30,7 @@ using System;
23666 using System.Collections.Specialized;
23667 using System.Collections.Generic;
23668 using System.Diagnostics;
23669+using System.Globalization;
23670 using System.IO;
23671 using System.Windows.Forms;
23672
23673@@ -98,7 +99,7 @@ namespace Gendarme {
23674 if ((v.Major == 0) && (v.Minor == 0))
23675 welcome_gendarme_label.Text = "Gendarme (development snapshot)";
23676 else
23677- welcome_gendarme_label.Text = String.Format ("Gendarme, version {0}", v);
23678+ welcome_gendarme_label.Text = String.Format (CultureInfo.CurrentCulture, "Gendarme, version {0}", v);
23679
23680 assembly_loader = UpdateAssemblies;
23681
23682@@ -265,7 +266,7 @@ namespace Gendarme {
23683 next_button.Enabled = has_files;
23684 remove_file_button.Enabled = has_files;
23685 if (has_files) {
23686- add_files_count_label.Text = String.Format ("{0} assembl{1} selected",
23687+ add_files_count_label.Text = String.Format (CultureInfo.CurrentCulture, "{0} assembl{1} selected",
23688 files_count, files_count == 1 ? "y" : "ies");
23689 } else {
23690 add_files_count_label.Text = "No assembly selected.";
23691@@ -344,7 +345,8 @@ namespace Gendarme {
23692 // asynchronously load assemblies (or the one that changed)
23693 assemblies_loading = assembly_loader.BeginInvoke (EndCallback, assembly_loader);
23694
23695- rules_count_label.Text = String.Format ("{0} rules are available.", Runner.Rules.Count);
23696+ rules_count_label.Text = String.Format (CultureInfo.CurrentCulture,
23697+ "{0} rules are available.", Runner.Rules.Count);
23698 if (rules_loading == null)
23699 throw new InvalidOperationException ("rules_loading");
23700
23701@@ -390,7 +392,8 @@ namespace Gendarme {
23702 parent.Checked = true;
23703 }
23704 foreach (TreeNode node in rules_tree_view.Nodes) {
23705- node.ToolTipText = String.Format ("{0} rules available", node.Nodes.Count);
23706+ node.ToolTipText = String.Format (CultureInfo.CurrentCulture,
23707+ "{0} rules available", node.Nodes.Count);
23708 }
23709 nodes.Clear ();
23710 rules_tree_view.AfterCheck += RulesTreeViewAfterCheck;
23711@@ -527,8 +530,8 @@ namespace Gendarme {
23712 // update UI before waiting for assemblies to be loaded
23713 progress_bar.Value = 0;
23714 next_button.Enabled = false;
23715- analyze_status_label.Text = String.Format ("Processing assembly 1 of {0}",
23716- assemblies.Count);
23717+ analyze_status_label.Text = String.Format (CultureInfo.CurrentCulture,
23718+ "Processing assembly 1 of {0}", assemblies.Count);
23719 analyze_defect_label.Text = "Defects Found: 0";
23720 // make sure all assemblies are loaded into memory
23721 assemblies_loading.AsyncWaitHandle.WaitOne ();
23722@@ -597,7 +600,8 @@ namespace Gendarme {
23723
23724 private bool ConfirmAnalyzeAbort (bool quit)
23725 {
23726- string message = String.Format ("Abort the current analysis being executed {0}Gendarme ?",
23727+ string message = String.Format (CultureInfo.CurrentCulture,
23728+ "Abort the current analysis being executed {0}Gendarme ?",
23729 quit ? "and quit " : String.Empty);
23730 return (MessageBox.Show (this, message, "Gendarme", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
23731 MessageBoxDefaultButton.Button2) == DialogResult.Yes);
23732@@ -610,7 +614,8 @@ namespace Gendarme {
23733 internal void PreAssemblyUpdate (RunnerEventArgs e)
23734 {
23735 progress_bar.Value = counter++;
23736- analyze_status_label.Text = String.Format ("Processing assembly {0} of {1}",
23737+ analyze_status_label.Text = String.Format (CultureInfo.CurrentCulture,
23738+ "Processing assembly {0} of {1}",
23739 counter, e.Runner.Assemblies.Count);
23740 analyze_assembly_label.Text = "Assembly: " + e.CurrentAssembly.Name.FullName;
23741 }
23742@@ -621,7 +626,8 @@ namespace Gendarme {
23743 /// <param name="e">RunnerEventArgs that contains the Assembly being analyzed and the Runner</param>
23744 internal void PostTypeUpdate (RunnerEventArgs e)
23745 {
23746- analyze_defect_label.Text = String.Format ("Defects Found: {0}", e.Runner.Defects.Count);
23747+ analyze_defect_label.Text = String.Format (CultureInfo.CurrentCulture,
23748+ "Defects Found: {0}", e.Runner.Defects.Count);
23749 }
23750
23751 #endregion
23752@@ -633,8 +639,9 @@ namespace Gendarme {
23753 bool has_defects = (Runner.Defects.Count > 0);
23754 save_report_button.Enabled = has_defects;
23755 view_report_button.Enabled = has_defects;
23756- report_subtitle_label.Text = String.Format ("Gendarme has found {0} defects during analysis.",
23757- has_defects ? Runner.Defects.Count.ToString () : "no");
23758+ report_subtitle_label.Text = String.Format (CultureInfo.CurrentCulture,
23759+ "Gendarme has found {0} defects during analysis.",
23760+ has_defects ? Runner.Defects.Count.ToString (CultureInfo.CurrentCulture) : "no");
23761 cancel_button.Text = "Close";
23762 next_button.Enabled = false;
23763
23764diff --git a/gendarme/swf-wizard-runner/swf-wizard-runner.csproj b/gendarme/swf-wizard-runner/swf-wizard-runner.csproj
23765index b54da3b..4f52a11 100644
23766--- a/gendarme/swf-wizard-runner/swf-wizard-runner.csproj
23767+++ b/gendarme/swf-wizard-runner/swf-wizard-runner.csproj
23768@@ -1,5 +1,5 @@
23769 <?xml version="1.0" encoding="utf-8"?>\r
23770-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
23771+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
23772 <PropertyGroup>\r
23773 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
23774 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
23775@@ -10,9 +10,29 @@
23776 <AppDesignerFolder>Properties</AppDesignerFolder>\r
23777 <RootNamespace>Gendarme</RootNamespace>\r
23778 <AssemblyName>GendarmeWizard</AssemblyName>\r
23779- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
23780+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
23781 <FileAlignment>512</FileAlignment>\r
23782 <ApplicationIcon>Resources\gendarme.ico</ApplicationIcon>\r
23783+ <FileUpgradeFlags>\r
23784+ </FileUpgradeFlags>\r
23785+ <OldToolsVersion>3.5</OldToolsVersion>\r
23786+ <UpgradeBackupLocation />\r
23787+ <PublishUrl>publish\</PublishUrl>\r
23788+ <Install>true</Install>\r
23789+ <InstallFrom>Disk</InstallFrom>\r
23790+ <UpdateEnabled>false</UpdateEnabled>\r
23791+ <UpdateMode>Foreground</UpdateMode>\r
23792+ <UpdateInterval>7</UpdateInterval>\r
23793+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
23794+ <UpdatePeriodically>false</UpdatePeriodically>\r
23795+ <UpdateRequired>false</UpdateRequired>\r
23796+ <MapFileExtensions>true</MapFileExtensions>\r
23797+ <ApplicationRevision>0</ApplicationRevision>\r
23798+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
23799+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
23800+ <UseApplicationTrust>false</UseApplicationTrust>\r
23801+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
23802+ <TargetFrameworkProfile />\r
23803 </PropertyGroup>\r
23804 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
23805 <DebugSymbols>true</DebugSymbols>\r
23806@@ -22,6 +42,7 @@
23807 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
23808 <ErrorReport>prompt</ErrorReport>\r
23809 <WarningLevel>4</WarningLevel>\r
23810+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
23811 </PropertyGroup>\r
23812 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
23813 <DebugType>pdbonly</DebugType>\r
23814@@ -30,6 +51,7 @@
23815 <DefineConstants>TRACE;RELEASE</DefineConstants>\r
23816 <ErrorReport>prompt</ErrorReport>\r
23817 <WarningLevel>4</WarningLevel>\r
23818+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
23819 </PropertyGroup>\r
23820 <ItemGroup>\r
23821 <Reference Include="System" />\r
23822@@ -39,7 +61,7 @@
23823 <Reference Include="System.Drawing" />\r
23824 <Reference Include="System.Windows.Forms" />\r
23825 <Reference Include="System.Xml" />\r
23826- <Reference Include="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL" />\r
23827+ <Reference Include="System.Xml.Linq" />\r
23828 </ItemGroup>\r
23829 <ItemGroup>\r
23830 <Compile Include="..\AssemblyStaticInfo.cs" />\r
23831@@ -50,6 +72,16 @@
23832 <Compile Include="..\console\XmlResultWriter.cs" />\r
23833 <Compile Include="GuiRunner.cs" />\r
23834 <Compile Include="Page.cs" />\r
23835+ <Compile Include="Properties\Resources.Designer.cs">\r
23836+ <AutoGen>True</AutoGen>\r
23837+ <DesignTime>True</DesignTime>\r
23838+ <DependentUpon>Resources.resx</DependentUpon>\r
23839+ </Compile>\r
23840+ <Compile Include="Properties\Settings.Designer.cs">\r
23841+ <AutoGen>True</AutoGen>\r
23842+ <DesignTimeSharedInput>True</DesignTimeSharedInput>\r
23843+ <DependentUpon>Settings.settings</DependentUpon>\r
23844+ </Compile>\r
23845 <Compile Include="Wizard.cs">\r
23846 <SubType>Form</SubType>\r
23847 </Compile>\r
23848@@ -64,16 +96,12 @@
23849 <EmbeddedResource Include="Properties\Resources.resx">\r
23850 <SubType>Designer</SubType>\r
23851 <Generator>ResXFileCodeGenerator</Generator>\r
23852+ <LastGenOutput>Resources.Designer.cs</LastGenOutput>\r
23853 </EmbeddedResource>\r
23854- <Compile Include="Properties\Resources.Designer.cs">\r
23855- <DependentUpon>Resources.resx</DependentUpon>\r
23856- </Compile>\r
23857 <None Include="Properties\Settings.settings">\r
23858 <Generator>SettingsSingleFileGenerator</Generator>\r
23859+ <LastGenOutput>Settings.Designer.cs</LastGenOutput>\r
23860 </None>\r
23861- <Compile Include="Properties\Settings.Designer.cs">\r
23862- <DependentUpon>Settings.settings</DependentUpon>\r
23863- </Compile>\r
23864 <EmbeddedResource Include="..\console\gendarme.xsl" />\r
23865 <None Include="Resources\gendarme.png" />\r
23866 </ItemGroup>\r
23867@@ -90,6 +118,23 @@
23868 <ItemGroup>\r
23869 <Content Include="Resources\gendarme.ico" />\r
23870 </ItemGroup>\r
23871+ <ItemGroup>\r
23872+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
23873+ <Visible>False</Visible>\r
23874+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
23875+ <Install>false</Install>\r
23876+ </BootstrapperPackage>\r
23877+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
23878+ <Visible>False</Visible>\r
23879+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
23880+ <Install>true</Install>\r
23881+ </BootstrapperPackage>\r
23882+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
23883+ <Visible>False</Visible>\r
23884+ <ProductName>Windows Installer 3.1</ProductName>\r
23885+ <Install>true</Install>\r
23886+ </BootstrapperPackage>\r
23887+ </ItemGroup>\r
23888 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
23889 <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
23890 Other similar extension points exist, see Microsoft.Common.targets.\r
23891diff --git a/gendarme/tools/supported/Makefile.am b/gendarme/tools/supported/Makefile.am
23892index 4f8f0a9..8590cf2 100644
23893--- a/gendarme/tools/supported/Makefile.am
23894+++ b/gendarme/tools/supported/Makefile.am
23895@@ -1,2 +1,2 @@
23896-SUBDIRS = gd2i
23897+SUBDIRS = gd2i templates
23898
23899diff --git a/gendarme/tools/supported/gd2i/Makefile.am b/gendarme/tools/supported/gd2i/Makefile.am
23900index 0ad49f3..c698ed5 100644
23901--- a/gendarme/tools/supported/gd2i/Makefile.am
23902+++ b/gendarme/tools/supported/gd2i/Makefile.am
23903@@ -12,7 +12,7 @@ gd2i_sources = \
23904 gd2i.cs
23905
23906 $(gd2i_SCRIPTS): $(gd2i_sources)
23907- $(GMCS) -d:CODE_ANALYSIS -debug $^ -out:$@
23908+ $(MCS) -d:CODE_ANALYSIS -debug $^ -out:$@
23909
23910 update: $(gd2i_SCRIPTS)
23911 mono --debug $(gd2i_SCRIPTS) ../../../bin/self-test.xml ../../../self-test.ignore
23912diff --git a/gendarme/tools/supported/gd2i/gd2i.csproj b/gendarme/tools/supported/gd2i/gd2i.csproj
23913index ec2aa2d..84105de 100644
23914--- a/gendarme/tools/supported/gd2i/gd2i.csproj
23915+++ b/gendarme/tools/supported/gd2i/gd2i.csproj
23916@@ -1,60 +1,99 @@
23917-<?xml version="1.0" encoding="utf-8"?>
23918-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
23919- <PropertyGroup>
23920- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
23921- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
23922- <ProductVersion>9.0.30729</ProductVersion>
23923- <SchemaVersion>2.0</SchemaVersion>
23924- <ProjectGuid>{627AA224-D043-4CF4-A783-72546E6ACFDD}</ProjectGuid>
23925- <OutputType>Exe</OutputType>
23926- <AppDesignerFolder>Properties</AppDesignerFolder>
23927- <RootNamespace>gd2i</RootNamespace>
23928- <AssemblyName>gd2i</AssemblyName>
23929- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
23930- <FileAlignment>512</FileAlignment>
23931- </PropertyGroup>
23932- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
23933- <DebugSymbols>true</DebugSymbols>
23934- <DebugType>full</DebugType>
23935- <Optimize>false</Optimize>
23936- <OutputPath>bin\Debug\</OutputPath>
23937- <DefineConstants>TRACE;DEBUG;CODE_ANALYSIS</DefineConstants>
23938- <ErrorReport>prompt</ErrorReport>
23939- <WarningLevel>4</WarningLevel>
23940- </PropertyGroup>
23941- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
23942- <DebugType>pdbonly</DebugType>
23943- <Optimize>true</Optimize>
23944- <OutputPath>bin\Release\</OutputPath>
23945- <DefineConstants>TRACE</DefineConstants>
23946- <ErrorReport>prompt</ErrorReport>
23947- <WarningLevel>4</WarningLevel>
23948- </PropertyGroup>
23949- <ItemGroup>
23950- <Reference Include="System" />
23951- <Reference Include="System.Core">
23952- <RequiredTargetFramework>3.5</RequiredTargetFramework>
23953- </Reference>
23954- <Reference Include="System.Xml" />
23955- </ItemGroup>
23956- <ItemGroup>
23957- <Compile Include="..\..\..\AssemblyStaticInfo.cs">
23958- <Link>AssemblyStaticInfo.cs</Link>
23959- </Compile>
23960- <Compile Include="..\..\..\console\Options.cs">
23961- <Link>Options.cs</Link>
23962- </Compile>
23963- <Compile Include="gd2i.cs" />
23964- </ItemGroup>
23965- <ItemGroup>
23966- <Folder Include="Properties\" />
23967- </ItemGroup>
23968- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
23969+<?xml version="1.0" encoding="utf-8"?>\r
23970+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
23971+ <PropertyGroup>\r
23972+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
23973+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
23974+ <ProductVersion>9.0.30729</ProductVersion>\r
23975+ <SchemaVersion>2.0</SchemaVersion>\r
23976+ <ProjectGuid>{627AA224-D043-4CF4-A783-72546E6ACFDD}</ProjectGuid>\r
23977+ <OutputType>Exe</OutputType>\r
23978+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
23979+ <RootNamespace>gd2i</RootNamespace>\r
23980+ <AssemblyName>gd2i</AssemblyName>\r
23981+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
23982+ <FileAlignment>512</FileAlignment>\r
23983+ <FileUpgradeFlags>\r
23984+ </FileUpgradeFlags>\r
23985+ <OldToolsVersion>3.5</OldToolsVersion>\r
23986+ <UpgradeBackupLocation />\r
23987+ <PublishUrl>publish\</PublishUrl>\r
23988+ <Install>true</Install>\r
23989+ <InstallFrom>Disk</InstallFrom>\r
23990+ <UpdateEnabled>false</UpdateEnabled>\r
23991+ <UpdateMode>Foreground</UpdateMode>\r
23992+ <UpdateInterval>7</UpdateInterval>\r
23993+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
23994+ <UpdatePeriodically>false</UpdatePeriodically>\r
23995+ <UpdateRequired>false</UpdateRequired>\r
23996+ <MapFileExtensions>true</MapFileExtensions>\r
23997+ <ApplicationRevision>0</ApplicationRevision>\r
23998+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
23999+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
24000+ <UseApplicationTrust>false</UseApplicationTrust>\r
24001+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
24002+ <TargetFrameworkProfile />\r
24003+ </PropertyGroup>\r
24004+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
24005+ <DebugSymbols>true</DebugSymbols>\r
24006+ <DebugType>full</DebugType>\r
24007+ <Optimize>false</Optimize>\r
24008+ <OutputPath>bin\Debug\</OutputPath>\r
24009+ <DefineConstants>TRACE;DEBUG;CODE_ANALYSIS</DefineConstants>\r
24010+ <ErrorReport>prompt</ErrorReport>\r
24011+ <WarningLevel>4</WarningLevel>\r
24012+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
24013+ </PropertyGroup>\r
24014+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
24015+ <DebugType>pdbonly</DebugType>\r
24016+ <Optimize>true</Optimize>\r
24017+ <OutputPath>bin\Release\</OutputPath>\r
24018+ <DefineConstants>TRACE</DefineConstants>\r
24019+ <ErrorReport>prompt</ErrorReport>\r
24020+ <WarningLevel>4</WarningLevel>\r
24021+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
24022+ </PropertyGroup>\r
24023+ <ItemGroup>\r
24024+ <Reference Include="System" />\r
24025+ <Reference Include="System.Core">\r
24026+ <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
24027+ </Reference>\r
24028+ <Reference Include="System.Xml" />\r
24029+ </ItemGroup>\r
24030+ <ItemGroup>\r
24031+ <Compile Include="..\..\..\AssemblyStaticInfo.cs">\r
24032+ <Link>AssemblyStaticInfo.cs</Link>\r
24033+ </Compile>\r
24034+ <Compile Include="..\..\..\console\Options.cs">\r
24035+ <Link>Options.cs</Link>\r
24036+ </Compile>\r
24037+ <Compile Include="gd2i.cs" />\r
24038+ </ItemGroup>\r
24039+ <ItemGroup>\r
24040+ <Folder Include="Properties\" />\r
24041+ </ItemGroup>\r
24042+ <ItemGroup>\r
24043+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
24044+ <Visible>False</Visible>\r
24045+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
24046+ <Install>false</Install>\r
24047+ </BootstrapperPackage>\r
24048+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
24049+ <Visible>False</Visible>\r
24050+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
24051+ <Install>true</Install>\r
24052+ </BootstrapperPackage>\r
24053+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
24054+ <Visible>False</Visible>\r
24055+ <ProductName>Windows Installer 3.1</ProductName>\r
24056+ <Install>true</Install>\r
24057+ </BootstrapperPackage>\r
24058+ </ItemGroup>\r
24059+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
24060 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
24061 Other similar extension points exist, see Microsoft.Common.targets.
24062 <Target Name="BeforeBuild">
24063 </Target>
24064 <Target Name="AfterBuild">
24065 </Target>
24066- -->
24067+ -->\r
24068 </Project>
24069\ No newline at end of file
24070diff --git a/gendarme/tools/supported/templates/.gitignore b/gendarme/tools/supported/templates/.gitignore
24071new file mode 100644
24072index 0000000..c4c4ffc
24073--- /dev/null
24074+++ b/gendarme/tools/supported/templates/.gitignore
24075@@ -0,0 +1 @@
24076+*.zip
24077diff --git a/gendarme/tools/supported/templates/AssemblyRule.cs b/gendarme/tools/supported/templates/AssemblyRule.cs
24078new file mode 100644
24079index 0000000..80e77c1
24080--- /dev/null
24081+++ b/gendarme/tools/supported/templates/AssemblyRule.cs
24082@@ -0,0 +1,65 @@
24083+//
24084+// $rootnamespace$.$safeitemname$
24085+//
24086+// Authors:
24087+// $name$ <$email$>
24088+//
24089+// Copyright (C) $year$ $name$
24090+//
24091+// Permission is hereby granted, free of charge, to any person obtaining a copy
24092+// of this software and associated documentation files (the "Software"), to deal
24093+// in the Software without restriction, including without limitation the rights
24094+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24095+// copies of the Software, and to permit persons to whom the Software is
24096+// furnished to do so, subject to the following conditions:
24097+//
24098+// The above copyright notice and this permission notice shall be included in
24099+// all copies or substantial portions of the Software.
24100+//
24101+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24102+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24103+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24104+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24105+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24106+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24107+// THE SOFTWARE.
24108+
24109+using System;
24110+
24111+using Mono.Cecil;
24112+using Mono.Cecil.Cil;
24113+
24114+using Gendarme.Framework;
24115+using Gendarme.Framework.Engines;
24116+using Gendarme.Framework.Helpers;
24117+using Gendarme.Framework.Rocks;
24118+
24119+namespace $rootnamespace$ {
24120+
24121+ /// <summary>
24122+ /// TODO: Add a summary of the rule.
24123+ /// </summary>
24124+ /// <example>
24125+ /// Bad example:
24126+ /// <code>
24127+ /// TODO: Add an example where the rule would fail.
24128+ /// </code>
24129+ /// </example>
24130+ /// <example>
24131+ /// Good example:
24132+ /// <code>
24133+ /// TODO: Show how to fix the bad example.
24134+ /// </code>
24135+ /// </example>
24136+
24137+ // TODO: Describe the problem and solution
24138+ [Problem ("")]
24139+ [Solution ("")]
24140+ public class $safeitemname$ : Rule, IAssemblyRule {
24141+ public RuleResult CheckAssembly (AssemblyDefinition assembly)
24142+ {
24143+ // TODO: Write the rule.
24144+ return RuleResult.Success;
24145+ }
24146+ }
24147+}
24148diff --git a/gendarme/tools/supported/templates/AssemblyRule.vstemplate b/gendarme/tools/supported/templates/AssemblyRule.vstemplate
24149new file mode 100644
24150index 0000000..9715194
24151--- /dev/null
24152+++ b/gendarme/tools/supported/templates/AssemblyRule.vstemplate
24153@@ -0,0 +1,24 @@
24154+<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">\r
24155+ <TemplateData>\r
24156+ <DefaultName>Assembly Rule.cs</DefaultName>\r
24157+ <Name>Assembly Rule</Name>\r
24158+ <Description>A gendarme rule that checks an assembly.</Description>\r
24159+ <ProjectType>CSharp</ProjectType>\r
24160+ <SortOrder>10</SortOrder>\r
24161+ <Icon>__TemplateIcon.ico</Icon>\r
24162+ </TemplateData>\r
24163+ <TemplateContent>\r
24164+ <References>\r
24165+ <Reference>\r
24166+ <Assembly>Mono.Cecil</Assembly>\r
24167+ </Reference>\r
24168+ <Reference>\r
24169+ <Assembly>Gendarme.Framework</Assembly>\r
24170+ </Reference>\r
24171+ <Reference>\r
24172+ <Assembly>System.Core</Assembly>\r
24173+ </Reference>\r
24174+ </References>\r
24175+ <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">AssemblyRule.cs</ProjectItem>\r
24176+ </TemplateContent>\r
24177+</VSTemplate>
24178\ No newline at end of file
24179diff --git a/gendarme/tools/supported/templates/AssemblyTest.cs b/gendarme/tools/supported/templates/AssemblyTest.cs
24180new file mode 100644
24181index 0000000..77d5c06
24182--- /dev/null
24183+++ b/gendarme/tools/supported/templates/AssemblyTest.cs
24184@@ -0,0 +1,64 @@
24185+//
24186+// $rootnamespace$.$safeitemname$
24187+//
24188+// Authors:
24189+// $name$ <$email$>
24190+//
24191+// Copyright (C) $year$ $name$
24192+//
24193+// Permission is hereby granted, free of charge, to any person obtaining a copy
24194+// of this software and associated documentation files (the "Software"), to deal
24195+// in the Software without restriction, including without limitation the rights
24196+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24197+// copies of the Software, and to permit persons to whom the Software is
24198+// furnished to do so, subject to the following conditions:
24199+//
24200+// The above copyright notice and this permission notice shall be included in
24201+// all copies or substantial portions of the Software.
24202+//
24203+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24204+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24205+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24206+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24207+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24208+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24209+// THE SOFTWARE.
24210+
24211+using System;
24212+using System.Reflection;
24213+
24214+using Mono.Cecil;
24215+// TODO: Add using for the project of the rule being tested.
24216+// using Gendarme.Rules. ;
24217+
24218+using NUnit.Framework;
24219+using Test.Rules.Fixtures;
24220+using Test.Rules.Helpers;
24221+using Test.Rules.Definitions;
24222+
24223+namespace $rootnamespace$ {
24224+
24225+ [TestFixture]
24226+ public class $safeitemname$ : AssemblyRuleTestFixture</* TODO: Add rule's type */> {
24227+ [Test]
24228+ public void DoesNotApply ()
24229+ {
24230+ // TODO: Write tests that don't apply.
24231+ // AssertRuleDoesNotApply (assembly);
24232+ }
24233+
24234+ [Test]
24235+ public void Good ()
24236+ {
24237+ // TODO: Write tests that should succeed.
24238+ // AssertRuleSuccess (assembly);
24239+ }
24240+
24241+ [Test]
24242+ public void Bad ()
24243+ {
24244+ // TODO: Write tests that should fail.
24245+ // AssertRuleFailure (assembly);
24246+ }
24247+ }
24248+}
24249diff --git a/gendarme/tools/supported/templates/AssemblyTest.vstemplate b/gendarme/tools/supported/templates/AssemblyTest.vstemplate
24250new file mode 100644
24251index 0000000..9c8c0f0
24252--- /dev/null
24253+++ b/gendarme/tools/supported/templates/AssemblyTest.vstemplate
24254@@ -0,0 +1,27 @@
24255+<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">\r
24256+ <TemplateData>\r
24257+ <DefaultName>Assembly Rule Test.cs</DefaultName>\r
24258+ <Name>Assembly Rule Test</Name>\r
24259+ <Description>A unit test for a gendarme assembly rule.</Description>\r
24260+ <ProjectType>CSharp</ProjectType>\r
24261+ <SortOrder>10</SortOrder>\r
24262+ <Icon>__TemplateIcon.ico</Icon>\r
24263+ </TemplateData>\r
24264+ <TemplateContent>\r
24265+ <References>\r
24266+ <Reference>\r
24267+ <Assembly>Mono.Cecil</Assembly>\r
24268+ </Reference>\r
24269+ <Reference>\r
24270+ <Assembly>Gendarme.Framework</Assembly>\r
24271+ </Reference>\r
24272+ <Reference>\r
24273+ <Assembly>Test.Rules</Assembly>\r
24274+ </Reference>\r
24275+ <Reference>\r
24276+ <Assembly>System.Core</Assembly>\r
24277+ </Reference>\r
24278+ </References>\r
24279+ <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">AssemblyTest.cs</ProjectItem>\r
24280+ </TemplateContent>\r
24281+</VSTemplate>
24282\ No newline at end of file
24283diff --git a/gendarme/tools/supported/templates/Makefile.am b/gendarme/tools/supported/templates/Makefile.am
24284new file mode 100644
24285index 0000000..885e9e8
24286--- /dev/null
24287+++ b/gendarme/tools/supported/templates/Makefile.am
24288@@ -0,0 +1,102 @@
24289+EXTRA_DIST = README README.vsnet \
24290+ AssemblyRule.cs AssemblyRule.vstemplate \
24291+ AssemblyTest.cs AssemblyTest.vstemplate \
24292+ TypeRule.cs TypeRule.vstemplate \
24293+ TypeTest.cs TypeTest.vstemplate \
24294+ MethodRule.cs MethodRule.vstemplate \
24295+ MethodTest.cs MethodTest.vstemplate \
24296+ Templates.RuleProject.csproj Templates.RuleProject.vstemplate \
24297+ Templates.TestProject.csproj Templates.TestProject.vstemplate
24298+
24299+GENDARME_ICON = ../../../swf-wizard-runner/Resources/gendarme.ico
24300+
24301+vsnet-item-assembly-rule:
24302+ mkdir -p temp
24303+ cp $(GENDARME_ICON) temp/__TemplateIcon.ico
24304+ cp AssemblyRule.cs temp/AssemblyRule.cs
24305+ cp AssemblyRule.vstemplate temp/MyTemplate.vstemplate
24306+ zip -j "Templates\ItemTemplates\Visual C#\Gendarme Items\Assembly Rule.zip" temp/*
24307+ rm -rf temp/*
24308+
24309+vsnet-item-assembly-test:
24310+ mkdir -p temp
24311+ cp $(GENDARME_ICON) temp/__TemplateIcon.ico
24312+ cp AssemblyTest.cs temp/AssemblyTest.cs
24313+ cp AssemblyTest.vstemplate temp/MyTemplate.vstemplate
24314+ zip -j "Templates\ItemTemplates\Visual C#\Gendarme Items\Assembly Rule Test.zip" temp/*
24315+ rm -rf temp/*
24316+
24317+vsnet-item-method-rule:
24318+ mkdir -p temp
24319+ cp $(GENDARME_ICON) temp/__TemplateIcon.ico
24320+ cp MethodRule.cs temp/MethodRule.cs
24321+ cp MethodRule.vstemplate temp/MyTemplate.vstemplate
24322+ zip -j "Templates\ItemTemplates\Visual C#\Gendarme Items\Method Rule.zip" temp/*
24323+ rm -rf temp/*
24324+
24325+vsnet-item-method-test:
24326+ mkdir -p temp
24327+ cp $(GENDARME_ICON) temp/__TemplateIcon.ico
24328+ cp MethodTest.cs temp/MethodTest.cs
24329+ cp MethodTest.vstemplate temp/MyTemplate.vstemplate
24330+ zip -j "Templates\ItemTemplates\Visual C#\Gendarme Items\Method Rule Test.zip" temp/*
24331+ rm -rf temp/*
24332+
24333+vsnet-item-type-rule:
24334+ mkdir -p temp
24335+ cp $(GENDARME_ICON) temp/__TemplateIcon.ico
24336+ cp TypeRule.cs temp/TypeRule.cs
24337+ cp TypeRule.vstemplate temp/MyTemplate.vstemplate
24338+ zip -j "Templates\ItemTemplates\Visual C#\Gendarme Items\Type Rule.zip" temp/*
24339+ rm -rf temp/*
24340+
24341+vsnet-item-type-test:
24342+ mkdir -p temp
24343+ cp $(GENDARME_ICON) temp/__TemplateIcon.ico
24344+ cp TypeTest.cs temp/TypeTest.cs
24345+ cp TypeTest.vstemplate temp/MyTemplate.vstemplate
24346+ zip -j "Templates\ItemTemplates\Visual C#\Gendarme Items\Type Rule Test.zip" temp/*
24347+ rm -rf temp/*
24348+
24349+vsnet-item-templates: vsnet-item-assembly-rule vsnet-item-assembly-test \
24350+ vsnet-item-method-rule vsnet-item-method-test \
24351+ vsnet-item-type-rule vsnet-item-type-test
24352+
24353+vsnet-project-rules:
24354+ mkdir -p temp
24355+ cp $(GENDARME_ICON) temp/__TemplateIcon.ico
24356+ cp Templates.RuleProject.csproj temp/Templates.RuleProject.csproj
24357+ cp Templates.RuleProject.vstemplate temp/MyTemplate.vstemplate
24358+ zip -j "Templates\ProjectTemplates\Visual C#\Gendarme Projects\Rule Assembly.zip" temp/*
24359+ rm -rf temp/*
24360+
24361+vsnet-project-tests:
24362+ mkdir -p temp
24363+ cp $(GENDARME_ICON) temp/__TemplateIcon.ico
24364+ cp Templates.TestProject.csproj temp/Templates.TestProject.csproj
24365+ cp Templates.TestProject.vstemplate temp/MyTemplate.vstemplate
24366+ zip -j "Templates\ProjectTemplates\Visual C#\Gendarme Projects\Rule Test Assembly.zip" temp/*
24367+ rm -rf temp/*
24368+
24369+vsnet-project-templates: vsnet-project-rules vsnet-project-tests
24370+
24371+vsnet: vsnet-item-templates vsnet-project-templates
24372+ zip gendarme-vsnet-templates.zip README.vsnet \
24373+ "Templates\ItemTemplates\Visual C#\Gendarme Items\Assembly Rule.zip" \
24374+ "Templates\ItemTemplates\Visual C#\Gendarme Items\Assembly Rule Test.zip" \
24375+ "Templates\ItemTemplates\Visual C#\Gendarme Items\Method Rule.zip" \
24376+ "Templates\ItemTemplates\Visual C#\Gendarme Items\Method Rule Test.zip" \
24377+ "Templates\ItemTemplates\Visual C#\Gendarme Items\Type Rule.zip" \
24378+ "Templates\ItemTemplates\Visual C#\Gendarme Items\Type Rule Test.zip" \
24379+ "Templates\ProjectTemplates\Visual C#\Gendarme Projects\Rule Assembly.zip" \
24380+ "Templates\ProjectTemplates\Visual C#\Gendarme Projects\Rule Test Assembly.zip"
24381+ rmdir temp
24382+
24383+gendarme-vsnet-templates.zip: vsnet
24384+
24385+all: gendarme-vsnet-templates.zip
24386+
24387+clean:
24388+ rm -f *.zip
24389+ rm -rf temp
24390+
24391diff --git a/gendarme/tools/supported/templates/MethodRule.cs b/gendarme/tools/supported/templates/MethodRule.cs
24392new file mode 100644
24393index 0000000..bd0911a
24394--- /dev/null
24395+++ b/gendarme/tools/supported/templates/MethodRule.cs
24396@@ -0,0 +1,65 @@
24397+//
24398+// $rootnamespace$.$safeitemname$
24399+//
24400+// Authors:
24401+// $name$ <$email$>
24402+//
24403+// Copyright (C) $year$ $name$
24404+//
24405+// Permission is hereby granted, free of charge, to any person obtaining a copy
24406+// of this software and associated documentation files (the "Software"), to deal
24407+// in the Software without restriction, including without limitation the rights
24408+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24409+// copies of the Software, and to permit persons to whom the Software is
24410+// furnished to do so, subject to the following conditions:
24411+//
24412+// The above copyright notice and this permission notice shall be included in
24413+// all copies or substantial portions of the Software.
24414+//
24415+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24416+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24417+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24418+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24419+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24420+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24421+// THE SOFTWARE.
24422+
24423+using System;
24424+
24425+using Mono.Cecil;
24426+using Mono.Cecil.Cil;
24427+
24428+using Gendarme.Framework;
24429+using Gendarme.Framework.Engines;
24430+using Gendarme.Framework.Helpers;
24431+using Gendarme.Framework.Rocks;
24432+
24433+namespace $rootnamespace$ {
24434+
24435+ /// <summary>
24436+ /// TODO: Add a summary of the rule.
24437+ /// </summary>
24438+ /// <example>
24439+ /// Bad example:
24440+ /// <code>
24441+ /// TODO: Add an example where the rule would fail.
24442+ /// </code>
24443+ /// </example>
24444+ /// <example>
24445+ /// Good example:
24446+ /// <code>
24447+ /// TODO: Show how to fix the bad example.
24448+ /// </code>
24449+ /// </example>
24450+
24451+ // TODO: Describe the problem and solution
24452+ [Problem ("")]
24453+ [Solution ("")]
24454+ public class $safeitemname$ : Rule, IMethodRule {
24455+ public RuleResult CheckMethod (MethodDefinition method)
24456+ {
24457+ // TODO: Write the rule.
24458+ return RuleResult.Success;
24459+ }
24460+ }
24461+}
24462diff --git a/gendarme/tools/supported/templates/MethodRule.vstemplate b/gendarme/tools/supported/templates/MethodRule.vstemplate
24463new file mode 100644
24464index 0000000..5942dbd
24465--- /dev/null
24466+++ b/gendarme/tools/supported/templates/MethodRule.vstemplate
24467@@ -0,0 +1,24 @@
24468+<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">\r
24469+ <TemplateData>\r
24470+ <DefaultName>Method Rule.cs</DefaultName>\r
24471+ <Name>Method Rule</Name>\r
24472+ <Description>A gendarme rule that checks a method.</Description>\r
24473+ <ProjectType>CSharp</ProjectType>\r
24474+ <SortOrder>10</SortOrder>\r
24475+ <Icon>__TemplateIcon.ico</Icon>\r
24476+ </TemplateData>\r
24477+ <TemplateContent>\r
24478+ <References>\r
24479+ <Reference>\r
24480+ <Assembly>Mono.Cecil</Assembly>\r
24481+ </Reference>\r
24482+ <Reference>\r
24483+ <Assembly>Gendarme.Framework</Assembly>\r
24484+ </Reference>\r
24485+ <Reference>\r
24486+ <Assembly>System.Core</Assembly>\r
24487+ </Reference>\r
24488+ </References>\r
24489+ <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">MethodRule.cs</ProjectItem>\r
24490+ </TemplateContent>\r
24491+</VSTemplate>
24492\ No newline at end of file
24493diff --git a/gendarme/tools/supported/templates/MethodTest.cs b/gendarme/tools/supported/templates/MethodTest.cs
24494new file mode 100644
24495index 0000000..4f70412
24496--- /dev/null
24497+++ b/gendarme/tools/supported/templates/MethodTest.cs
24498@@ -0,0 +1,64 @@
24499+//
24500+// $rootnamespace$.$safeitemname$
24501+//
24502+// Authors:
24503+// $name$ <$email$>
24504+//
24505+// Copyright (C) $year$ $name$
24506+//
24507+// Permission is hereby granted, free of charge, to any person obtaining a copy
24508+// of this software and associated documentation files (the "Software"), to deal
24509+// in the Software without restriction, including without limitation the rights
24510+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24511+// copies of the Software, and to permit persons to whom the Software is
24512+// furnished to do so, subject to the following conditions:
24513+//
24514+// The above copyright notice and this permission notice shall be included in
24515+// all copies or substantial portions of the Software.
24516+//
24517+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24518+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24519+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24520+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24521+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24522+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24523+// THE SOFTWARE.
24524+
24525+using System;
24526+using System.Reflection;
24527+
24528+using Mono.Cecil;
24529+// TODO: Add using for the project of the rule being tested.
24530+// using Gendarme.Rules. ;
24531+
24532+using NUnit.Framework;
24533+using Test.Rules.Fixtures;
24534+using Test.Rules.Helpers;
24535+using Test.Rules.Definitions;
24536+
24537+namespace $rootnamespace$ {
24538+
24539+ [TestFixture]
24540+ public class $safeitemname$ : MethodRuleTestFixture</* TODO: Add rule's type */> {
24541+ [Test]
24542+ public void DoesNotApply ()
24543+ {
24544+ // TODO: Write tests that don't apply.
24545+ // AssertRuleDoesNotApply (method);
24546+ }
24547+
24548+ [Test]
24549+ public void Good ()
24550+ {
24551+ // TODO: Write tests that should succeed.
24552+ // AssertRuleSuccess (method);
24553+ }
24554+
24555+ [Test]
24556+ public void Bad ()
24557+ {
24558+ // TODO: Write tests that should fail.
24559+ // AssertRuleFailure (method);
24560+ }
24561+ }
24562+}
24563diff --git a/gendarme/tools/supported/templates/MethodTest.vstemplate b/gendarme/tools/supported/templates/MethodTest.vstemplate
24564new file mode 100644
24565index 0000000..c9e9cd7
24566--- /dev/null
24567+++ b/gendarme/tools/supported/templates/MethodTest.vstemplate
24568@@ -0,0 +1,27 @@
24569+<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">\r
24570+ <TemplateData>\r
24571+ <DefaultName>Method Rule Test.cs</DefaultName>\r
24572+ <Name>Method Rule Test</Name>\r
24573+ <Description>A unit test for a gendarme method rule.</Description>\r
24574+ <ProjectType>CSharp</ProjectType>\r
24575+ <SortOrder>10</SortOrder>\r
24576+ <Icon>__TemplateIcon.ico</Icon>\r
24577+ </TemplateData>\r
24578+ <TemplateContent>\r
24579+ <References>\r
24580+ <Reference>\r
24581+ <Assembly>Mono.Cecil</Assembly>\r
24582+ </Reference>\r
24583+ <Reference>\r
24584+ <Assembly>Gendarme.Framework</Assembly>\r
24585+ </Reference>\r
24586+ <Reference>\r
24587+ <Assembly>Test.Rules</Assembly>\r
24588+ </Reference>\r
24589+ <Reference>\r
24590+ <Assembly>System.Core</Assembly>\r
24591+ </Reference>\r
24592+ </References>\r
24593+ <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">MethodTest.cs</ProjectItem>\r
24594+ </TemplateContent>\r
24595+</VSTemplate>
24596\ No newline at end of file
24597diff --git a/gendarme/tools/supported/templates/README b/gendarme/tools/supported/templates/README
24598new file mode 100644
24599index 0000000..13a814b
24600--- /dev/null
24601+++ b/gendarme/tools/supported/templates/README
24602@@ -0,0 +1,8 @@
24603+Here are uncompressed C# templates for Gendarme rules, tests and projects.
24604+
24605+To build the compressed templates required by VS.NET (2008/2010) just issue a:
24606+
24607+% make vsnet
24608+
24609+and read the README.vsnet file (also part of the archive).
24610+
24611diff --git a/gendarme/tools/supported/templates/README.vsnet b/gendarme/tools/supported/templates/README.vsnet
24612new file mode 100644
24613index 0000000..9ffcf5e
24614--- /dev/null
24615+++ b/gendarme/tools/supported/templates/README.vsnet
24616@@ -0,0 +1,12 @@
24617+Gendarme Item/Project Templates for Visual Studio
24618+
24619+To Install:
24620+- Extract this file to your My Documents\Visual Studio 20x folder.
24621+- Optionally, open the .vstemplate file in each item template.
24622+ In the <TemplateContent> section, add the following:
24623+ <CustomParameters>
24624+ <CustomParameter Name="$name$" Value="(your name)"/>
24625+ <CustomParameter Name="$email$" Value="(your email)"/>
24626+ </CustomParameters>
24627+ This will allow your name and e-mail address to be automatically
24628+ entered into rules and tests you create.
24629\ No newline at end of file
24630diff --git a/gendarme/tools/supported/templates/Templates.RuleProject.csproj b/gendarme/tools/supported/templates/Templates.RuleProject.csproj
24631new file mode 100644
24632index 0000000..4208f3e
24633--- /dev/null
24634+++ b/gendarme/tools/supported/templates/Templates.RuleProject.csproj
24635@@ -0,0 +1,57 @@
24636+<?xml version="1.0" encoding="utf-8"?>\r
24637+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
24638+ <PropertyGroup>\r
24639+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
24640+ <Platform Condition=" '$(Platform)' == '' ">x86</Platform>\r
24641+ <ProductVersion>8.0.30703</ProductVersion>\r
24642+ <SchemaVersion>2.0</SchemaVersion>\r
24643+ <ProjectGuid>{BDADA65A-2C52-42C3-A7E4-A824FCDF4C9D}</ProjectGuid>\r
24644+ <OutputType>Exe</OutputType>\r
24645+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
24646+ <RootNamespace>$safeprojectname$</RootNamespace>\r
24647+ <AssemblyName>$safeprojectname$</AssemblyName>\r
24648+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
24649+ <TargetFrameworkProfile>Client</TargetFrameworkProfile>\r
24650+ <FileAlignment>512</FileAlignment>\r
24651+ </PropertyGroup>\r
24652+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">\r
24653+ <PlatformTarget>x86</PlatformTarget>\r
24654+ <DebugSymbols>true</DebugSymbols>\r
24655+ <DebugType>full</DebugType>\r
24656+ <Optimize>false</Optimize>\r
24657+ <OutputPath>bin\Debug\</OutputPath>\r
24658+ <DefineConstants>DEBUG;TRACE</DefineConstants>\r
24659+ <ErrorReport>prompt</ErrorReport>\r
24660+ <WarningLevel>4</WarningLevel>\r
24661+ </PropertyGroup>\r
24662+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">\r
24663+ <PlatformTarget>x86</PlatformTarget>\r
24664+ <DebugType>pdbonly</DebugType>\r
24665+ <Optimize>true</Optimize>\r
24666+ <OutputPath>bin\Release\</OutputPath>\r
24667+ <DefineConstants>TRACE</DefineConstants>\r
24668+ <ErrorReport>prompt</ErrorReport>\r
24669+ <WarningLevel>4</WarningLevel>\r
24670+ </PropertyGroup>\r
24671+ <ItemGroup>\r
24672+ <Reference Include="System" />\r
24673+ </ItemGroup>\r
24674+ <ItemGroup>\r
24675+ <ProjectReference Include="..\..\..\cecil\Mono.Cecil.csproj">\r
24676+ <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
24677+ <Name>Mono.Cecil</Name>\r
24678+ </ProjectReference>\r
24679+ <ProjectReference Include="..\framework\Gendarme.Framework.csproj">\r
24680+ <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>\r
24681+ <Name>Gendarme.Framework</Name>\r
24682+ </ProjectReference>\r
24683+ </ItemGroup>\r
24684+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
24685+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
24686+ Other similar extension points exist, see Microsoft.Common.targets.\r
24687+ <Target Name="BeforeBuild">\r
24688+ </Target>\r
24689+ <Target Name="AfterBuild">\r
24690+ </Target>\r
24691+ -->\r
24692+</Project>
24693\ No newline at end of file
24694diff --git a/gendarme/tools/supported/templates/Templates.RuleProject.vstemplate b/gendarme/tools/supported/templates/Templates.RuleProject.vstemplate
24695new file mode 100644
24696index 0000000..41afb51
24697--- /dev/null
24698+++ b/gendarme/tools/supported/templates/Templates.RuleProject.vstemplate
24699@@ -0,0 +1,19 @@
24700+<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">\r
24701+ <TemplateData>\r
24702+ <Name>Rule Assembly</Name>\r
24703+ <Description>An assembly containing gendarme rules.</Description>\r
24704+ <ProjectType>CSharp</ProjectType>\r
24705+ <ProjectSubType>\r
24706+ </ProjectSubType>\r
24707+ <SortOrder>1000</SortOrder>\r
24708+ <CreateNewFolder>true</CreateNewFolder>\r
24709+ <DefaultName>Rule Assembly</DefaultName>\r
24710+ <ProvideDefaultName>true</ProvideDefaultName>\r
24711+ <LocationField>Enabled</LocationField>\r
24712+ <EnableLocationBrowseButton>true</EnableLocationBrowseButton>\r
24713+ <Icon>__TemplateIcon.ico</Icon>\r
24714+ </TemplateData>\r
24715+ <TemplateContent>\r
24716+ <Project TargetFileName="Templates.RuleProject.csproj" File="Templates.RuleProject.csproj" ReplaceParameters="true" />\r
24717+ </TemplateContent>\r
24718+</VSTemplate>
24719\ No newline at end of file
24720diff --git a/gendarme/tools/supported/templates/Templates.TestProject.csproj b/gendarme/tools/supported/templates/Templates.TestProject.csproj
24721new file mode 100644
24722index 0000000..6dd3298
24723--- /dev/null
24724+++ b/gendarme/tools/supported/templates/Templates.TestProject.csproj
24725@@ -0,0 +1,62 @@
24726+<?xml version="1.0" encoding="utf-8"?>\r
24727+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
24728+ <PropertyGroup>\r
24729+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
24730+ <Platform Condition=" '$(Platform)' == '' ">x86</Platform>\r
24731+ <ProductVersion>8.0.30703</ProductVersion>\r
24732+ <SchemaVersion>2.0</SchemaVersion>\r
24733+ <ProjectGuid>{0B35C07C-19E8-40D0-8634-FE3929DBB8C7}</ProjectGuid>\r
24734+ <OutputType>Exe</OutputType>\r
24735+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
24736+ <RootNamespace>$safeprojectname$</RootNamespace>\r
24737+ <AssemblyName>$safeprojectname$</AssemblyName>\r
24738+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
24739+ <TargetFrameworkProfile>Client</TargetFrameworkProfile>\r
24740+ <FileAlignment>512</FileAlignment>\r
24741+ </PropertyGroup>\r
24742+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">\r
24743+ <PlatformTarget>x86</PlatformTarget>\r
24744+ <DebugSymbols>true</DebugSymbols>\r
24745+ <DebugType>full</DebugType>\r
24746+ <Optimize>false</Optimize>\r
24747+ <OutputPath>bin\Debug\</OutputPath>\r
24748+ <DefineConstants>DEBUG;TRACE</DefineConstants>\r
24749+ <ErrorReport>prompt</ErrorReport>\r
24750+ <WarningLevel>4</WarningLevel>\r
24751+ </PropertyGroup>\r
24752+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">\r
24753+ <PlatformTarget>x86</PlatformTarget>\r
24754+ <DebugType>pdbonly</DebugType>\r
24755+ <Optimize>true</Optimize>\r
24756+ <OutputPath>bin\Release\</OutputPath>\r
24757+ <DefineConstants>TRACE</DefineConstants>\r
24758+ <ErrorReport>prompt</ErrorReport>\r
24759+ <WarningLevel>4</WarningLevel>\r
24760+ </PropertyGroup>\r
24761+ <ItemGroup>\r
24762+ <ProjectReference Include="..\..\..\cecil\Mono.Cecil.csproj">\r
24763+ <Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project>\r
24764+ <Name>Mono.Cecil</Name>\r
24765+ </ProjectReference>\r
24766+ <ProjectReference Include="..\framework\Gendarme.Framework.csproj">\r
24767+ <Project>{CD6818D5-B398-486C-B180-92A07B143AFD}</Project>\r
24768+ <Name>Gendarme.Framework</Name>\r
24769+ </ProjectReference>\r
24770+ <ProjectReference Include="..\rules\Test.Rules\Test.Rules.csproj">\r
24771+ <Project>{069148AF-86AB-4EE3-BFB9-429AE722461F}</Project>\r
24772+ <Name>Test.Rules</Name>\r
24773+ </ProjectReference>\r
24774+ </ItemGroup>\r
24775+ <ItemGroup>\r
24776+ <Reference Include="nunit.framework, Version=2.5.3.9345, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" />\r
24777+ <Reference Include="System" />\r
24778+ </ItemGroup>\r
24779+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
24780+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
24781+ Other similar extension points exist, see Microsoft.Common.targets.\r
24782+ <Target Name="BeforeBuild">\r
24783+ </Target>\r
24784+ <Target Name="AfterBuild">\r
24785+ </Target>\r
24786+ -->\r
24787+</Project>
24788\ No newline at end of file
24789diff --git a/gendarme/tools/supported/templates/Templates.TestProject.vstemplate b/gendarme/tools/supported/templates/Templates.TestProject.vstemplate
24790new file mode 100644
24791index 0000000..2d87449
24792--- /dev/null
24793+++ b/gendarme/tools/supported/templates/Templates.TestProject.vstemplate
24794@@ -0,0 +1,19 @@
24795+<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">\r
24796+ <TemplateData>\r
24797+ <Name>Rule Test Assembly</Name>\r
24798+ <Description>An assembly of unit tests for gendarme rules.</Description>\r
24799+ <ProjectType>CSharp</ProjectType>\r
24800+ <ProjectSubType>\r
24801+ </ProjectSubType>\r
24802+ <SortOrder>1000</SortOrder>\r
24803+ <CreateNewFolder>true</CreateNewFolder>\r
24804+ <DefaultName>Rule Test Assembly</DefaultName>\r
24805+ <ProvideDefaultName>true</ProvideDefaultName>\r
24806+ <LocationField>Enabled</LocationField>\r
24807+ <EnableLocationBrowseButton>true</EnableLocationBrowseButton>\r
24808+ <Icon>__TemplateIcon.ico</Icon>\r
24809+ </TemplateData>\r
24810+ <TemplateContent>\r
24811+ <Project TargetFileName="Templates.TestProject.csproj" File="Templates.TestProject.csproj" ReplaceParameters="true" />\r
24812+ </TemplateContent>\r
24813+</VSTemplate>
24814\ No newline at end of file
24815diff --git a/gendarme/tools/supported/templates/TypeRule.cs b/gendarme/tools/supported/templates/TypeRule.cs
24816new file mode 100644
24817index 0000000..fce1256
24818--- /dev/null
24819+++ b/gendarme/tools/supported/templates/TypeRule.cs
24820@@ -0,0 +1,65 @@
24821+//
24822+// $rootnamespace$.$safeitemname$
24823+//
24824+// Authors:
24825+// $name$ <$email$>
24826+//
24827+// Copyright (C) $year$ $name$
24828+//
24829+// Permission is hereby granted, free of charge, to any person obtaining a copy
24830+// of this software and associated documentation files (the "Software"), to deal
24831+// in the Software without restriction, including without limitation the rights
24832+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24833+// copies of the Software, and to permit persons to whom the Software is
24834+// furnished to do so, subject to the following conditions:
24835+//
24836+// The above copyright notice and this permission notice shall be included in
24837+// all copies or substantial portions of the Software.
24838+//
24839+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24840+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24841+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24842+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24843+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24844+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24845+// THE SOFTWARE.
24846+
24847+using System;
24848+
24849+using Mono.Cecil;
24850+using Mono.Cecil.Cil;
24851+
24852+using Gendarme.Framework;
24853+using Gendarme.Framework.Engines;
24854+using Gendarme.Framework.Helpers;
24855+using Gendarme.Framework.Rocks;
24856+
24857+namespace $rootnamespace$ {
24858+
24859+ /// <summary>
24860+ /// TODO: Add a summary of the rule.
24861+ /// </summary>
24862+ /// <example>
24863+ /// Bad example:
24864+ /// <code>
24865+ /// TODO: Add an example where the rule would fail.
24866+ /// </code>
24867+ /// </example>
24868+ /// <example>
24869+ /// Good example:
24870+ /// <code>
24871+ /// TODO: Show how to fix the bad example.
24872+ /// </code>
24873+ /// </example>
24874+
24875+ // TODO: Describe the problem and solution
24876+ [Problem ("")]
24877+ [Solution ("")]
24878+ public class $safeitemname$ : Rule, ITypeRule {
24879+ public RuleResult CheckType (TypeDefinition type)
24880+ {
24881+ // TODO: Write the rule.
24882+ return RuleResult.Success;
24883+ }
24884+ }
24885+}
24886diff --git a/gendarme/tools/supported/templates/TypeRule.vstemplate b/gendarme/tools/supported/templates/TypeRule.vstemplate
24887new file mode 100644
24888index 0000000..3a0e9c1
24889--- /dev/null
24890+++ b/gendarme/tools/supported/templates/TypeRule.vstemplate
24891@@ -0,0 +1,24 @@
24892+<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">\r
24893+ <TemplateData>\r
24894+ <DefaultName>Type Rule.cs</DefaultName>\r
24895+ <Name>Type Rule</Name>\r
24896+ <Description>A gendarme rule that checks a type.</Description>\r
24897+ <ProjectType>CSharp</ProjectType>\r
24898+ <SortOrder>10</SortOrder>\r
24899+ <Icon>__TemplateIcon.ico</Icon>\r
24900+ </TemplateData>\r
24901+ <TemplateContent>\r
24902+ <References>\r
24903+ <Reference>\r
24904+ <Assembly>Mono.Cecil</Assembly>\r
24905+ </Reference>\r
24906+ <Reference>\r
24907+ <Assembly>Gendarme.Framework</Assembly>\r
24908+ </Reference>\r
24909+ <Reference>\r
24910+ <Assembly>System.Core</Assembly>\r
24911+ </Reference>\r
24912+ </References>\r
24913+ <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">TypeRule.cs</ProjectItem>\r
24914+ </TemplateContent>\r
24915+</VSTemplate>
24916\ No newline at end of file
24917diff --git a/gendarme/tools/supported/templates/TypeTest.cs b/gendarme/tools/supported/templates/TypeTest.cs
24918new file mode 100644
24919index 0000000..92af871
24920--- /dev/null
24921+++ b/gendarme/tools/supported/templates/TypeTest.cs
24922@@ -0,0 +1,64 @@
24923+//
24924+// $rootnamespace$.$safeitemname$
24925+//
24926+// Authors:
24927+// $name$ <$email$>
24928+//
24929+// Copyright (C) $year$ $name$
24930+//
24931+// Permission is hereby granted, free of charge, to any person obtaining a copy
24932+// of this software and associated documentation files (the "Software"), to deal
24933+// in the Software without restriction, including without limitation the rights
24934+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24935+// copies of the Software, and to permit persons to whom the Software is
24936+// furnished to do so, subject to the following conditions:
24937+//
24938+// The above copyright notice and this permission notice shall be included in
24939+// all copies or substantial portions of the Software.
24940+//
24941+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24942+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24943+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24944+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24945+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24946+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24947+// THE SOFTWARE.
24948+
24949+using System;
24950+using System.Reflection;
24951+
24952+using Mono.Cecil;
24953+// TODO: Add using for the project of the rule being tested.
24954+// using Gendarme.Rules. ;
24955+
24956+using NUnit.Framework;
24957+using Test.Rules.Fixtures;
24958+using Test.Rules.Helpers;
24959+using Test.Rules.Definitions;
24960+
24961+namespace $rootnamespace$ {
24962+
24963+ [TestFixture]
24964+ public class $safeitemname$ : TypeRuleTestFixture</* TODO: Add rule's type */> {
24965+ [Test]
24966+ public void DoesNotApply ()
24967+ {
24968+ // TODO: Write tests that don't apply.
24969+ // AssertRuleDoesNotApply<type> ();
24970+ }
24971+
24972+ [Test]
24973+ public void Good ()
24974+ {
24975+ // TODO: Write tests that should succeed.
24976+ // AssertRuleSuccess<type> ();
24977+ }
24978+
24979+ [Test]
24980+ public void Bad ()
24981+ {
24982+ // TODO: Write tests that should fail.
24983+ // AssertRuleFailure<type> ();
24984+ }
24985+ }
24986+}
24987diff --git a/gendarme/tools/supported/templates/TypeTest.vstemplate b/gendarme/tools/supported/templates/TypeTest.vstemplate
24988new file mode 100644
24989index 0000000..2e0c866
24990--- /dev/null
24991+++ b/gendarme/tools/supported/templates/TypeTest.vstemplate
24992@@ -0,0 +1,27 @@
24993+<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">\r
24994+ <TemplateData>\r
24995+ <DefaultName>Type Rule Test.cs</DefaultName>\r
24996+ <Name>Type Rule Test</Name>\r
24997+ <Description>A unit test for a gendarme type rule.</Description>\r
24998+ <ProjectType>CSharp</ProjectType>\r
24999+ <SortOrder>10</SortOrder>\r
25000+ <Icon>__TemplateIcon.ico</Icon>\r
25001+ </TemplateData>\r
25002+ <TemplateContent>\r
25003+ <References>\r
25004+ <Reference>\r
25005+ <Assembly>Mono.Cecil</Assembly>\r
25006+ </Reference>\r
25007+ <Reference>\r
25008+ <Assembly>Gendarme.Framework</Assembly>\r
25009+ </Reference>\r
25010+ <Reference>\r
25011+ <Assembly>Test.Rules</Assembly>\r
25012+ </Reference>\r
25013+ <Reference>\r
25014+ <Assembly>System.Core</Assembly>\r
25015+ </Reference>\r
25016+ </References>\r
25017+ <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">TypeTest.cs</ProjectItem>\r
25018+ </TemplateContent>\r
25019+</VSTemplate>
25020\ No newline at end of file
25021diff --git a/gendarme/tools/unsupported/mapper/FxCopMapBuilder.cs b/gendarme/tools/unsupported/mapper/FxCopMapBuilder.cs
25022index 7d2eee2..c62919f 100644
25023--- a/gendarme/tools/unsupported/mapper/FxCopMapBuilder.cs
25024+++ b/gendarme/tools/unsupported/mapper/FxCopMapBuilder.cs
25025@@ -222,7 +222,8 @@ namespace FxCopMapBuilder {
25026 idName [0], idName [1], rule.Attribute ("category").Value);
25027 }
25028 if (rule.Attribute ("type").Value == "gendarme") {
25029- return String.Format ("[[{0}]]", rule.Attribute ("id").Value);
25030+ return String.Format ("[[{1}|{0}.{1}{2}]]", rule.Attribute ("category").Value,
25031+ rule.Attribute ("id").Value, "(2.10)");
25032 }
25033 return String.Empty;
25034 }
25035diff --git a/gendarme/tools/unsupported/mapper/Makefile.am b/gendarme/tools/unsupported/mapper/Makefile.am
25036index a283bee..ae79ba4 100644
25037--- a/gendarme/tools/unsupported/mapper/Makefile.am
25038+++ b/gendarme/tools/unsupported/mapper/Makefile.am
25039@@ -7,7 +7,7 @@ mapper_sources = \
25040 FxCopRule.cs
25041
25042 mapper.exe: $(mapper_sources)
25043- $(GMCS) -debug $^ -out:$@ -r:System.Xml.Linq.dll -r:$(CECIL_ASM)
25044+ $(MCS) -debug $^ -out:$@ -r:System.Xml.Linq.dll -r:$(CECIL_ASM)
25045
25046 clean:
25047 rm -f mapper.exe*
25048diff --git a/gendarme/tools/unsupported/mapper/fxcop.missing b/gendarme/tools/unsupported/mapper/fxcop.missing
25049index 556c2fc..919df45 100644
25050--- a/gendarme/tools/unsupported/mapper/fxcop.missing
25051+++ b/gendarme/tools/unsupported/mapper/fxcop.missing
25052@@ -3,7 +3,6 @@ CA1025 Replace repetitive arguments with params array
25053 CA1026 Default parameters should not be used http://msdn.microsoft.com/en-us/library/ms182135.aspx
25054 CA1033 Interface methods should be callable by child types http://msdn.microsoft.com/en-us/library/ms182153.aspx
25055 CA1046 Do not overload operator equals on reference types http://msdn.microsoft.com/en-us/library/ms182145.aspx
25056-CA1052 Static holder types should be sealed http://msdn.microsoft.com/en-us/library/ms182168.aspx
25057 CA1058 Types should not extend certain base types http://msdn.microsoft.com/en-us/library/ms182171.aspx
25058 CA1061 Do not hide base class methods http://msdn.microsoft.com/en-us/library/ms182143.aspx
25059 CA1063 Implement IDisposable correctly http://msdn.microsoft.com/en-us/library/ms244737.aspx
25060@@ -14,10 +13,7 @@ CA1300 Specify MessageBoxOptions
25061 CA1301 Avoid duplicate accelerators http://msdn.microsoft.com/en-us/library/ms182185.aspx
25062 CA1302 Do not hardcode locale specific strings http://msdn.microsoft.com/en-us/library/ms182186.aspx
25063 CA1303 Do not pass literals as localized parameters http://msdn.microsoft.com/en-us/library/ms182187.aspx
25064-CA1304 Specify CultureInfo http://msdn.microsoft.com/en-us/library/ms182189.aspx
25065-CA1305 Specify IFormatProvider http://msdn.microsoft.com/en-us/library/ms182190.aspx
25066 CA1306 Set locale for data types http://msdn.microsoft.com/en-us/library/ms182188.aspx
25067-CA1307 Specify StringComparison http://msdn.microsoft.com/en-us/library/bb386080.aspx
25068 CA1308 Normalize strings to uppercase http://msdn.microsoft.com/en-us/library/bb386042.aspx
25069 CA1309 Use ordinal StringComparison http://msdn.microsoft.com/en-us/library/bb385972.aspx
25070
25071@@ -40,7 +36,6 @@ CA1717 Only FlagsAttribute enums should have plural names
25072 CA1719 Parameter names should not match member names http://msdn.microsoft.com/en-us/library/ms182252.aspx
25073 CA1720 Identifiers should not contain type names http://msdn.microsoft.com/en-us/library/bb531486.aspx
25074 CA1721 Property names should not match get methods http://msdn.microsoft.com/en-us/library/ms182253.aspx
25075-CA1724 Type Names Should Not Match Namespaces http://msdn.microsoft.com/en-us/library/ms182257.aspx
25076
25077 Microsoft.Performance
25078 CA1810 Initialize reference type static fields inline http://msdn.microsoft.com/en-us/library/ms182275.aspx
25079@@ -97,9 +92,6 @@ CA2207 Initialize value type static fields inline
25080 CA2212 Do not mark serviced components with WebMethod http://msdn.microsoft.com/en-us/library/ms182336.aspx
25081 CA2215 Dispose methods should call base class dispose http://msdn.microsoft.com/en-us/library/ms182330.aspx
25082 CA2217 Do not mark enums with FlagsAttribute http://msdn.microsoft.com/en-us/library/ms182335.aspx
25083-CA2219 Do not raise exceptions in exception clauses http://msdn.microsoft.com/en-us/library/bb386041.aspx
25084-CA2222 Do not decrease inherited member visibility http://msdn.microsoft.com/en-us/library/ms182332.aspx
25085 CA2223 Members should differ by more than return type http://msdn.microsoft.com/en-us/library/ms182352.aspx
25086-CA2227 Collection properties should be read only http://msdn.microsoft.com/en-us/library/ms182327.aspx
25087 CA2228 Do not ship unreleased resource formats http://msdn.microsoft.com/en-us/library/ms182339.aspx
25088 CA2233 Operations should not overflow http://msdn.microsoft.com/en-us/library/ms182354.aspx
25089diff --git a/gendarme/tools/unsupported/typeref/Makefile.am b/gendarme/tools/unsupported/typeref/Makefile.am
25090index 436189e..e1ba4d3 100644
25091--- a/gendarme/tools/unsupported/typeref/Makefile.am
25092+++ b/gendarme/tools/unsupported/typeref/Makefile.am
25093@@ -6,7 +6,7 @@ typeref_sources = \
25094 typeref.cs
25095
25096 typeref.exe: $(typeref_sources)
25097- $(GMCS) -debug $^ -out:$@ -r:$(CECIL_ASM)
25098+ $(MCS) -debug $^ -out:$@ -r:$(CECIL_ASM)
25099
25100 clean:
25101 rm -f typeref.exe*
25102diff --git a/gendarme/tools/unsupported/typeref/typeref.csproj b/gendarme/tools/unsupported/typeref/typeref.csproj
25103index 25854ee..09d805d 100644
25104--- a/gendarme/tools/unsupported/typeref/typeref.csproj
25105+++ b/gendarme/tools/unsupported/typeref/typeref.csproj
25106@@ -1,5 +1,5 @@
25107 <?xml version="1.0" encoding="utf-8"?>\r
25108-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
25109+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
25110 <PropertyGroup>\r
25111 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
25112 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
25113@@ -10,8 +10,28 @@
25114 <AppDesignerFolder>Properties</AppDesignerFolder>\r
25115 <RootNamespace>typeref</RootNamespace>\r
25116 <AssemblyName>typeref</AssemblyName>\r
25117- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
25118+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
25119 <FileAlignment>512</FileAlignment>\r
25120+ <FileUpgradeFlags>\r
25121+ </FileUpgradeFlags>\r
25122+ <OldToolsVersion>3.5</OldToolsVersion>\r
25123+ <UpgradeBackupLocation />\r
25124+ <PublishUrl>publish\</PublishUrl>\r
25125+ <Install>true</Install>\r
25126+ <InstallFrom>Disk</InstallFrom>\r
25127+ <UpdateEnabled>false</UpdateEnabled>\r
25128+ <UpdateMode>Foreground</UpdateMode>\r
25129+ <UpdateInterval>7</UpdateInterval>\r
25130+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
25131+ <UpdatePeriodically>false</UpdatePeriodically>\r
25132+ <UpdateRequired>false</UpdateRequired>\r
25133+ <MapFileExtensions>true</MapFileExtensions>\r
25134+ <ApplicationRevision>0</ApplicationRevision>\r
25135+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
25136+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
25137+ <UseApplicationTrust>false</UseApplicationTrust>\r
25138+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
25139+ <TargetFrameworkProfile />\r
25140 </PropertyGroup>\r
25141 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
25142 <DebugSymbols>true</DebugSymbols>\r
25143@@ -21,6 +41,7 @@
25144 <DefineConstants>DEBUG;TRACE</DefineConstants>\r
25145 <ErrorReport>prompt</ErrorReport>\r
25146 <WarningLevel>4</WarningLevel>\r
25147+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
25148 </PropertyGroup>\r
25149 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
25150 <DebugType>pdbonly</DebugType>\r
25151@@ -29,6 +50,7 @@
25152 <DefineConstants>TRACE</DefineConstants>\r
25153 <ErrorReport>prompt</ErrorReport>\r
25154 <WarningLevel>4</WarningLevel>\r
25155+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
25156 </PropertyGroup>\r
25157 <ItemGroup>\r
25158 <Reference Include="System" />\r
25159@@ -51,6 +73,23 @@
25160 <ItemGroup>\r
25161 <Folder Include="Properties\" />\r
25162 </ItemGroup>\r
25163+ <ItemGroup>\r
25164+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
25165+ <Visible>False</Visible>\r
25166+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
25167+ <Install>false</Install>\r
25168+ </BootstrapperPackage>\r
25169+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
25170+ <Visible>False</Visible>\r
25171+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
25172+ <Install>true</Install>\r
25173+ </BootstrapperPackage>\r
25174+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
25175+ <Visible>False</Visible>\r
25176+ <ProductName>Windows Installer 3.1</ProductName>\r
25177+ <Install>true</Install>\r
25178+ </BootstrapperPackage>\r
25179+ </ItemGroup>\r
25180 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
25181 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
25182 Other similar extension points exist, see Microsoft.Common.targets.
25183diff --git a/gendarme/tools/unsupported/xmldoc2wiki/Makefile.am b/gendarme/tools/unsupported/xmldoc2wiki/Makefile.am
25184index ff0167b..55fb249 100644
25185--- a/gendarme/tools/unsupported/xmldoc2wiki/Makefile.am
25186+++ b/gendarme/tools/unsupported/xmldoc2wiki/Makefile.am
25187@@ -6,7 +6,7 @@ xmldoc2wiki_sources = \
25188 xmldoc2wiki.cs
25189
25190 xmldoc2wiki.exe: $(xmldoc2wiki_sources)
25191- $(GMCS) -debug $^ -out:$@ -r:System.Xml.Linq.dll
25192+ $(MCS) -debug $^ -out:$@ -r:System.Xml.Linq.dll
25193
25194 clean:
25195 rm -f xmldoc2wiki.exe*
25196diff --git a/gendarme/tools/unsupported/xmldoc2wiki/README b/gendarme/tools/unsupported/xmldoc2wiki/README
25197index 764df91..ce17af9 100644
25198--- a/gendarme/tools/unsupported/xmldoc2wiki/README
25199+++ b/gendarme/tools/unsupported/xmldoc2wiki/README
25200@@ -11,5 +11,16 @@ Examples:
25201 xmldoc2wiki bin/*.xml 2-8-doc
25202
25203 Local wiki access:
25204- You can access the wiki locally by using github's gollum: https://github.com/github/gollum#readme
25205- The installation is pretty simple, don't forget to install rdiscount gem that provides Markdown support.
25206+
25207+ a) Install gollum (https://github.com/github/gollum#readme). This requires Ruby.
25208+
25209+ % gem install gollum
25210+
25211+ b) Install rdiscount (http://daringfireball.net/projects/markdown/) for Markdown support
25212+
25213+ % gem install rdiscount
25214+
25215+ c) Install Pygments (http://pygments.org/) for syntax highlightning. This requires Python.
25216+
25217+ % easy_install Pygments
25218+
25219diff --git a/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.cs b/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.cs
25220index 4fbca7f..5fbc2dd 100644
25221--- a/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.cs
25222+++ b/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.cs
25223@@ -1,3 +1,31 @@
25224+//
25225+// Gendarme's xmldoc2wiki tool
25226+//
25227+// Authors:
25228+// Sebastien Pouliot <sebastien@ximian.com>
25229+// Yuri Stuken <stuken.yuri@gmail.com>
25230+//
25231+// Copyright (C) 2010-2011 Novell, Inc (http://www.novell.com)
25232+// Copyright (C) 2010 Yuri Stuken
25233+//
25234+// Permission is hereby granted, free of charge, to any person obtaining a copy
25235+// of this software and associated documentation files (the "Software"), to deal
25236+// in the Software without restriction, including without limitation the rights
25237+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
25238+// copies of the Software, and to permit persons to whom the Software is
25239+// furnished to do so, subject to the following conditions:
25240+//
25241+// The above copyright notice and this permission notice shall be included in
25242+// all copies or substantial portions of the Software.
25243+//
25244+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25245+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25246+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25247+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25248+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25249+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25250+// THE SOFTWARE.
25251+
25252 using System;
25253 using System.IO;
25254 using System.Collections.Generic;
25255@@ -11,6 +39,7 @@ static class Program {
25256 static HashSet<string> assembliesIndex = new HashSet<string> ();
25257
25258 static string outputdir;
25259+ static string version = "git";
25260
25261 static string CleanUp (this string s)
25262 {
25263@@ -18,20 +47,6 @@ static class Program {
25264 return Regex.Replace (s, @"([\`\*])", @"\$1");
25265 }
25266
25267- static void Header (TextWriter tw)
25268- {
25269- // tw.WriteLine ("# Rules");
25270- // tw.WriteLine ();
25271- }
25272-
25273- static void Footer (TextWriter tw)
25274- {
25275- tw.WriteLine (@"## Feedback
25276-
25277-Please report any documentation errors, typos or suggestions to the
25278-[[Gendarme Google Group|http://groups.google.com/group/gendarme]]. Thanks!");
25279- }
25280-
25281 static void AppendIndentedLine (StringBuilder sb, string line, int indentation)
25282 {
25283 for (int i = 0; i < indentation; i++)
25284@@ -168,6 +183,7 @@ Please report any documentation errors, typos or suggestions to the
25285 ProcessText (tw, description.Nodes ());
25286 }
25287 tw.AppendLine ();
25288+ tw.AppendLine (); // make sure the following text is not part of the last item on the list
25289 }
25290
25291 static void ProcessRules (IEnumerable<XElement> rules, string assembly)
25292@@ -207,83 +223,104 @@ Please report any documentation errors, typos or suggestions to the
25293
25294 rulesIndex.Add (name);
25295
25296- TextWriter writer = File.CreateText (Path.Combine(Path.Combine(outputdir, assembly), Path.ChangeExtension (name, "md")));
25297- Header (writer);
25298-
25299- rsb.AppendFormat ("# {0}", name);
25300- rsb.AppendFormat ("{1}**{0}**{1}{1}", assembly, Environment.NewLine);
25301- rsb.AppendLine ("## Description");
25302-
25303- // tw.WriteLine (ProcessSummary (item));
25304- ProcessText (rsb, item.Nodes ());
25305- rsb.AppendLine ();
25306- rsb.AppendLine ();
25307-
25308- var examples = member.Elements ("example");
25309- if (examples != null)
25310- rsb.AppendLine ("## Examples");
25311- foreach (XNode example in examples.Nodes ()) {
25312- XText node = (example as XText);
25313- if (node != null) {
25314- string text = example.ToString ().CleanUp ().Replace ("Bad", "**Bad**");
25315- text = text.Replace ("Good", "**Good**");
25316- rsb.AppendFormat ("{0}{1}{1}", text.Trim (), Environment.NewLine);
25317- continue;
25318- }
25319+ string rule_file = String.Format ("{0}{1}{2}{1}{3}.{4}({2}).md",
25320+ outputdir, Path.DirectorySeparatorChar, version, assembly, name);
25321+ using (TextWriter writer = File.CreateText (rule_file)) {
25322+ rsb.AppendFormat ("# {0}{1}{1}", name, Environment.NewLine);
25323+ rsb.AppendFormat ("Assembly: **[[{0}|{0}({1})]]**<br/>", assembly, version);
25324+ rsb.AppendFormat ("Version: **{0}**{1}{1}", version, Environment.NewLine);
25325+ rsb.AppendLine ("## Description");
25326+
25327+ // tw.WriteLine (ProcessSummary (item));
25328+ ProcessText (rsb, item.Nodes ());
25329+ rsb.AppendLine ();
25330+ rsb.AppendLine ();
25331+
25332+ var examples = member.Elements ("example");
25333+ if (examples != null)
25334+ rsb.AppendLine ("## Examples");
25335+ foreach (XNode example in examples.Nodes ()) {
25336+ XText node = (example as XText);
25337+ if (node != null) {
25338+ string text = example.ToString ().CleanUp ().Replace ("Bad", "**Bad**");
25339+ text = text.Replace ("Good", "**Good**");
25340+ rsb.AppendFormat ("{0}{1}{1}", text.Trim (), Environment.NewLine);
25341+ continue;
25342+ }
25343+
25344+ XElement code = (example as XElement);
25345+ if (code == null)
25346+ continue;
25347
25348- XElement code = (example as XElement);
25349- if (code == null)
25350- continue;
25351-
25352- switch (code.Name.LocalName) {
25353- case "code":
25354- rsb.AppendFormat ("```csharp{1}{0}{1}```{1}{1}", ProcessCode (code.Value),
25355- Environment.NewLine);
25356- break;
25357- case "c":
25358- rsb.AppendFormat (" {0}{1}{1}", code.Value, Environment.NewLine);
25359- break;
25360+ switch (code.Name.LocalName) {
25361+ case "code":
25362+ rsb.AppendFormat ("```csharp{1}{0}{1}```{1}{1}", ProcessCode (code.Value),
25363+ Environment.NewLine);
25364+ break;
25365+ case "c":
25366+ rsb.AppendFormat (" {0}{1}{1}", code.Value, Environment.NewLine);
25367+ break;
25368+ }
25369 }
25370- }
25371
25372- XElement container = member.Element ("remarks");
25373- if (container != null) {
25374- IEnumerable<XNode> remarks = container.Nodes ();
25375- if (remarks.Count () > 0) {
25376- rsb.AppendFormat ("## Notes{0}{0}", Environment.NewLine);
25377- rsb.Append ("* ");
25378+ XElement container = member.Element ("remarks");
25379+ if (container != null) {
25380+ IEnumerable<XNode> remarks = container.Nodes ();
25381+ if (remarks.Count () > 0) {
25382+ rsb.AppendFormat ("## Notes{0}{0}", Environment.NewLine);
25383+ rsb.Append ("* ");
25384
25385- ProcessText (rsb, remarks);
25386+ ProcessText (rsb, remarks);
25387+ rsb.AppendLine ();
25388+ }
25389+ }
25390+
25391+ StringBuilder psb;
25392+ if (properties.TryGetValue (name, out psb)) {
25393+ rsb.AppendFormat ("## Configuration{0}{0}", Environment.NewLine);
25394+ rsb.AppendFormat ("Some elements of this rule can be customized to better fit your needs.{0}{0}", Environment.NewLine);
25395+ rsb.Append (psb);
25396 rsb.AppendLine ();
25397 }
25398- }
25399
25400- StringBuilder psb;
25401- if (properties.TryGetValue (name, out psb)) {
25402- rsb.AppendFormat ("## Configuration{0}{0}", Environment.NewLine);
25403- rsb.AppendFormat ("Some elements of this rule can be customized to better fit your needs.{0}{0}", Environment.NewLine);
25404- rsb.Append (psb);
25405- rsb.AppendLine ();
25406- }
25407+ writer.WriteLine (rsb);
25408
25409- writer.WriteLine (rsb);
25410+ if (version == "git") {
25411+ writer.WriteLine ();
25412+ writer.WriteLine (@"## Source code
25413
25414- Footer (writer);
25415- writer.Close ();
25416+You can browse the latest [[source code|https://github.com/mono/mono-tools/tree/master/gendarme/rules/{0}/{1}.cs]] of this rule on github.com", assembly, name);
25417+ }
25418+ }
25419 }
25420
25421 var rulesList =
25422 from rule in rulesIndex
25423 orderby rule
25424 select rule;
25425- TextWriter indexWriter = File.CreateText (Path.Combine(outputdir, Path.Combine(assembly, assembly + ".md")));
25426
25427- foreach (var rule in rulesList) {
25428- indexWriter.WriteLine ("[[{0}]] ", rule);
25429- }
25430+ string assembly_index = String.Format ("{0}{1}{2}{1}{3}({2}).md",
25431+ outputdir, Path.DirectorySeparatorChar, version, assembly);
25432+
25433+ using (TextWriter writer = File.CreateText (assembly_index)) {
25434+ writer.WriteLine ("# {0} Rules", assembly);
25435+ writer.WriteLine ();
25436+ writer.WriteLine ("The following ({0}) rules are available in version [[{1}|Gendarme.Rules({1})]] of {2}:",
25437+ rulesList.Count (), version, assembly);
25438+ writer.WriteLine ();
25439+ foreach (var rule in rulesList) {
25440+ writer.WriteLine ("* [[{0}|{1}.{0}({2})]] ", rule, assembly, version);
25441+ }
25442+
25443+ if (version == "git") {
25444+ writer.WriteLine ();
25445+ writer.WriteLine (@"## Source code
25446
25447- indexWriter.Close ();
25448+You can browse the latest [[source code|https://github.com/mono/mono-tools/tree/master/gendarme/rules/{0}]] of this assembly on github.com", assembly);
25449+ }
25450
25451+ writer.WriteLine ();
25452+ }
25453 }
25454
25455 static void ProcessFile (string filename)
25456@@ -294,15 +331,14 @@ Please report any documentation errors, typos or suggestions to the
25457 orderby (string)member.Attribute ("name") ascending
25458 select member;
25459
25460- string assembly =
25461+ string assembly = Path.GetFileName (
25462 (from a in doc.Descendants ("assembly")
25463- select a.Element ("name").Value).FirstOrDefault();
25464-
25465- if (assembly == null || !assembly.StartsWith("Gendarme"))
25466+ select a.Element ("name").Value).FirstOrDefault ());
25467+
25468+ if (assembly == null || !assembly.StartsWith ("Gendarme"))
25469 return;
25470
25471 assembliesIndex.Add (assembly);
25472- Directory.CreateDirectory (Path.Combine(outputdir, assembly));
25473 ProcessRules (members, assembly);
25474 }
25475
25476@@ -310,40 +346,99 @@ Please report any documentation errors, typos or suggestions to the
25477 {
25478 string [] files;
25479 if (args.Length < 1) {
25480- Console.WriteLine ("Usage: xmldoc2wiki filepattern [outputdir]");
25481+ Console.WriteLine ("Usage: xmldoc2wiki filepattern [--out outputdir] [--version version]");
25482 return;
25483 }
25484
25485- int index = args [0].LastIndexOfAny (new char [] { '/', '\\' });
25486- string dir, pattern;
25487- if (index >= 0) {
25488- dir = args [0].Substring (0, index);
25489- pattern = args [0].Substring (args [0].LastIndexOfAny (new char [] { '/', '\\' }) + 1);
25490- } else {
25491- dir = ".";
25492- pattern = args [0];
25493+ outputdir = ".";
25494+ version = "git";
25495+
25496+ List<string> filenames = new List<string> ();
25497+ for (int i = 0; i < args.Length; i++) {
25498+ string arg = args [i];
25499+ switch (arg) {
25500+ case "--version":
25501+ version = args [++i];
25502+ break;
25503+ case "--out":
25504+ outputdir = args [++i];
25505+ break;
25506+ default:
25507+ int index = arg.LastIndexOfAny (new char [] { '/', '\\' });
25508+ string dir, pattern;
25509+ if (index >= 0) {
25510+ dir = arg.Substring (0, index);
25511+ pattern = arg.Substring (index + 1);
25512+ } else {
25513+ dir = ".";
25514+ pattern = arg;
25515+ }
25516+
25517+ files = Directory.GetFiles (dir, pattern);
25518+ foreach (string file in files) {
25519+ filenames.Add (file);
25520+ }
25521+ break;
25522+ }
25523 }
25524
25525- files = Directory.GetFiles (dir, pattern);
25526- if (args.Length >= 2)
25527- outputdir = args [1];
25528- else
25529- outputdir = ".";
25530+ string subdir = Path.Combine (outputdir, version);
25531+ if (!Directory.Exists (subdir))
25532+ Directory.CreateDirectory (subdir);
25533
25534- foreach (string file in files) {
25535+ foreach (string file in filenames) {
25536+ Console.WriteLine ("processing {0}", file);
25537 ProcessFile (file);
25538 }
25539
25540- TextWriter writer = File.CreateText (Path.Combine(outputdir, "index.md"));
25541+ CreateVersionIndex ();
25542+ CreateFooterFile ();
25543+ }
25544+
25545+ static void CreateVersionIndex ()
25546+ {
25547+ string rules_index = String.Format ("{0}{1}{2}{1}Gendarme.Rules({2}).md",
25548+ outputdir, Path.DirectorySeparatorChar, version);
25549+
25550+ using (TextWriter writer = File.CreateText (rules_index)) {
25551+ writer.WriteLine ("# Gendarme Rules Documentation Index");
25552+ writer.WriteLine ();
25553+
25554+ var assemblies =
25555+ from assembly in assembliesIndex
25556+ orderby assembly
25557+ select assembly;
25558+
25559+ writer.WriteLine ("The following ({0}) assemblies are available in version {1}:",
25560+ assemblies.Count (), version);
25561+ writer.WriteLine ();
25562+
25563+ foreach (var assembly in assemblies) {
25564+ writer.WriteLine ("* [[{0}|{0}({1})]] ", assembly, version);
25565+ }
25566+
25567+ if (version == "git") {
25568+ writer.WriteLine ();
25569+ writer.WriteLine (@"## Source code
25570
25571- var assemblies =
25572- from assembly in assembliesIndex
25573- orderby assembly
25574- select assembly;
25575+* Latest [[source code|https://github.com/mono/mono-tools/tree/master/gendarme/rules/]] for Gendarme's rules is available on github.com
25576+* Documentation is produced using gendarme's `xmldoc2wiki` (unsupported) tool which [[source code|https://github.com/mono/mono-tools/tree/master/gendarme/tools/unsupported/xmldoc2wiki]] is also available on github.com");
25577+ }
25578
25579- foreach (var assembly in assemblies) {
25580- writer.WriteLine ("[[{0}]] ", assembly);
25581+ writer.WriteLine ();
25582 }
25583- writer.Close ();
25584 }
25585-}
25586\ No newline at end of file
25587+
25588+ static void CreateFooterFile ()
25589+ {
25590+ string footer = String.Format ("{0}{1}{2}{1}_Footer.md", outputdir, Path.DirectorySeparatorChar, version);
25591+
25592+ using (TextWriter writer = File.CreateText (footer)) {
25593+ writer.WriteLine (@"## Feedback
25594+
25595+Note that this page was autogenerated ({0}) based on the `xmldoc` comments inside the rules source code and cannot be edited from this wiki.
25596+Please report any documentation errors, typos or suggestions to the
25597+[[Gendarme Google Group|http://groups.google.com/group/gendarme]]. Thanks!", DateTime.Now);
25598+ }
25599+ }
25600+}
25601diff --git a/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.csproj b/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.csproj
25602index db2fbf3..ee295fe 100644
25603--- a/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.csproj
25604+++ b/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.csproj
25605@@ -1,60 +1,99 @@
25606-<?xml version="1.0" encoding="utf-8"?>
25607-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
25608- <PropertyGroup>
25609- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
25610- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
25611- <ProductVersion>9.0.30729</ProductVersion>
25612- <SchemaVersion>2.0</SchemaVersion>
25613- <ProjectGuid>{AF174688-A979-4B3C-BE21-1C1BE8A0358E}</ProjectGuid>
25614- <OutputType>Exe</OutputType>
25615- <AppDesignerFolder>Properties</AppDesignerFolder>
25616- <RootNamespace>xmldoc2wiki</RootNamespace>
25617- <AssemblyName>xmldoc2wiki</AssemblyName>
25618- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
25619- <FileAlignment>512</FileAlignment>
25620- </PropertyGroup>
25621- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
25622- <DebugSymbols>true</DebugSymbols>
25623- <DebugType>full</DebugType>
25624- <Optimize>false</Optimize>
25625- <OutputPath>bin\Debug\</OutputPath>
25626- <DefineConstants>DEBUG;TRACE</DefineConstants>
25627- <ErrorReport>prompt</ErrorReport>
25628- <WarningLevel>4</WarningLevel>
25629- </PropertyGroup>
25630- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
25631- <DebugType>pdbonly</DebugType>
25632- <Optimize>true</Optimize>
25633- <OutputPath>bin\Release\</OutputPath>
25634- <DefineConstants>TRACE</DefineConstants>
25635- <ErrorReport>prompt</ErrorReport>
25636- <WarningLevel>4</WarningLevel>
25637- </PropertyGroup>
25638- <ItemGroup>
25639- <Reference Include="System" />
25640- <Reference Include="System.Core">
25641- <RequiredTargetFramework>3.5</RequiredTargetFramework>
25642- </Reference>
25643- <Reference Include="System.Xml.Linq">
25644- <RequiredTargetFramework>3.5</RequiredTargetFramework>
25645- </Reference>
25646- <Reference Include="System.Xml" />
25647- </ItemGroup>
25648- <ItemGroup>
25649- <Compile Include="..\..\..\AssemblyStaticInfo.cs">
25650- <Link>AssemblyStaticInfo.cs</Link>
25651- </Compile>
25652- <Compile Include="xmldoc2wiki.cs" />
25653- </ItemGroup>
25654- <ItemGroup>
25655- <Folder Include="Properties\" />
25656- </ItemGroup>
25657- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
25658+<?xml version="1.0" encoding="utf-8"?>\r
25659+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
25660+ <PropertyGroup>\r
25661+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
25662+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
25663+ <ProductVersion>9.0.30729</ProductVersion>\r
25664+ <SchemaVersion>2.0</SchemaVersion>\r
25665+ <ProjectGuid>{AF174688-A979-4B3C-BE21-1C1BE8A0358E}</ProjectGuid>\r
25666+ <OutputType>Exe</OutputType>\r
25667+ <AppDesignerFolder>Properties</AppDesignerFolder>\r
25668+ <RootNamespace>xmldoc2wiki</RootNamespace>\r
25669+ <AssemblyName>xmldoc2wiki</AssemblyName>\r
25670+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
25671+ <FileAlignment>512</FileAlignment>\r
25672+ <FileUpgradeFlags>\r
25673+ </FileUpgradeFlags>\r
25674+ <OldToolsVersion>3.5</OldToolsVersion>\r
25675+ <UpgradeBackupLocation />\r
25676+ <PublishUrl>publish\</PublishUrl>\r
25677+ <Install>true</Install>\r
25678+ <InstallFrom>Disk</InstallFrom>\r
25679+ <UpdateEnabled>false</UpdateEnabled>\r
25680+ <UpdateMode>Foreground</UpdateMode>\r
25681+ <UpdateInterval>7</UpdateInterval>\r
25682+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r
25683+ <UpdatePeriodically>false</UpdatePeriodically>\r
25684+ <UpdateRequired>false</UpdateRequired>\r
25685+ <MapFileExtensions>true</MapFileExtensions>\r
25686+ <ApplicationRevision>0</ApplicationRevision>\r
25687+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r
25688+ <IsWebBootstrapper>false</IsWebBootstrapper>\r
25689+ <UseApplicationTrust>false</UseApplicationTrust>\r
25690+ <BootstrapperEnabled>true</BootstrapperEnabled>\r
25691+ <TargetFrameworkProfile />\r
25692+ </PropertyGroup>\r
25693+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
25694+ <DebugSymbols>true</DebugSymbols>\r
25695+ <DebugType>full</DebugType>\r
25696+ <Optimize>false</Optimize>\r
25697+ <OutputPath>bin\Debug\</OutputPath>\r
25698+ <DefineConstants>DEBUG;TRACE</DefineConstants>\r
25699+ <ErrorReport>prompt</ErrorReport>\r
25700+ <WarningLevel>4</WarningLevel>\r
25701+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
25702+ </PropertyGroup>\r
25703+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
25704+ <DebugType>pdbonly</DebugType>\r
25705+ <Optimize>true</Optimize>\r
25706+ <OutputPath>bin\Release\</OutputPath>\r
25707+ <DefineConstants>TRACE</DefineConstants>\r
25708+ <ErrorReport>prompt</ErrorReport>\r
25709+ <WarningLevel>4</WarningLevel>\r
25710+ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r
25711+ </PropertyGroup>\r
25712+ <ItemGroup>\r
25713+ <Reference Include="System" />\r
25714+ <Reference Include="System.Core">\r
25715+ <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
25716+ </Reference>\r
25717+ <Reference Include="System.Xml.Linq">\r
25718+ <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
25719+ </Reference>\r
25720+ <Reference Include="System.Xml" />\r
25721+ </ItemGroup>\r
25722+ <ItemGroup>\r
25723+ <Compile Include="..\..\..\AssemblyStaticInfo.cs">\r
25724+ <Link>AssemblyStaticInfo.cs</Link>\r
25725+ </Compile>\r
25726+ <Compile Include="xmldoc2wiki.cs" />\r
25727+ </ItemGroup>\r
25728+ <ItemGroup>\r
25729+ <Folder Include="Properties\" />\r
25730+ </ItemGroup>\r
25731+ <ItemGroup>\r
25732+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">\r
25733+ <Visible>False</Visible>\r
25734+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r
25735+ <Install>false</Install>\r
25736+ </BootstrapperPackage>\r
25737+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">\r
25738+ <Visible>False</Visible>\r
25739+ <ProductName>.NET Framework 3.5 SP1</ProductName>\r
25740+ <Install>true</Install>\r
25741+ </BootstrapperPackage>\r
25742+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">\r
25743+ <Visible>False</Visible>\r
25744+ <ProductName>Windows Installer 3.1</ProductName>\r
25745+ <Install>true</Install>\r
25746+ </BootstrapperPackage>\r
25747+ </ItemGroup>\r
25748+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
25749 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
25750 Other similar extension points exist, see Microsoft.Common.targets.
25751 <Target Name="BeforeBuild">
25752 </Target>
25753 <Target Name="AfterBuild">
25754 </Target>
25755- -->
25756+ -->\r
25757 </Project>
25758\ No newline at end of file
25759diff --git a/gendarme/wix/Product.wxs b/gendarme/wix/Product.wxs
25760index cce4d8d..cd04e05 100644
25761--- a/gendarme/wix/Product.wxs
25762+++ b/gendarme/wix/Product.wxs
25763@@ -1,7 +1,7 @@
25764 <?xml version="1.0" encoding="UTF-8"?>\r
25765 <?define ProductShortName = "Gendarme" ?>\r
25766-<?define ProductVersion = "2.10.0" ?>\r
25767-<?define ProductVersionText = "2.10" ?>\r
25768+<?define ProductVersion = "2.11.0" ?>\r
25769+<?define ProductVersionText = "2.11" ?>\r
25770 <?define Manufacturer = "Novell" ?>\r
25771 <?define UpgradeCode = "D7C83968-DEF2-4614-81F2-A3EEFC9BC6B3" ?>\r
25772 \r
25773@@ -92,10 +92,10 @@
25774 <RemoveExistingProducts After="InstallValidate" />\r
25775 </InstallExecuteSequence>\r
25776 \r
25777- <!-- Ensure .Net Framework 3.5 is installed -->\r
25778- <PropertyRef Id="NETFRAMEWORK35" />\r
25779- <Condition Message="This setup requires the .NET Framework 3.5 to be installed.">\r
25780- <![CDATA[Installed OR NETFRAMEWORK35]]>\r
25781+ <!-- Ensure .Net Framework 4.0 is installed -->\r
25782+ <PropertyRef Id="NETFRAMEWORK40FULL" />\r
25783+ <Condition Message="This setup requires the .NET Framework 4.0 (full) to be installed.">\r
25784+ <![CDATA[Installed OR NETFRAMEWORK40FULL]]>\r
25785 </Condition>\r
25786 \r
25787 <!-- This enables the license screen and where to install screen -->\r
25788diff --git a/gendarme/wix/license.rtf b/gendarme/wix/license.rtf
25789index 8bd49b0..45c52b3 100644
25790--- a/gendarme/wix/license.rtf
25791+++ b/gendarme/wix/license.rtf
25792@@ -1,5 +1,5 @@
25793 {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fprq2\fcharset0 Arial;}}\r
25794-{\*\generator Msftedit 5.41.21.2508;}\viewkind4\uc1\pard\f0\fs20 Copyright (c) 2005-2010 Novell, Inc and the individuals listed on the ChangeLog entries.\par\r
25795+{\*\generator Msftedit 5.41.21.2508;}\viewkind4\uc1\pard\f0\fs20 Copyright (c) 2005-2011 Novell, Inc and the individuals listed on the ChangeLog entries.\par\r
25796 \par\r
25797 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\par\r
25798 \par\r
25799@@ -7,4 +7,4 @@ The above copyright notice and this permission notice shall be included in all c
25800 \par\r
25801 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\par\r
25802 }\r
25803-
25804\ No newline at end of file
25805+ \r
25806diff --git a/gsharp/Main.cs b/gsharp/Main.cs
25807index 84899b8..52ed96a 100644
25808--- a/gsharp/Main.cs
25809+++ b/gsharp/Main.cs
25810@@ -19,6 +19,7 @@ namespace Mono.CSharp.Gui
25811 public static bool Attached;
25812 public static bool HostHasGtkRunning;
25813 public static bool Debug;
25814+ static Evaluator evaluator;
25815
25816 public static void ShowHelp (OptionSet p)
25817 {
25818@@ -59,10 +60,10 @@ namespace Mono.CSharp.Gui
25819 else
25820 Start ("C# InteractiveBase Shell", extra);
25821 }
25822-
25823+
25824 static void AssemblyLoaded (object sender, AssemblyLoadEventArgs e)
25825 {
25826- Evaluator.ReferenceAssembly (e.LoadedAssembly);
25827+ evaluator.ReferenceAssembly (e.LoadedAssembly);
25828 }
25829
25830 internal static object RenderBitmaps (object o)
25831@@ -92,7 +93,7 @@ namespace Mono.CSharp.Gui
25832 InteractiveGraphicsBase.Attached = true;
25833 Gtk.Application.Invoke (delegate {
25834 try {
25835- Evaluator.Init (new string [0]);
25836+ evaluator = new Evaluator (new CompilerContext (new CompilerSettings (), new ConsoleReportPrinter ()));
25837 } catch {
25838 return;
25839 }
25840@@ -103,7 +104,7 @@ namespace Mono.CSharp.Gui
25841
25842 // Add all currently loaded assemblies
25843 foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ())
25844- Evaluator.ReferenceAssembly (a);
25845+ evaluator.ReferenceAssembly (a);
25846
25847 Start (String.Format ("Attached C# Interactive Shell at Process {0}", Process.GetCurrentProcess ().Id), null);
25848 } finally {
25849@@ -129,7 +130,6 @@ namespace Mono.CSharp.Gui
25850 if (files != null)
25851 m.LoadFiles (files, false);
25852 m.ShowAll ();
25853- Evaluator.DescribeTypeExpressions = true;
25854
25855 if (!HostHasGtkRunning){
25856 try {
25857@@ -146,4 +146,4 @@ namespace Mono.CSharp.Gui
25858 }
25859 }
25860 }
25861-}
25862\ No newline at end of file
25863+}
25864diff --git a/gsharp/MainWindow.cs b/gsharp/MainWindow.cs
25865index 34c24e4..f5da16a 100644
25866--- a/gsharp/MainWindow.cs
25867+++ b/gsharp/MainWindow.cs
25868@@ -80,7 +80,7 @@ namespace Mono.CSharp.Gui
25869 }
25870
25871 foreach (string file in libraries){
25872- Evaluator.LoadAssembly (file);
25873+ Shell.Evaluator.LoadAssembly (file);
25874 }
25875
25876 foreach (string file in sources){
25877@@ -101,7 +101,7 @@ namespace Mono.CSharp.Gui
25878 object result;
25879
25880 try {
25881- input = Evaluator.Evaluate (input, out result, out result_set);
25882+ input = Shell.Evaluator.Evaluate (input, out result, out result_set);
25883 } catch (Exception e){
25884 Console.WriteLine (e);
25885 return null;
25886diff --git a/gsharp/Shell.cs b/gsharp/Shell.cs
25887index 05d5695..5f41ea5 100644
25888--- a/gsharp/Shell.cs
25889+++ b/gsharp/Shell.cs
25890@@ -50,7 +50,9 @@ namespace Mono.CSharp.Gui
25891 public class Shell : TextView
25892 {
25893 TextMark end_of_last_processing;
25894- string expr = null;
25895+ string expr;
25896+ Evaluator evaluator;
25897+ CompilerContext context;
25898
25899 List<string> history = new List<string> ();
25900 int history_cursor;
25901@@ -72,10 +74,14 @@ namespace Mono.CSharp.Gui
25902 Buffer.InsertWithTagsByName (ref end, "Mono C# Shell, type 'help;' for help\n\nEnter statements or expressions below.\n", "Comment");
25903 ShowPrompt (false);
25904
25905- Evaluator.Init (new string [0]);
25906- Evaluator.SetInteractiveBaseClass (typeof (InteractiveGraphicsBase));
25907- Evaluator.Run ("LoadAssembly (\"System.Drawing\");");
25908- Evaluator.Run ("using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Drawing;");
25909+
25910+ context = new CompilerContext (new CompilerSettings (), new ConsoleReportPrinter ());
25911+ evaluator = new Evaluator (context);
25912+ evaluator.DescribeTypeExpressions = true;
25913+
25914+ evaluator.InteractiveBaseClass = typeof (InteractiveGraphicsBase);
25915+ evaluator.Run ("LoadAssembly (\"System.Drawing\");");
25916+ evaluator.Run ("using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Drawing;");
25917
25918 if (!MainClass.Debug){
25919 GuiStream error_stream = new GuiStream ("Error", (x, y) => Output (x, y));
25920@@ -139,16 +145,18 @@ namespace Mono.CSharp.Gui
25921 object result;
25922 bool result_set;
25923 StringWriter errorwriter = new StringWriter ();
25924-
25925- Evaluator.MessageOutput = errorwriter;
25926+
25927+ var old_printer = context.Report.SetPrinter (new StreamReportPrinter (errorwriter));
25928
25929 try {
25930- res = Evaluator.Evaluate (s, out result, out result_set);
25931+ res = evaluator.Evaluate (s, out result, out result_set);
25932 } catch (Exception e){
25933 expr = null;
25934 ShowError (e.ToString ());
25935 ShowPrompt (true, false);
25936 return true;
25937+ } finally {
25938+ context.Report.SetPrinter (old_printer);
25939 }
25940
25941 // Partial input
25942@@ -262,7 +270,7 @@ namespace Mono.CSharp.Gui
25943 case Gdk.Key.Tab:
25944 string saved_text = InputLine;
25945 string prefix;
25946- string [] completions = Evaluator.GetCompletions (LineUntilCursor, out prefix);
25947+ string [] completions = evaluator.GetCompletions (LineUntilCursor, out prefix);
25948 if (completions == null)
25949 return true;
25950
25951@@ -405,6 +413,12 @@ namespace Mono.CSharp.Gui
25952 TextIter Cursor {
25953 get { return Buffer.GetIterAtMark(Buffer.InsertMark); }
25954 }
25955+
25956+ public Evaluator Evaluator {
25957+ get {
25958+ return evaluator;
25959+ }
25960+ }
25961
25962 string InputLine {
25963 get { return Buffer.GetText(InputLineBegin, InputLineEnd, false); }
25964diff --git a/gsharp/gtk-gui/Mono.CSharp.Gui.DescribeType.cs b/gsharp/gtk-gui/Mono.CSharp.Gui.DescribeType.cs
25965index 21e9c5b..7e04ad0 100644
25966--- a/gsharp/gtk-gui/Mono.CSharp.Gui.DescribeType.cs
25967+++ b/gsharp/gtk-gui/Mono.CSharp.Gui.DescribeType.cs
25968@@ -1,105 +1,93 @@
25969-// ------------------------------------------------------------------------------
25970-// <autogenerated>
25971-// This code was generated by a tool.
25972-//
25973-//
25974-// Changes to this file may cause incorrect behavior and will be lost if
25975-// the code is regenerated.
25976-// </autogenerated>
25977-// ------------------------------------------------------------------------------
25978
25979-namespace Mono.CSharp.Gui {
25980-
25981-
25982- public partial class DescribeType {
25983-
25984- private Gtk.HBox hbox1;
25985-
25986- private Gtk.Label label1;
25987-
25988- private Gtk.Entry entry1;
25989-
25990- private Gtk.Button buttonCancel;
25991-
25992- private Gtk.Button buttonOk;
25993-
25994- protected virtual void Build() {
25995- Stetic.Gui.Initialize(this);
25996- // Widget Mono.CSharp.Gui.DescribeType
25997- this.Name = "Mono.CSharp.Gui.DescribeType";
25998- this.WindowPosition = ((Gtk.WindowPosition)(4));
25999- // Internal child Mono.CSharp.Gui.DescribeType.VBox
26000- Gtk.VBox w1 = this.VBox;
26001- w1.Name = "dialog1_VBox";
26002- w1.BorderWidth = ((uint)(2));
26003- // Container child dialog1_VBox.Gtk.Box+BoxChild
26004- this.hbox1 = new Gtk.HBox();
26005- this.hbox1.Name = "hbox1";
26006- this.hbox1.Spacing = 6;
26007- // Container child hbox1.Gtk.Box+BoxChild
26008- this.label1 = new Gtk.Label();
26009- this.label1.Name = "label1";
26010- this.label1.Xpad = 5;
26011- this.label1.Ypad = 15;
26012- this.label1.LabelProp = Mono.Unix.Catalog.GetString("Type name:");
26013- this.hbox1.Add(this.label1);
26014- Gtk.Box.BoxChild w2 = ((Gtk.Box.BoxChild)(this.hbox1[this.label1]));
26015- w2.Position = 0;
26016- w2.Expand = false;
26017- w2.Fill = false;
26018- // Container child hbox1.Gtk.Box+BoxChild
26019- this.entry1 = new Gtk.Entry();
26020- this.entry1.CanDefault = true;
26021- this.entry1.CanFocus = true;
26022- this.entry1.Name = "entry1";
26023- this.entry1.IsEditable = true;
26024- this.entry1.InvisibleChar = '●';
26025- this.hbox1.Add(this.entry1);
26026- Gtk.Box.BoxChild w3 = ((Gtk.Box.BoxChild)(this.hbox1[this.entry1]));
26027- w3.Position = 1;
26028- w1.Add(this.hbox1);
26029- Gtk.Box.BoxChild w4 = ((Gtk.Box.BoxChild)(w1[this.hbox1]));
26030- w4.Position = 0;
26031- w4.Expand = false;
26032- w4.Fill = false;
26033- // Internal child Mono.CSharp.Gui.DescribeType.ActionArea
26034- Gtk.HButtonBox w5 = this.ActionArea;
26035- w5.Name = "dialog1_ActionArea";
26036- w5.Spacing = 6;
26037- w5.BorderWidth = ((uint)(5));
26038- w5.LayoutStyle = ((Gtk.ButtonBoxStyle)(4));
26039- // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
26040- this.buttonCancel = new Gtk.Button();
26041- this.buttonCancel.CanDefault = true;
26042- this.buttonCancel.CanFocus = true;
26043- this.buttonCancel.Name = "buttonCancel";
26044- this.buttonCancel.UseStock = true;
26045- this.buttonCancel.UseUnderline = true;
26046- this.buttonCancel.Label = "gtk-cancel";
26047- this.AddActionWidget(this.buttonCancel, -6);
26048- Gtk.ButtonBox.ButtonBoxChild w6 = ((Gtk.ButtonBox.ButtonBoxChild)(w5[this.buttonCancel]));
26049- w6.Expand = false;
26050- w6.Fill = false;
26051- // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
26052- this.buttonOk = new Gtk.Button();
26053- this.buttonOk.CanDefault = true;
26054- this.buttonOk.CanFocus = true;
26055- this.buttonOk.Name = "buttonOk";
26056- this.buttonOk.UseStock = true;
26057- this.buttonOk.UseUnderline = true;
26058- this.buttonOk.Label = "gtk-ok";
26059- this.AddActionWidget(this.buttonOk, -5);
26060- Gtk.ButtonBox.ButtonBoxChild w7 = ((Gtk.ButtonBox.ButtonBoxChild)(w5[this.buttonOk]));
26061- w7.Position = 1;
26062- w7.Expand = false;
26063- w7.Fill = false;
26064- if ((this.Child != null)) {
26065- this.Child.ShowAll();
26066- }
26067- this.DefaultWidth = 284;
26068- this.DefaultHeight = 133;
26069- this.Show();
26070- this.entry1.Activated += new System.EventHandler(this.OnEntry1Activated);
26071- }
26072- }
26073+// This file has been generated by the GUI designer. Do not modify.
26074+namespace Mono.CSharp.Gui
26075+{
26076+ public partial class DescribeType
26077+ {
26078+ private global::Gtk.HBox hbox1;
26079+ private global::Gtk.Label label1;
26080+ private global::Gtk.Entry entry1;
26081+ private global::Gtk.Button buttonCancel;
26082+ private global::Gtk.Button buttonOk;
26083+
26084+ protected virtual void Build ()
26085+ {
26086+ global::Stetic.Gui.Initialize (this);
26087+ // Widget Mono.CSharp.Gui.DescribeType
26088+ this.Name = "Mono.CSharp.Gui.DescribeType";
26089+ this.WindowPosition = ((global::Gtk.WindowPosition)(4));
26090+ // Internal child Mono.CSharp.Gui.DescribeType.VBox
26091+ global::Gtk.VBox w1 = this.VBox;
26092+ w1.Name = "dialog1_VBox";
26093+ w1.BorderWidth = ((uint)(2));
26094+ // Container child dialog1_VBox.Gtk.Box+BoxChild
26095+ this.hbox1 = new global::Gtk.HBox ();
26096+ this.hbox1.Name = "hbox1";
26097+ this.hbox1.Spacing = 6;
26098+ // Container child hbox1.Gtk.Box+BoxChild
26099+ this.label1 = new global::Gtk.Label ();
26100+ this.label1.Name = "label1";
26101+ this.label1.Xpad = 5;
26102+ this.label1.Ypad = 15;
26103+ this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Type name:");
26104+ this.hbox1.Add (this.label1);
26105+ global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.label1]));
26106+ w2.Position = 0;
26107+ w2.Expand = false;
26108+ w2.Fill = false;
26109+ // Container child hbox1.Gtk.Box+BoxChild
26110+ this.entry1 = new global::Gtk.Entry ();
26111+ this.entry1.CanDefault = true;
26112+ this.entry1.CanFocus = true;
26113+ this.entry1.Name = "entry1";
26114+ this.entry1.IsEditable = true;
26115+ this.entry1.InvisibleChar = '●';
26116+ this.hbox1.Add (this.entry1);
26117+ global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.entry1]));
26118+ w3.Position = 1;
26119+ w1.Add (this.hbox1);
26120+ global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(w1 [this.hbox1]));
26121+ w4.Position = 0;
26122+ w4.Expand = false;
26123+ w4.Fill = false;
26124+ // Internal child Mono.CSharp.Gui.DescribeType.ActionArea
26125+ global::Gtk.HButtonBox w5 = this.ActionArea;
26126+ w5.Name = "dialog1_ActionArea";
26127+ w5.Spacing = 6;
26128+ w5.BorderWidth = ((uint)(5));
26129+ w5.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4));
26130+ // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
26131+ this.buttonCancel = new global::Gtk.Button ();
26132+ this.buttonCancel.CanDefault = true;
26133+ this.buttonCancel.CanFocus = true;
26134+ this.buttonCancel.Name = "buttonCancel";
26135+ this.buttonCancel.UseStock = true;
26136+ this.buttonCancel.UseUnderline = true;
26137+ this.buttonCancel.Label = "gtk-cancel";
26138+ this.AddActionWidget (this.buttonCancel, -6);
26139+ global::Gtk.ButtonBox.ButtonBoxChild w6 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w5 [this.buttonCancel]));
26140+ w6.Expand = false;
26141+ w6.Fill = false;
26142+ // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
26143+ this.buttonOk = new global::Gtk.Button ();
26144+ this.buttonOk.CanDefault = true;
26145+ this.buttonOk.CanFocus = true;
26146+ this.buttonOk.Name = "buttonOk";
26147+ this.buttonOk.UseStock = true;
26148+ this.buttonOk.UseUnderline = true;
26149+ this.buttonOk.Label = "gtk-ok";
26150+ this.AddActionWidget (this.buttonOk, -5);
26151+ global::Gtk.ButtonBox.ButtonBoxChild w7 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w5 [this.buttonOk]));
26152+ w7.Position = 1;
26153+ w7.Expand = false;
26154+ w7.Fill = false;
26155+ if ((this.Child != null)) {
26156+ this.Child.ShowAll ();
26157+ }
26158+ this.DefaultWidth = 284;
26159+ this.DefaultHeight = 133;
26160+ this.Show ();
26161+ this.entry1.Activated += new global::System.EventHandler (this.OnEntry1Activated);
26162+ }
26163+ }
26164 }
26165diff --git a/gsharp/gtk-gui/Mono.CSharp.Gui.MainWindow.cs b/gsharp/gtk-gui/Mono.CSharp.Gui.MainWindow.cs
26166index 7fb30cf..ad540d7 100644
26167--- a/gsharp/gtk-gui/Mono.CSharp.Gui.MainWindow.cs
26168+++ b/gsharp/gtk-gui/Mono.CSharp.Gui.MainWindow.cs
26169@@ -1,226 +1,193 @@
26170-// ------------------------------------------------------------------------------
26171-// <autogenerated>
26172-// This code was generated by a tool.
26173-//
26174-//
26175-// Changes to this file may cause incorrect behavior and will be lost if
26176-// the code is regenerated.
26177-// </autogenerated>
26178-// ------------------------------------------------------------------------------
26179
26180-namespace Mono.CSharp.Gui {
26181-
26182-
26183- public partial class MainWindow {
26184-
26185- private Gtk.UIManager UIManager;
26186-
26187- private Gtk.Action FileAction;
26188-
26189- private Gtk.Action QuitAction;
26190-
26191- private Gtk.Action AttachToProcessAction;
26192-
26193- private Gtk.Action HelpAction;
26194-
26195- private Gtk.Action AboutAction;
26196-
26197- private Gtk.Action ViewAction;
26198-
26199- private Gtk.ToggleAction gtkpane;
26200-
26201- private Gtk.Action ToolsAction;
26202-
26203- private Gtk.Action DescribeTypeAction;
26204-
26205- private Gtk.VBox vbox1;
26206-
26207- private Gtk.MenuBar menubar1;
26208-
26209- private Gtk.Notebook notebook1;
26210-
26211- private Gtk.HPaned hpaned;
26212-
26213- private Gtk.EventBox paned_container;
26214-
26215- private Gtk.VBox vbox2;
26216-
26217- private Gtk.Expander expander1;
26218-
26219- private Gtk.Label label4;
26220-
26221- private Gtk.Label GtkLabel4;
26222-
26223- private Gtk.EventBox eventbox;
26224-
26225- private Gtk.Label label1;
26226-
26227- private Gtk.EventBox standalone_container;
26228-
26229- private Gtk.Notebook shellnotebook;
26230-
26231- private Gtk.ScrolledWindow sw;
26232-
26233- private Gtk.Label label3;
26234-
26235- private Gtk.Label label2;
26236-
26237- protected virtual void Build() {
26238- Stetic.Gui.Initialize(this);
26239- // Widget Mono.CSharp.Gui.MainWindow
26240- this.UIManager = new Gtk.UIManager();
26241- Gtk.ActionGroup w1 = new Gtk.ActionGroup("Default");
26242- this.FileAction = new Gtk.Action("FileAction", Mono.Unix.Catalog.GetString("_File"), null, null);
26243- this.FileAction.ShortLabel = Mono.Unix.Catalog.GetString("File");
26244- w1.Add(this.FileAction, null);
26245- this.QuitAction = new Gtk.Action("QuitAction", Mono.Unix.Catalog.GetString("_Quit"), null, "gtk-quit");
26246- this.QuitAction.ShortLabel = Mono.Unix.Catalog.GetString("_Quit");
26247- w1.Add(this.QuitAction, null);
26248- this.AttachToProcessAction = new Gtk.Action("AttachToProcessAction", Mono.Unix.Catalog.GetString("Attach to Process"), null, null);
26249- this.AttachToProcessAction.ShortLabel = Mono.Unix.Catalog.GetString("Attach to Process");
26250- w1.Add(this.AttachToProcessAction, null);
26251- this.HelpAction = new Gtk.Action("HelpAction", Mono.Unix.Catalog.GetString("Help"), null, null);
26252- this.HelpAction.ShortLabel = Mono.Unix.Catalog.GetString("Help");
26253- w1.Add(this.HelpAction, null);
26254- this.AboutAction = new Gtk.Action("AboutAction", Mono.Unix.Catalog.GetString("About"), null, null);
26255- this.AboutAction.ShortLabel = Mono.Unix.Catalog.GetString("About");
26256- w1.Add(this.AboutAction, null);
26257- this.ViewAction = new Gtk.Action("ViewAction", Mono.Unix.Catalog.GetString("View"), null, null);
26258- this.ViewAction.ShortLabel = Mono.Unix.Catalog.GetString("View");
26259- w1.Add(this.ViewAction, null);
26260- this.gtkpane = new Gtk.ToggleAction("gtkpane", Mono.Unix.Catalog.GetString("Gtk Pane"), null, null);
26261- this.gtkpane.ShortLabel = Mono.Unix.Catalog.GetString("Gtk Pane");
26262- w1.Add(this.gtkpane, null);
26263- this.ToolsAction = new Gtk.Action("ToolsAction", Mono.Unix.Catalog.GetString("_Tools"), null, null);
26264- this.ToolsAction.ShortLabel = Mono.Unix.Catalog.GetString("_Tools");
26265- w1.Add(this.ToolsAction, null);
26266- this.DescribeTypeAction = new Gtk.Action("DescribeTypeAction", Mono.Unix.Catalog.GetString("Describe Type"), null, null);
26267- this.DescribeTypeAction.ShortLabel = Mono.Unix.Catalog.GetString("Describe Type");
26268- w1.Add(this.DescribeTypeAction, null);
26269- this.UIManager.InsertActionGroup(w1, 0);
26270- this.AddAccelGroup(this.UIManager.AccelGroup);
26271- this.Name = "Mono.CSharp.Gui.MainWindow";
26272- this.Title = Mono.Unix.Catalog.GetString("MainWindow");
26273- this.WindowPosition = ((Gtk.WindowPosition)(4));
26274- this.DefaultWidth = 600;
26275- this.DefaultHeight = 500;
26276- // Container child Mono.CSharp.Gui.MainWindow.Gtk.Container+ContainerChild
26277- this.vbox1 = new Gtk.VBox();
26278- this.vbox1.Name = "vbox1";
26279- this.vbox1.Spacing = 6;
26280- // Container child vbox1.Gtk.Box+BoxChild
26281- this.UIManager.AddUiFromString("<ui><menubar name='menubar1'><menu name='FileAction' action='FileAction'><menuitem name='AttachToProcessAction' action='AttachToProcessAction'/><separator/><menuitem name='QuitAction' action='QuitAction'/></menu><menu name='ViewAction' action='ViewAction'><menuitem name='gtkpane' action='gtkpane'/></menu><menu name='ToolsAction' action='ToolsAction'><menuitem name='DescribeTypeAction' action='DescribeTypeAction'/></menu><menu name='HelpAction' action='HelpAction'><menuitem name='AboutAction' action='AboutAction'/></menu></menubar></ui>");
26282- this.menubar1 = ((Gtk.MenuBar)(this.UIManager.GetWidget("/menubar1")));
26283- this.menubar1.Name = "menubar1";
26284- this.vbox1.Add(this.menubar1);
26285- Gtk.Box.BoxChild w2 = ((Gtk.Box.BoxChild)(this.vbox1[this.menubar1]));
26286- w2.Position = 0;
26287- w2.Expand = false;
26288- w2.Fill = false;
26289- // Container child vbox1.Gtk.Box+BoxChild
26290- this.notebook1 = new Gtk.Notebook();
26291- this.notebook1.CanFocus = true;
26292- this.notebook1.Name = "notebook1";
26293- this.notebook1.CurrentPage = 0;
26294- this.notebook1.ShowBorder = false;
26295- this.notebook1.ShowTabs = false;
26296- // Container child notebook1.Gtk.Notebook+NotebookChild
26297- this.hpaned = new Gtk.HPaned();
26298- this.hpaned.CanFocus = true;
26299- this.hpaned.Name = "hpaned";
26300- this.hpaned.Position = 472;
26301- // Container child hpaned.Gtk.Paned+PanedChild
26302- this.paned_container = new Gtk.EventBox();
26303- this.paned_container.Name = "paned_container";
26304- this.hpaned.Add(this.paned_container);
26305- Gtk.Paned.PanedChild w3 = ((Gtk.Paned.PanedChild)(this.hpaned[this.paned_container]));
26306- w3.Resize = false;
26307- // Container child hpaned.Gtk.Paned+PanedChild
26308- this.vbox2 = new Gtk.VBox();
26309- this.vbox2.Name = "vbox2";
26310- this.vbox2.Spacing = 6;
26311- // Container child vbox2.Gtk.Box+BoxChild
26312- this.expander1 = new Gtk.Expander(null);
26313- this.expander1.CanFocus = true;
26314- this.expander1.Name = "expander1";
26315- this.expander1.Expanded = true;
26316- // Container child expander1.Gtk.Container+ContainerChild
26317- this.label4 = new Gtk.Label();
26318- this.label4.Name = "label4";
26319- this.label4.Xpad = 10;
26320- this.label4.Xalign = 0.1F;
26321- this.label4.LabelProp = Mono.Unix.Catalog.GetString("Set the contents of this pane by adding Gtk.Widgets children to the <b>PaneContainer</b> property. The PaneContainer is a Gtk.EventBox. \n\nTry it like this:\n\nLoadPackage (\"gtk-sharp-2.0\");\nvar l = new Label (\"Hello world\");\nPaneContainer.Add (l);\nl.ShowAll ();");
26322- this.label4.UseMarkup = true;
26323- this.label4.Wrap = true;
26324- this.expander1.Add(this.label4);
26325- this.GtkLabel4 = new Gtk.Label();
26326- this.GtkLabel4.Name = "GtkLabel4";
26327- this.GtkLabel4.LabelProp = Mono.Unix.Catalog.GetString("<b>PaneContent</b>");
26328- this.GtkLabel4.UseMarkup = true;
26329- this.GtkLabel4.UseUnderline = true;
26330- this.expander1.LabelWidget = this.GtkLabel4;
26331- this.vbox2.Add(this.expander1);
26332- Gtk.Box.BoxChild w5 = ((Gtk.Box.BoxChild)(this.vbox2[this.expander1]));
26333- w5.Position = 0;
26334- w5.Expand = false;
26335- w5.Fill = false;
26336- // Container child vbox2.Gtk.Box+BoxChild
26337- this.eventbox = new Gtk.EventBox();
26338- this.eventbox.Name = "eventbox";
26339- this.vbox2.Add(this.eventbox);
26340- Gtk.Box.BoxChild w6 = ((Gtk.Box.BoxChild)(this.vbox2[this.eventbox]));
26341- w6.Position = 1;
26342- this.hpaned.Add(this.vbox2);
26343- this.notebook1.Add(this.hpaned);
26344- // Notebook tab
26345- this.label1 = new Gtk.Label();
26346- this.label1.Name = "label1";
26347- this.label1.LabelProp = Mono.Unix.Catalog.GetString("page1");
26348- this.notebook1.SetTabLabel(this.hpaned, this.label1);
26349- this.label1.ShowAll();
26350- // Container child notebook1.Gtk.Notebook+NotebookChild
26351- this.standalone_container = new Gtk.EventBox();
26352- this.standalone_container.Name = "standalone_container";
26353- // Container child standalone_container.Gtk.Container+ContainerChild
26354- this.shellnotebook = new Gtk.Notebook();
26355- this.shellnotebook.CanFocus = true;
26356- this.shellnotebook.Name = "shellnotebook";
26357- this.shellnotebook.CurrentPage = 0;
26358- this.shellnotebook.ShowTabs = false;
26359- this.shellnotebook.Scrollable = true;
26360- // Container child shellnotebook.Gtk.Notebook+NotebookChild
26361- this.sw = new Gtk.ScrolledWindow();
26362- this.sw.CanFocus = true;
26363- this.sw.Name = "sw";
26364- this.sw.ShadowType = ((Gtk.ShadowType)(1));
26365- this.shellnotebook.Add(this.sw);
26366- // Notebook tab
26367- this.label3 = new Gtk.Label();
26368- this.label3.Name = "label3";
26369- this.label3.LabelProp = Mono.Unix.Catalog.GetString("C#");
26370- this.shellnotebook.SetTabLabel(this.sw, this.label3);
26371- this.label3.ShowAll();
26372- this.standalone_container.Add(this.shellnotebook);
26373- this.notebook1.Add(this.standalone_container);
26374- Gtk.Notebook.NotebookChild w11 = ((Gtk.Notebook.NotebookChild)(this.notebook1[this.standalone_container]));
26375- w11.Position = 1;
26376- // Notebook tab
26377- this.label2 = new Gtk.Label();
26378- this.label2.Name = "label2";
26379- this.label2.LabelProp = Mono.Unix.Catalog.GetString("page2");
26380- this.notebook1.SetTabLabel(this.standalone_container, this.label2);
26381- this.label2.ShowAll();
26382- this.vbox1.Add(this.notebook1);
26383- Gtk.Box.BoxChild w12 = ((Gtk.Box.BoxChild)(this.vbox1[this.notebook1]));
26384- w12.Position = 1;
26385- this.Add(this.vbox1);
26386- if ((this.Child != null)) {
26387- this.Child.ShowAll();
26388- }
26389- this.Show();
26390- this.QuitAction.Activated += new System.EventHandler(this.OnQuitActionActivated);
26391- this.AttachToProcessAction.Activated += new System.EventHandler(this.OnAttachToProcessActionActivated);
26392- this.DescribeTypeAction.Activated += new System.EventHandler(this.OnDescribeTypeActionActivated);
26393- }
26394- }
26395+// This file has been generated by the GUI designer. Do not modify.
26396+namespace Mono.CSharp.Gui
26397+{
26398+ public partial class MainWindow
26399+ {
26400+ private global::Gtk.UIManager UIManager;
26401+ private global::Gtk.Action FileAction;
26402+ private global::Gtk.Action QuitAction;
26403+ private global::Gtk.Action AttachToProcessAction;
26404+ private global::Gtk.Action HelpAction;
26405+ private global::Gtk.Action AboutAction;
26406+ private global::Gtk.Action ViewAction;
26407+ private global::Gtk.ToggleAction gtkpane;
26408+ private global::Gtk.Action ToolsAction;
26409+ private global::Gtk.Action DescribeTypeAction;
26410+ private global::Gtk.VBox vbox1;
26411+ private global::Gtk.MenuBar menubar1;
26412+ private global::Gtk.Notebook notebook1;
26413+ private global::Gtk.HPaned hpaned;
26414+ private global::Gtk.EventBox paned_container;
26415+ private global::Gtk.VBox vbox2;
26416+ private global::Gtk.Expander expander1;
26417+ private global::Gtk.Label label4;
26418+ private global::Gtk.Label GtkLabel4;
26419+ private global::Gtk.EventBox eventbox;
26420+ private global::Gtk.Label label1;
26421+ private global::Gtk.EventBox standalone_container;
26422+ private global::Gtk.Notebook shellnotebook;
26423+ private global::Gtk.ScrolledWindow sw;
26424+ private global::Gtk.Label label3;
26425+ private global::Gtk.Label label2;
26426+
26427+ protected virtual void Build ()
26428+ {
26429+ global::Stetic.Gui.Initialize (this);
26430+ // Widget Mono.CSharp.Gui.MainWindow
26431+ this.UIManager = new global::Gtk.UIManager ();
26432+ global::Gtk.ActionGroup w1 = new global::Gtk.ActionGroup ("Default");
26433+ this.FileAction = new global::Gtk.Action ("FileAction", global::Mono.Unix.Catalog.GetString ("_File"), null, null);
26434+ this.FileAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("File");
26435+ w1.Add (this.FileAction, null);
26436+ this.QuitAction = new global::Gtk.Action ("QuitAction", global::Mono.Unix.Catalog.GetString ("_Quit"), null, "gtk-quit");
26437+ this.QuitAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("_Quit");
26438+ w1.Add (this.QuitAction, null);
26439+ this.AttachToProcessAction = new global::Gtk.Action ("AttachToProcessAction", global::Mono.Unix.Catalog.GetString ("Attach to Process"), null, null);
26440+ this.AttachToProcessAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Attach to Process");
26441+ w1.Add (this.AttachToProcessAction, null);
26442+ this.HelpAction = new global::Gtk.Action ("HelpAction", global::Mono.Unix.Catalog.GetString ("Help"), null, null);
26443+ this.HelpAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Help");
26444+ w1.Add (this.HelpAction, null);
26445+ this.AboutAction = new global::Gtk.Action ("AboutAction", global::Mono.Unix.Catalog.GetString ("About"), null, null);
26446+ this.AboutAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("About");
26447+ w1.Add (this.AboutAction, null);
26448+ this.ViewAction = new global::Gtk.Action ("ViewAction", global::Mono.Unix.Catalog.GetString ("View"), null, null);
26449+ this.ViewAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("View");
26450+ w1.Add (this.ViewAction, null);
26451+ this.gtkpane = new global::Gtk.ToggleAction ("gtkpane", global::Mono.Unix.Catalog.GetString ("Gtk Pane"), null, null);
26452+ this.gtkpane.ShortLabel = global::Mono.Unix.Catalog.GetString ("Gtk Pane");
26453+ w1.Add (this.gtkpane, null);
26454+ this.ToolsAction = new global::Gtk.Action ("ToolsAction", global::Mono.Unix.Catalog.GetString ("_Tools"), null, null);
26455+ this.ToolsAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("_Tools");
26456+ w1.Add (this.ToolsAction, null);
26457+ this.DescribeTypeAction = new global::Gtk.Action ("DescribeTypeAction", global::Mono.Unix.Catalog.GetString ("Describe Type"), null, null);
26458+ this.DescribeTypeAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Describe Type");
26459+ w1.Add (this.DescribeTypeAction, null);
26460+ this.UIManager.InsertActionGroup (w1, 0);
26461+ this.AddAccelGroup (this.UIManager.AccelGroup);
26462+ this.Name = "Mono.CSharp.Gui.MainWindow";
26463+ this.Title = global::Mono.Unix.Catalog.GetString ("MainWindow");
26464+ this.WindowPosition = ((global::Gtk.WindowPosition)(4));
26465+ this.DefaultWidth = 600;
26466+ this.DefaultHeight = 500;
26467+ // Container child Mono.CSharp.Gui.MainWindow.Gtk.Container+ContainerChild
26468+ this.vbox1 = new global::Gtk.VBox ();
26469+ this.vbox1.Name = "vbox1";
26470+ this.vbox1.Spacing = 6;
26471+ // Container child vbox1.Gtk.Box+BoxChild
26472+ this.UIManager.AddUiFromString ("<ui><menubar name='menubar1'><menu name='FileAction' action='FileAction'><menuitem name='AttachToProcessAction' action='AttachToProcessAction'/><separator/><menuitem name='QuitAction' action='QuitAction'/></menu><menu name='ViewAction' action='ViewAction'><menuitem name='gtkpane' action='gtkpane'/></menu><menu name='ToolsAction' action='ToolsAction'><menuitem name='DescribeTypeAction' action='DescribeTypeAction'/></menu><menu name='HelpAction' action='HelpAction'><menuitem name='AboutAction' action='AboutAction'/></menu></menubar></ui>");
26473+ this.menubar1 = ((global::Gtk.MenuBar)(this.UIManager.GetWidget ("/menubar1")));
26474+ this.menubar1.Name = "menubar1";
26475+ this.vbox1.Add (this.menubar1);
26476+ global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.menubar1]));
26477+ w2.Position = 0;
26478+ w2.Expand = false;
26479+ w2.Fill = false;
26480+ // Container child vbox1.Gtk.Box+BoxChild
26481+ this.notebook1 = new global::Gtk.Notebook ();
26482+ this.notebook1.CanFocus = true;
26483+ this.notebook1.Name = "notebook1";
26484+ this.notebook1.CurrentPage = 0;
26485+ this.notebook1.ShowBorder = false;
26486+ this.notebook1.ShowTabs = false;
26487+ // Container child notebook1.Gtk.Notebook+NotebookChild
26488+ this.hpaned = new global::Gtk.HPaned ();
26489+ this.hpaned.CanFocus = true;
26490+ this.hpaned.Name = "hpaned";
26491+ this.hpaned.Position = 472;
26492+ // Container child hpaned.Gtk.Paned+PanedChild
26493+ this.paned_container = new global::Gtk.EventBox ();
26494+ this.paned_container.Name = "paned_container";
26495+ this.hpaned.Add (this.paned_container);
26496+ global::Gtk.Paned.PanedChild w3 = ((global::Gtk.Paned.PanedChild)(this.hpaned [this.paned_container]));
26497+ w3.Resize = false;
26498+ // Container child hpaned.Gtk.Paned+PanedChild
26499+ this.vbox2 = new global::Gtk.VBox ();
26500+ this.vbox2.Name = "vbox2";
26501+ this.vbox2.Spacing = 6;
26502+ // Container child vbox2.Gtk.Box+BoxChild
26503+ this.expander1 = new global::Gtk.Expander (null);
26504+ this.expander1.CanFocus = true;
26505+ this.expander1.Name = "expander1";
26506+ this.expander1.Expanded = true;
26507+ // Container child expander1.Gtk.Container+ContainerChild
26508+ this.label4 = new global::Gtk.Label ();
26509+ this.label4.Name = "label4";
26510+ this.label4.Xpad = 10;
26511+ this.label4.Xalign = 0.1F;
26512+ this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("Set the contents of this pane by adding Gtk.Widgets children to the <b>PaneContainer</b> property. The PaneContainer is a Gtk.EventBox. \n\nTry it like this:\n\nLoadPackage (\"gtk-sharp-2.0\");\nvar l = new Label (\"Hello world\");\nPaneContainer.Add (l);\nl.ShowAll ();");
26513+ this.label4.UseMarkup = true;
26514+ this.label4.Wrap = true;
26515+ this.expander1.Add (this.label4);
26516+ this.GtkLabel4 = new global::Gtk.Label ();
26517+ this.GtkLabel4.Name = "GtkLabel4";
26518+ this.GtkLabel4.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>PaneContent</b>");
26519+ this.GtkLabel4.UseMarkup = true;
26520+ this.GtkLabel4.UseUnderline = true;
26521+ this.expander1.LabelWidget = this.GtkLabel4;
26522+ this.vbox2.Add (this.expander1);
26523+ global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.expander1]));
26524+ w5.Position = 0;
26525+ w5.Expand = false;
26526+ w5.Fill = false;
26527+ // Container child vbox2.Gtk.Box+BoxChild
26528+ this.eventbox = new global::Gtk.EventBox ();
26529+ this.eventbox.Name = "eventbox";
26530+ this.vbox2.Add (this.eventbox);
26531+ global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.eventbox]));
26532+ w6.Position = 1;
26533+ this.hpaned.Add (this.vbox2);
26534+ this.notebook1.Add (this.hpaned);
26535+ // Notebook tab
26536+ this.label1 = new global::Gtk.Label ();
26537+ this.label1.Name = "label1";
26538+ this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("page1");
26539+ this.notebook1.SetTabLabel (this.hpaned, this.label1);
26540+ this.label1.ShowAll ();
26541+ // Container child notebook1.Gtk.Notebook+NotebookChild
26542+ this.standalone_container = new global::Gtk.EventBox ();
26543+ this.standalone_container.Name = "standalone_container";
26544+ // Container child standalone_container.Gtk.Container+ContainerChild
26545+ this.shellnotebook = new global::Gtk.Notebook ();
26546+ this.shellnotebook.CanFocus = true;
26547+ this.shellnotebook.Name = "shellnotebook";
26548+ this.shellnotebook.CurrentPage = 0;
26549+ this.shellnotebook.ShowTabs = false;
26550+ this.shellnotebook.Scrollable = true;
26551+ // Container child shellnotebook.Gtk.Notebook+NotebookChild
26552+ this.sw = new global::Gtk.ScrolledWindow ();
26553+ this.sw.CanFocus = true;
26554+ this.sw.Name = "sw";
26555+ this.sw.ShadowType = ((global::Gtk.ShadowType)(1));
26556+ this.shellnotebook.Add (this.sw);
26557+ // Notebook tab
26558+ this.label3 = new global::Gtk.Label ();
26559+ this.label3.Name = "label3";
26560+ this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("C#");
26561+ this.shellnotebook.SetTabLabel (this.sw, this.label3);
26562+ this.label3.ShowAll ();
26563+ this.standalone_container.Add (this.shellnotebook);
26564+ this.notebook1.Add (this.standalone_container);
26565+ global::Gtk.Notebook.NotebookChild w11 = ((global::Gtk.Notebook.NotebookChild)(this.notebook1 [this.standalone_container]));
26566+ w11.Position = 1;
26567+ // Notebook tab
26568+ this.label2 = new global::Gtk.Label ();
26569+ this.label2.Name = "label2";
26570+ this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("page2");
26571+ this.notebook1.SetTabLabel (this.standalone_container, this.label2);
26572+ this.label2.ShowAll ();
26573+ this.vbox1.Add (this.notebook1);
26574+ global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.notebook1]));
26575+ w12.Position = 1;
26576+ this.Add (this.vbox1);
26577+ if ((this.Child != null)) {
26578+ this.Child.ShowAll ();
26579+ }
26580+ this.Show ();
26581+ this.QuitAction.Activated += new global::System.EventHandler (this.OnQuitActionActivated);
26582+ this.AttachToProcessAction.Activated += new global::System.EventHandler (this.OnAttachToProcessActionActivated);
26583+ this.DescribeTypeAction.Activated += new global::System.EventHandler (this.OnDescribeTypeActionActivated);
26584+ }
26585+ }
26586 }
26587diff --git a/gsharp/gtk-gui/Mono.CSharp.Gui.ProcessSelector.cs b/gsharp/gtk-gui/Mono.CSharp.Gui.ProcessSelector.cs
26588index 3ae7cd7..fed8491 100644
26589--- a/gsharp/gtk-gui/Mono.CSharp.Gui.ProcessSelector.cs
26590+++ b/gsharp/gtk-gui/Mono.CSharp.Gui.ProcessSelector.cs
26591@@ -1,108 +1,94 @@
26592-// ------------------------------------------------------------------------------
26593-// <autogenerated>
26594-// This code was generated by a tool.
26595-//
26596-//
26597-// Changes to this file may cause incorrect behavior and will be lost if
26598-// the code is regenerated.
26599-// </autogenerated>
26600-// ------------------------------------------------------------------------------
26601
26602-namespace Mono.CSharp.Gui {
26603-
26604-
26605- public partial class ProcessSelector {
26606-
26607- private Gtk.Frame frame1;
26608-
26609- private Gtk.Alignment GtkAlignment;
26610-
26611- private Gtk.ScrolledWindow GtkScrolledWindow;
26612-
26613- private Gtk.TreeView treeview;
26614-
26615- private Gtk.Label GtkLabel;
26616-
26617- private Gtk.Button buttonCancel;
26618-
26619- private Gtk.Button buttonOk;
26620-
26621- protected virtual void Build() {
26622- Stetic.Gui.Initialize(this);
26623- // Widget Mono.CSharp.Gui.ProcessSelector
26624- this.Name = "Mono.CSharp.Gui.ProcessSelector";
26625- this.Title = Mono.Unix.Catalog.GetString("Select Mono Process to Attach");
26626- this.WindowPosition = ((Gtk.WindowPosition)(4));
26627- // Internal child Mono.CSharp.Gui.ProcessSelector.VBox
26628- Gtk.VBox w1 = this.VBox;
26629- w1.Name = "dialog1_VBox";
26630- w1.BorderWidth = ((uint)(2));
26631- // Container child dialog1_VBox.Gtk.Box+BoxChild
26632- this.frame1 = new Gtk.Frame();
26633- this.frame1.Name = "frame1";
26634- this.frame1.ShadowType = ((Gtk.ShadowType)(0));
26635- this.frame1.BorderWidth = ((uint)(2));
26636- // Container child frame1.Gtk.Container+ContainerChild
26637- this.GtkAlignment = new Gtk.Alignment(0F, 0F, 1F, 1F);
26638- this.GtkAlignment.Name = "GtkAlignment";
26639- this.GtkAlignment.LeftPadding = ((uint)(12));
26640- // Container child GtkAlignment.Gtk.Container+ContainerChild
26641- this.GtkScrolledWindow = new Gtk.ScrolledWindow();
26642- this.GtkScrolledWindow.Name = "GtkScrolledWindow";
26643- this.GtkScrolledWindow.ShadowType = ((Gtk.ShadowType)(1));
26644- // Container child GtkScrolledWindow.Gtk.Container+ContainerChild
26645- this.treeview = new Gtk.TreeView();
26646- this.treeview.CanFocus = true;
26647- this.treeview.Name = "treeview";
26648- this.GtkScrolledWindow.Add(this.treeview);
26649- this.GtkAlignment.Add(this.GtkScrolledWindow);
26650- this.frame1.Add(this.GtkAlignment);
26651- this.GtkLabel = new Gtk.Label();
26652- this.GtkLabel.Name = "GtkLabel";
26653- this.GtkLabel.LabelProp = Mono.Unix.Catalog.GetString("<b>Processes:</b>");
26654- this.GtkLabel.UseMarkup = true;
26655- this.frame1.LabelWidget = this.GtkLabel;
26656- w1.Add(this.frame1);
26657- Gtk.Box.BoxChild w5 = ((Gtk.Box.BoxChild)(w1[this.frame1]));
26658- w5.Position = 0;
26659- w5.Padding = ((uint)(3));
26660- // Internal child Mono.CSharp.Gui.ProcessSelector.ActionArea
26661- Gtk.HButtonBox w6 = this.ActionArea;
26662- w6.Name = "dialog1_ActionArea";
26663- w6.Spacing = 6;
26664- w6.BorderWidth = ((uint)(5));
26665- w6.LayoutStyle = ((Gtk.ButtonBoxStyle)(4));
26666- // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
26667- this.buttonCancel = new Gtk.Button();
26668- this.buttonCancel.CanDefault = true;
26669- this.buttonCancel.CanFocus = true;
26670- this.buttonCancel.Name = "buttonCancel";
26671- this.buttonCancel.UseStock = true;
26672- this.buttonCancel.UseUnderline = true;
26673- this.buttonCancel.Label = "gtk-cancel";
26674- this.AddActionWidget(this.buttonCancel, -6);
26675- Gtk.ButtonBox.ButtonBoxChild w7 = ((Gtk.ButtonBox.ButtonBoxChild)(w6[this.buttonCancel]));
26676- w7.Expand = false;
26677- w7.Fill = false;
26678- // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
26679- this.buttonOk = new Gtk.Button();
26680- this.buttonOk.CanDefault = true;
26681- this.buttonOk.CanFocus = true;
26682- this.buttonOk.Name = "buttonOk";
26683- this.buttonOk.UseUnderline = true;
26684- this.buttonOk.Label = Mono.Unix.Catalog.GetString("_Attach");
26685- this.AddActionWidget(this.buttonOk, -5);
26686- Gtk.ButtonBox.ButtonBoxChild w8 = ((Gtk.ButtonBox.ButtonBoxChild)(w6[this.buttonOk]));
26687- w8.Position = 1;
26688- w8.Expand = false;
26689- w8.Fill = false;
26690- if ((this.Child != null)) {
26691- this.Child.ShowAll();
26692- }
26693- this.DefaultWidth = 400;
26694- this.DefaultHeight = 300;
26695- this.Show();
26696- this.Close += new System.EventHandler(this.OnClose);
26697- }
26698- }
26699+// This file has been generated by the GUI designer. Do not modify.
26700+namespace Mono.CSharp.Gui
26701+{
26702+ public partial class ProcessSelector
26703+ {
26704+ private global::Gtk.Frame frame1;
26705+ private global::Gtk.Alignment GtkAlignment;
26706+ private global::Gtk.ScrolledWindow GtkScrolledWindow;
26707+ private global::Gtk.TreeView treeview;
26708+ private global::Gtk.Label GtkLabel;
26709+ private global::Gtk.Button buttonCancel;
26710+ private global::Gtk.Button buttonOk;
26711+
26712+ protected virtual void Build ()
26713+ {
26714+ global::Stetic.Gui.Initialize (this);
26715+ // Widget Mono.CSharp.Gui.ProcessSelector
26716+ this.Name = "Mono.CSharp.Gui.ProcessSelector";
26717+ this.Title = global::Mono.Unix.Catalog.GetString ("Select Mono Process to Attach");
26718+ this.WindowPosition = ((global::Gtk.WindowPosition)(4));
26719+ // Internal child Mono.CSharp.Gui.ProcessSelector.VBox
26720+ global::Gtk.VBox w1 = this.VBox;
26721+ w1.Name = "dialog1_VBox";
26722+ w1.BorderWidth = ((uint)(2));
26723+ // Container child dialog1_VBox.Gtk.Box+BoxChild
26724+ this.frame1 = new global::Gtk.Frame ();
26725+ this.frame1.Name = "frame1";
26726+ this.frame1.ShadowType = ((global::Gtk.ShadowType)(0));
26727+ this.frame1.BorderWidth = ((uint)(2));
26728+ // Container child frame1.Gtk.Container+ContainerChild
26729+ this.GtkAlignment = new global::Gtk.Alignment (0F, 0F, 1F, 1F);
26730+ this.GtkAlignment.Name = "GtkAlignment";
26731+ this.GtkAlignment.LeftPadding = ((uint)(12));
26732+ // Container child GtkAlignment.Gtk.Container+ContainerChild
26733+ this.GtkScrolledWindow = new global::Gtk.ScrolledWindow ();
26734+ this.GtkScrolledWindow.Name = "GtkScrolledWindow";
26735+ this.GtkScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1));
26736+ // Container child GtkScrolledWindow.Gtk.Container+ContainerChild
26737+ this.treeview = new global::Gtk.TreeView ();
26738+ this.treeview.CanFocus = true;
26739+ this.treeview.Name = "treeview";
26740+ this.GtkScrolledWindow.Add (this.treeview);
26741+ this.GtkAlignment.Add (this.GtkScrolledWindow);
26742+ this.frame1.Add (this.GtkAlignment);
26743+ this.GtkLabel = new global::Gtk.Label ();
26744+ this.GtkLabel.Name = "GtkLabel";
26745+ this.GtkLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Processes:</b>");
26746+ this.GtkLabel.UseMarkup = true;
26747+ this.frame1.LabelWidget = this.GtkLabel;
26748+ w1.Add (this.frame1);
26749+ global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(w1 [this.frame1]));
26750+ w5.Position = 0;
26751+ w5.Padding = ((uint)(3));
26752+ // Internal child Mono.CSharp.Gui.ProcessSelector.ActionArea
26753+ global::Gtk.HButtonBox w6 = this.ActionArea;
26754+ w6.Name = "dialog1_ActionArea";
26755+ w6.Spacing = 6;
26756+ w6.BorderWidth = ((uint)(5));
26757+ w6.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4));
26758+ // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
26759+ this.buttonCancel = new global::Gtk.Button ();
26760+ this.buttonCancel.CanDefault = true;
26761+ this.buttonCancel.CanFocus = true;
26762+ this.buttonCancel.Name = "buttonCancel";
26763+ this.buttonCancel.UseStock = true;
26764+ this.buttonCancel.UseUnderline = true;
26765+ this.buttonCancel.Label = "gtk-cancel";
26766+ this.AddActionWidget (this.buttonCancel, -6);
26767+ global::Gtk.ButtonBox.ButtonBoxChild w7 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w6 [this.buttonCancel]));
26768+ w7.Expand = false;
26769+ w7.Fill = false;
26770+ // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
26771+ this.buttonOk = new global::Gtk.Button ();
26772+ this.buttonOk.CanDefault = true;
26773+ this.buttonOk.CanFocus = true;
26774+ this.buttonOk.Name = "buttonOk";
26775+ this.buttonOk.UseUnderline = true;
26776+ this.buttonOk.Label = global::Mono.Unix.Catalog.GetString ("_Attach");
26777+ this.AddActionWidget (this.buttonOk, -5);
26778+ global::Gtk.ButtonBox.ButtonBoxChild w8 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w6 [this.buttonOk]));
26779+ w8.Position = 1;
26780+ w8.Expand = false;
26781+ w8.Fill = false;
26782+ if ((this.Child != null)) {
26783+ this.Child.ShowAll ();
26784+ }
26785+ this.DefaultWidth = 400;
26786+ this.DefaultHeight = 300;
26787+ this.Show ();
26788+ this.Close += new global::System.EventHandler (this.OnClose);
26789+ }
26790+ }
26791 }
26792diff --git a/gsharp/gtk-gui/generated.cs b/gsharp/gtk-gui/generated.cs
26793index 8b467a5..9ef3363 100644
26794--- a/gsharp/gtk-gui/generated.cs
26795+++ b/gsharp/gtk-gui/generated.cs
26796@@ -1,35 +1,29 @@
26797-// ------------------------------------------------------------------------------
26798-// <autogenerated>
26799-// This code was generated by a tool.
26800-//
26801-//
26802-// Changes to this file may cause incorrect behavior and will be lost if
26803-// the code is regenerated.
26804-// </autogenerated>
26805-// ------------------------------------------------------------------------------
26806
26807-namespace Stetic {
26808-
26809-
26810- internal class Gui {
26811-
26812- private static bool initialized;
26813-
26814- internal static void Initialize(Gtk.Widget iconRenderer) {
26815- if ((Stetic.Gui.initialized == false)) {
26816- Stetic.Gui.initialized = true;
26817- }
26818- }
26819- }
26820-
26821- internal class ActionGroups {
26822-
26823- public static Gtk.ActionGroup GetActionGroup(System.Type type) {
26824- return Stetic.ActionGroups.GetActionGroup(type.FullName);
26825- }
26826-
26827- public static Gtk.ActionGroup GetActionGroup(string name) {
26828- return null;
26829- }
26830- }
26831+// This file has been generated by the GUI designer. Do not modify.
26832+namespace Stetic
26833+{
26834+ internal class Gui
26835+ {
26836+ private static bool initialized;
26837+
26838+ internal static void Initialize (Gtk.Widget iconRenderer)
26839+ {
26840+ if ((Stetic.Gui.initialized == false)) {
26841+ Stetic.Gui.initialized = true;
26842+ }
26843+ }
26844+ }
26845+
26846+ internal class ActionGroups
26847+ {
26848+ public static Gtk.ActionGroup GetActionGroup (System.Type type)
26849+ {
26850+ return Stetic.ActionGroups.GetActionGroup (type.FullName);
26851+ }
26852+
26853+ public static Gtk.ActionGroup GetActionGroup (string name)
26854+ {
26855+ return null;
26856+ }
26857+ }
26858 }
26859diff --git a/gui-compare/CecilMetadata.cs b/gui-compare/CecilMetadata.cs
26860index 2387b5e..df43b5e 100644
26861--- a/gui-compare/CecilMetadata.cs
26862+++ b/gui-compare/CecilMetadata.cs
26863@@ -923,6 +923,7 @@ namespace GuiCompare {
26864 MethodAttributes.Static |
26865 MethodAttributes.Abstract |
26866 MethodAttributes.HideBySig |
26867+// MethodAttributes.HasSecurity |
26868 MethodAttributes.SpecialName);
26869 public override string GetMemberAccess ()
26870 {
26871@@ -1011,15 +1012,24 @@ namespace GuiCompare {
26872 sb.Append ('(');
26873 bool first_p = true;
26874 foreach (ParameterDefinition p in method_def.Parameters) {
26875+ TypeReference paramType = p.ParameterType;
26876 if (!first_p)
26877 sb.Append (", ");
26878 first_p = false;
26879 if (p.IsIn)
26880 sb.Append ("in ");
26881- else if (p.IsOut)
26882+ else if (paramType.IsByReference) {
26883+ if (beautify) {
26884+ sb.Append (p.IsOut ? "out " : "ref ");
26885+ paramType = paramType.GetElementType ();
26886+ } else if (p.IsOut) {
26887+ sb.Append ("out ");
26888+ }
26889+ } else if (p.IsOut) {
26890 sb.Append ("out ");
26891+ }
26892 sb.Append (beautify
26893- ? CecilUtils.PrettyType (p.ParameterType)
26894+ ? CecilUtils.PrettyType (paramType)
26895 : CecilUtils.FormatTypeLikeCorCompare (p.ParameterType));
26896 if (beautify) {
26897 sb.Append (" ");
26898@@ -1179,55 +1189,213 @@ namespace GuiCompare {
26899 public CecilAttribute (CustomAttribute ca)
26900 : base (ca.Constructor.DeclaringType.FullName)
26901 {
26902- var sb = new StringBuilder ("[" + ca.Constructor.DeclaringType.FullName);
26903- bool first = true;
26904-
26905- var cargs = ca.ConstructorArguments;
26906- if (cargs != null && cargs.Count > 0) {
26907- foreach (var argument in cargs) {
26908- if (first) {
26909- sb.Append (" (");
26910- first = false;
26911- } else
26912- sb.Append (", ");
26913+ Dictionary<string, object> attribute_mapping = CreateAttributeMapping (ca);
26914+
26915+ foreach (string name in attribute_mapping.Keys) {
26916+ if (name == "TypeId")
26917+ continue;
26918+
26919+ object o = attribute_mapping[name];
26920+ Properties.Add (name, o == null ? "null" : o.ToString ());
26921+ }
26922+ }
26923+
26924+ static Dictionary<string, object> CreateAttributeMapping (CustomAttribute attribute)
26925+ {
26926+ var mapping = new Dictionary<string, object> ();
26927+
26928+ PopulateMapping (mapping, attribute);
26929+
26930+ var constructor = attribute.Constructor.Resolve ();
26931+ if (constructor == null || constructor.Parameters.Count == 0)
26932+ return mapping;
26933+
26934+ PopulateMapping (mapping, constructor, attribute);
26935+
26936+ return mapping;
26937+ }
26938+
26939+ static void PopulateMapping (Dictionary<string, object> mapping, CustomAttribute attribute)
26940+ {
26941+ foreach (var named_argument in attribute.Properties) {
26942+ var name = named_argument.Name;
26943+ var arg = named_argument.Argument;
26944+
26945+ if (arg.Value is CustomAttributeArgument)
26946+ arg = (CustomAttributeArgument) arg.Value;
26947+
26948+ mapping.Add (name, GetArgumentValue (arg.Type, arg.Value));
26949+ }
26950+ }
26951
26952- sb.Append (FormatValue (argument.Value));
26953+ static Dictionary<FieldReference, int> CreateArgumentFieldMapping (MethodDefinition constructor)
26954+ {
26955+ Dictionary<FieldReference, int> field_mapping = new Dictionary<FieldReference, int> ();
26956+
26957+ int? argument = null;
26958+
26959+ foreach (Instruction instruction in constructor.Body.Instructions) {
26960+ switch (instruction.OpCode.Code) {
26961+ case Code.Ldarg_1:
26962+ argument = 1;
26963+ break;
26964+ case Code.Ldarg_2:
26965+ argument = 2;
26966+ break;
26967+ case Code.Ldarg_3:
26968+ argument = 3;
26969+ break;
26970+ case Code.Ldarg:
26971+ case Code.Ldarg_S:
26972+ argument = ((ParameterDefinition) instruction.Operand).Index + 1;
26973+ break;
26974+
26975+ case Code.Stfld:
26976+ FieldReference field = (FieldReference) instruction.Operand;
26977+ if (field.DeclaringType.FullName != constructor.DeclaringType.FullName)
26978+ continue;
26979+
26980+ if (!argument.HasValue)
26981+ break;
26982+
26983+ if (!field_mapping.ContainsKey (field))
26984+ field_mapping.Add (field, (int) argument - 1);
26985+
26986+ argument = null;
26987+ break;
26988 }
26989+ }
26990+
26991+ return field_mapping;
26992+ }
26993+
26994+ static Dictionary<PropertyDefinition, FieldReference> CreatePropertyFieldMapping (TypeDefinition type)
26995+ {
26996+ Dictionary<PropertyDefinition, FieldReference> property_mapping = new Dictionary<PropertyDefinition, FieldReference> ();
26997+
26998+ foreach (PropertyDefinition property in type.Properties) {
26999+ if (property.GetMethod == null)
27000+ continue;
27001+ if (!property.GetMethod.HasBody)
27002+ continue;
27003+
27004+ foreach (Instruction instruction in property.GetMethod.Body.Instructions) {
27005+ if (instruction.OpCode.Code != Code.Ldfld)
27006+ continue;
27007+
27008+ FieldReference field = (FieldReference) instruction.Operand;
27009+ if (field.DeclaringType.FullName != type.FullName)
27010+ continue;
27011+
27012+ property_mapping.Add (property, field);
27013+ break;
27014+ }
27015+ }
27016+
27017+ return property_mapping;
27018+ }
27019+
27020+ static void PopulateMapping (Dictionary<string, object> mapping, MethodDefinition constructor, CustomAttribute attribute)
27021+ {
27022+ if (!constructor.HasBody)
27023+ return;
27024+
27025+ if (constructor.DeclaringType.FullName == "System.Runtime.CompilerServices.DecimalConstantAttribute") {
27026+ var ca = attribute.ConstructorArguments;
27027+ var dca = constructor.Parameters[2].ParameterType == constructor.Module.TypeSystem.Int32 ?
27028+ new DecimalConstantAttribute ((byte) ca[0].Value, (byte) ca[1].Value, (int) ca[2].Value, (int) ca[3].Value, (int) ca[4].Value) :
27029+ new DecimalConstantAttribute ((byte) ca[0].Value, (byte) ca[1].Value, (uint) ca[2].Value, (uint) ca[3].Value, (uint) ca[4].Value);
27030+
27031+ mapping.Add ("Value", dca.Value);
27032+ return;
27033+ }
27034+
27035+ var field_mapping = CreateArgumentFieldMapping (constructor);
27036+ var property_mapping = CreatePropertyFieldMapping ((TypeDefinition) constructor.DeclaringType);
27037+
27038+ foreach (var pair in property_mapping) {
27039+ int argument;
27040+ if (!field_mapping.TryGetValue (pair.Value, out argument))
27041+ continue;
27042+
27043+ var ca_arg = attribute.ConstructorArguments[argument];
27044+ if (ca_arg.Value is CustomAttributeArgument)
27045+ ca_arg = (CustomAttributeArgument) ca_arg.Value;
27046
27047+ mapping[pair.Key.Name] = GetArgumentValue (ca_arg.Type, ca_arg.Value);
27048 }
27049+ }
27050
27051- var properties = ca.Properties;
27052- if (properties != null && properties.Count > 0) {
27053- foreach (var namedArg in properties) {
27054- if (first) {
27055- sb.Append (" (");
27056- first = false;
27057- } else
27058- sb.Append (", ");
27059-
27060- sb.AppendFormat ("{0}={1}", namedArg.Name, FormatValue (namedArg.Argument.Value));
27061+ static object GetArgumentValue (TypeReference reference, object value)
27062+ {
27063+ var type = reference.Resolve ();
27064+ if (type == null)
27065+ return value;
27066+
27067+ if (type.IsEnum) {
27068+ if (IsFlaggedEnum (type))
27069+ return GetFlaggedEnumValue (type, value);
27070+
27071+ return GetEnumValue (type, value);
27072+ }
27073+
27074+ return value;
27075+ }
27076+
27077+ static bool IsFlaggedEnum (TypeDefinition type)
27078+ {
27079+ if (!type.IsEnum)
27080+ return false;
27081+
27082+ if (type.CustomAttributes.Count == 0)
27083+ return false;
27084+
27085+ foreach (CustomAttribute attribute in type.CustomAttributes)
27086+ if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute")
27087+ return true;
27088+
27089+ return false;
27090+ }
27091+
27092+ static object GetFlaggedEnumValue (TypeDefinition type, object value)
27093+ {
27094+ long flags = Convert.ToInt64 (value);
27095+ var signature = new StringBuilder ();
27096+
27097+ for (int i = type.Fields.Count - 1; i >= 0; i--) {
27098+ FieldDefinition field = type.Fields[i];
27099+
27100+ if (!field.HasConstant)
27101+ continue;
27102+
27103+ long flag = Convert.ToInt64 (field.Constant);
27104+
27105+ if (flag == 0)
27106+ continue;
27107+
27108+ if ((flags & flag) == flag) {
27109+ if (signature.Length != 0)
27110+ signature.Append (", ");
27111+
27112+ signature.Append (field.Name);
27113+ flags -= flag;
27114 }
27115 }
27116-
27117- if (!first)
27118- sb.Append (')');
27119- sb.Append ("]");
27120-
27121- ExtraInfo = sb.ToString ();
27122+
27123+ return signature.ToString ();
27124 }
27125
27126- string FormatValue (object o)
27127+ static object GetEnumValue (TypeDefinition type, object value)
27128 {
27129- if (o == null)
27130- return "null";
27131+ foreach (FieldDefinition field in type.Fields) {
27132+ if (!field.HasConstant)
27133+ continue;
27134
27135- if (o is string)
27136- return "\"" + o + "\"";
27137+ if (Comparer.Default.Compare (field.Constant, value) == 0)
27138+ return field.Name;
27139+ }
27140
27141- if (o is bool)
27142- return o.ToString ().ToLowerInvariant ();
27143-
27144- return o.ToString ();
27145+ return value;
27146 }
27147 }
27148
27149diff --git a/gui-compare/CompareContext.cs b/gui-compare/CompareContext.cs
27150index 8a3b932..b171ef8 100644
27151--- a/gui-compare/CompareContext.cs
27152+++ b/gui-compare/CompareContext.cs
27153@@ -26,6 +26,7 @@
27154 using System;
27155 using System.Collections.Generic;
27156 using System.Threading;
27157+using System.Linq;
27158
27159 namespace GuiCompare {
27160
27161@@ -153,7 +154,7 @@ namespace GuiCompare {
27162 void CompareBaseTypes (ComparisonNode parent, ICompHasBaseType reference_type, ICompHasBaseType target_type)
27163 {
27164 if (reference_type.GetBaseType() != target_type.GetBaseType()) {
27165- parent.AddError (String.Format ("reference has base class of {0}, target has base class of {1}",
27166+ parent.AddError (String.Format ("Expected base class of {0} but found {1}",
27167 reference_type.GetBaseType(),
27168 target_type.GetBaseType()));
27169 }
27170@@ -162,7 +163,7 @@ namespace GuiCompare {
27171 string ref_mod = (reference_type.IsAbstract && reference_type.IsSealed) ? "static" : "abstract";
27172 string tar_mod = (target_type.IsAbstract && target_type.IsSealed) ? "static" : "abstract";
27173
27174- parent.AddError (String.Format ("reference is {0} {2}, target is {1} {3}",
27175+ parent.AddError (String.Format ("reference is {0} {2}, is {1} {3}",
27176 reference_type.IsAbstract ? null : "not", target_type.IsAbstract ? null : "not",
27177 ref_mod, tar_mod));
27178 } else if (reference_type.IsSealed != target_type.IsSealed) {
27179@@ -211,19 +212,15 @@ namespace GuiCompare {
27180 {
27181 var r = reference.GetTypeParameters ();
27182 var t = target.GetTypeParameters ();
27183- if (r == null && t == null)
27184+ if (r == null && t == null || (r == null && t != null) || (r != null && t == null))
27185 return;
27186
27187- if (r.Count != t.Count) {
27188- throw new NotImplementedException (string.Format ("Should never happen with valid data ({0} != {1})", r.Count, t.Count));
27189- }
27190-
27191 for (int i = 0; i < r.Count; ++i) {
27192 var r_i = r [i];
27193 var t_i = t [i];
27194
27195 if (r_i.GenericAttributes != t_i.GenericAttributes) {
27196- parent.AddError (string.Format ("reference type parameter {2} has {0} generic attributes, target type parameter {3} has {1} generic attributes",
27197+ parent.AddError (string.Format ("Expected type parameter {2} with {0} generic attributes but found type parameter {3} with {1} generic attributes",
27198 CompGenericParameter.GetGenericAttributeDesc (r_i.GenericAttributes),
27199 CompGenericParameter.GetGenericAttributeDesc (t_i.GenericAttributes),
27200 r_i.Name,
27201@@ -324,13 +321,42 @@ namespace GuiCompare {
27202
27203 List<CompNamed> reference_attrs = reference_container.GetAttributes ();
27204 List<CompNamed> target_attrs = target_container.GetAttributes ();
27205-
27206- reference_attrs.Sort (CompNamed.Compare);
27207- target_attrs.Sort (CompNamed.Compare);
27208+
27209+ Comparison<CompNamed> comp = (x, y) => {
27210+ var r = CompNamed.Compare (x, y);
27211+ if (r != 0)
27212+ return r;
27213+
27214+ var xa = ((CompAttribute)x).Properties.Values.ToList ();
27215+ var ya = ((CompAttribute)y).Properties.Values.ToList ();
27216+
27217+ for (int i = 0; i < Math.Min (xa.Count, ya.Count); ++i) {
27218+ r = xa[i].CompareTo (ya[i]);
27219+ if (r != 0)
27220+ return r;
27221+ }
27222+
27223+ return 0;
27224+ };
27225+
27226+ reference_attrs.Sort (comp);
27227+ target_attrs.Sort (comp);
27228
27229 while (m < reference_attrs.Count || a < target_attrs.Count) {
27230 if (m == reference_attrs.Count) {
27231- AddExtra (parent, target_attrs[a]);
27232+
27233+ switch (target_attrs[a].Name) {
27234+ case "System.Diagnostics.DebuggerDisplayAttribute":
27235+ case "System.Runtime.CompilerServices.AsyncStateMachineAttribute":
27236+ case "System.Runtime.CompilerServices.IteratorStateMachineAttribute":
27237+ case "System.Diagnostics.DebuggerBrowsableAttribute":
27238+ // Ignore extra attributes in Mono source code
27239+ break;
27240+ default:
27241+ AddExtra (parent, target_attrs[a]);
27242+ break;
27243+ }
27244+
27245 a++;
27246 continue;
27247 }
27248@@ -345,10 +371,9 @@ namespace GuiCompare {
27249
27250 if (c == 0) {
27251 /* the names match, further investigation is required */
27252-// Console.WriteLine ("method {0} is in both, doing more comparisons", reference_list[m].Name);
27253 ComparisonNode comparison = target_attrs[a].GetComparisonNode();
27254 parent.AddChild (comparison);
27255- //CompareParameters (comparison, reference_list[m], target_namespace [target_list[a]]);
27256+ CompareAttributeArguments (comparison, (CompAttribute)reference_attrs[m], (CompAttribute)target_attrs[a]);
27257 m++;
27258 a++;
27259 }
27260@@ -364,27 +389,120 @@ namespace GuiCompare {
27261 }
27262 }
27263 }
27264+
27265+ void CompareAttributeArguments (ComparisonNode parent, CompAttribute referenceAttribute, CompAttribute actualAttribute)
27266+ {
27267+ // Ignore all parameter differences for some attributes
27268+ switch (referenceAttribute.Name) {
27269+ case "System.Diagnostics.DebuggerDisplayAttribute":
27270+ case "System.Diagnostics.DebuggerTypeProxyAttribute":
27271+ case "System.Runtime.CompilerServices.CompilationRelaxationsAttribute":
27272+ case "System.Reflection.AssemblyFileVersionAttribute":
27273+ case "System.Reflection.AssemblyCompanyAttribute":
27274+ case "System.Reflection.AssemblyCopyrightAttribute":
27275+ case "System.Reflection.AssemblyProductAttribute":
27276+ case "System.Reflection.AssemblyTrademarkAttribute":
27277+ case "System.Reflection.AssemblyInformationalVersionAttribute":
27278+ case "System.Reflection.AssemblyKeyFileAttribute":
27279+
27280+ // Don't care about these for now
27281+ case "System.ComponentModel.EditorAttribute":
27282+ case "System.ComponentModel.DesignerAttribute":
27283+ return;
27284+ }
27285+
27286+ foreach (var entry in referenceAttribute.Properties) {
27287+ if (!actualAttribute.Properties.ContainsKey (entry.Key)) {
27288+
27289+ //
27290+ // Ignore missing value difference for default values
27291+ //
27292+ switch (referenceAttribute.Name) {
27293+ case "System.AttributeUsageAttribute":
27294+ // AllowMultiple defaults to false
27295+ if (entry.Key == "AllowMultiple" && entry.Value == "False")
27296+ continue;
27297+ // Inherited defaults to true
27298+ if (entry.Key == "Inherited" && entry.Value == "True")
27299+ continue;
27300+ break;
27301+ case "System.ObsoleteAttribute":
27302+ if (entry.Key == "IsError" && entry.Value == "False")
27303+ continue;
27304+
27305+ if (entry.Key == "Message")
27306+ continue;
27307+
27308+ break;
27309+ }
27310+
27311+ parent.AddError (String.Format ("Property `{0}' value is not set. Expected value: {1}", entry.Key, entry.Value));
27312+ parent.Status = ComparisonStatus.Error;
27313+ continue;
27314+ }
27315+
27316+ var target_value = actualAttribute.Properties[entry.Key];
27317+
27318+ switch (referenceAttribute.Name) {
27319+ case "System.Runtime.CompilerServices.TypeForwardedFromAttribute":
27320+ if (entry.Key == "AssemblyFullName")
27321+ target_value = target_value.Replace ("neutral", "Neutral");
27322+ break;
27323+ case "System.Runtime.InteropServices.GuidAttribute":
27324+ if (entry.Key == "Value")
27325+ target_value = target_value.ToUpperInvariant ();
27326+ break;
27327+ case "System.ObsoleteAttribute":
27328+ if (entry.Key == "Message")
27329+ continue;
27330+
27331+ break;
27332+ }
27333+
27334+ if (target_value != entry.Value) {
27335+ parent.AddError (String.Format ("Expected value `{0}' for attribute property `{1}' but found `{2}'", entry.Value, entry.Key, target_value));
27336+ parent.Status = ComparisonStatus.Error;
27337+ }
27338+ }
27339+
27340+
27341+ if (referenceAttribute.Properties.Count != actualAttribute.Properties.Count) {
27342+ foreach (var entry in actualAttribute.Properties) {
27343+ if (!referenceAttribute.Properties.ContainsKey (entry.Key)) {
27344+ parent.AddError (String.Format ("Property `{0}' should not be set", entry.Key));
27345+ parent.Status = ComparisonStatus.Error;
27346+ break;
27347+ }
27348+ }
27349+ }
27350+
27351+
27352+ return;
27353+ }
27354
27355 void CompareMembers (ComparisonNode parent,
27356 ICompMemberContainer reference_container, ICompMemberContainer target_container)
27357 {
27358+ bool is_sealed = reference_container.IsSealed;
27359+
27360 CompareMemberLists (parent,
27361- reference_container.GetInterfaces(), target_container.GetInterfaces());
27362+ reference_container.GetInterfaces(), target_container.GetInterfaces(), is_sealed);
27363 CompareMemberLists (parent,
27364- reference_container.GetConstructors(), target_container.GetConstructors());
27365+ reference_container.GetConstructors(), target_container.GetConstructors(), is_sealed);
27366 CompareMemberLists (parent,
27367- reference_container.GetMethods(), target_container.GetMethods());
27368+ reference_container.GetMethods(), target_container.GetMethods(), is_sealed);
27369 CompareMemberLists (parent,
27370- reference_container.GetProperties(), target_container.GetProperties());
27371+ reference_container.GetProperties(), target_container.GetProperties(), is_sealed);
27372 CompareMemberLists (parent,
27373- reference_container.GetFields(), target_container.GetFields());
27374+ reference_container.GetFields(), target_container.GetFields(), is_sealed);
27375 CompareMemberLists (parent,
27376- reference_container.GetEvents(), target_container.GetEvents());
27377+ reference_container.GetEvents(), target_container.GetEvents(), is_sealed);
27378 }
27379
27380 void CompareMemberLists (ComparisonNode parent,
27381 List<CompNamed> reference_list,
27382- List<CompNamed> target_list)
27383+ List<CompNamed> target_list,
27384+ bool isSealed)
27385 {
27386 int m = 0, a = 0;
27387
27388@@ -427,9 +545,9 @@ namespace GuiCompare {
27389 // Try to give some hints to the developer, best we can do with
27390 // strings.
27391 string extra_msg = "";
27392- if (reference_access.IndexOf ("Public, Final, Virtual, HideBySig") != -1 &&
27393+ if (reference_access.IndexOf ("Private, Final, Virtual, HideBySig") != -1 &&
27394 target_access.IndexOf ("Public, HideBySig") != -1){
27395- extra_msg = "\n\t\t<b>Hint:</b> reference uses an implicit interface implementation, target doesn't";
27396+ extra_msg = "\n\t\t<b>Hint:</b> reference uses an explicit interface implementation, target doesn't";
27397 }
27398
27399 comparison.AddError (String.Format ("reference access is '<i>{0}</i>', target access is '<i>{1}</i>'{2}",
27400@@ -447,13 +565,53 @@ namespace GuiCompare {
27401
27402 CompareTypeParameters (comparison, r_method, t_method);
27403 CompareParameters (comparison, r_method, t_method);
27404+ } else if (reference_list[m] is CompProperty) {
27405+ var m1 = ((CompProperty) reference_list[m]).GetMethods ();
27406+ var m2 = ((CompProperty) target_list[a]).GetMethods ();
27407+ if (m1.Count != m2.Count) {
27408+ comparison.AddError (String.Format ("Expected {0} accessors but found {1}", m1.Count, m2.Count));
27409+ comparison.Status = ComparisonStatus.Error;
27410+ } else {
27411+ for (int i = 0; i < m1.Count; ++i) {
27412+ string reference_access = ((CompMember) m1[i]).GetMemberAccess();
27413+ string target_access = ((CompMember) m2[i]).GetMemberAccess();
27414+ if (reference_access != target_access) {
27415+ // Try to give some hints to the developer, best we can do with
27416+ // strings.
27417+ string extra_msg = "";
27418+ if (reference_access.IndexOf ("Private, Final, Virtual, HideBySig") != -1 &&
27419+ target_access.IndexOf ("Public, HideBySig") != -1){
27420+ extra_msg = "\n\t\t<b>Hint:</b> reference uses an explicit interface implementation, target doesn't";
27421+ }
27422+
27423+ comparison.AddError (String.Format ("reference access is '<i>{0}</i>', target access is '<i>{1}</i>'{2}",
27424+ reference_access, target_access, extra_msg));
27425+ comparison.Status = ComparisonStatus.Error;
27426+ break;
27427+ }
27428+ }
27429+
27430+ if (m1[0].Name[0] == m2[0].Name[0]) {
27431+ CompareAttributes (comparison, (ICompAttributeContainer)m1[0], (ICompAttributeContainer)m2[0]);
27432+ if (m1.Count > 1)
27433+ CompareAttributes (comparison, (ICompAttributeContainer)m1[1], (ICompAttributeContainer)m2[1]);
27434+ } else {
27435+ CompareAttributes (comparison, (ICompAttributeContainer)m1[0], (ICompAttributeContainer)m2[1]);
27436+ if (m1.Count > 1)
27437+ CompareAttributes (comparison, (ICompAttributeContainer)m1[1], (ICompAttributeContainer)m2[0]);
27438+ }
27439+ }
27440+
27441+ // Compare indexer parameters
27442+ if (m1.Count == m2.Count)
27443+ CompareParameters (comparison, (ICompParameters) m1[0], (ICompParameters) m2[0]);
27444 }
27445
27446 if (reference_list[m] is CompField) {
27447 var v_ref = ((CompField)reference_list[m]).GetLiteralValue();
27448 var v_tar = ((CompField)target_list[a]).GetLiteralValue();
27449 if (v_ref != v_tar) {
27450- comparison.AddError (String.Format ("reference field has value {0}, target field has value {1}", v_ref, v_tar));
27451+ comparison.AddError (String.Format ("Expected field value {0} but found value {1}", v_ref, v_tar));
27452 comparison.Status = ComparisonStatus.Error;
27453 }
27454 }
27455@@ -476,13 +634,23 @@ namespace GuiCompare {
27456 a++;
27457 }
27458 else if (c < 0) {
27459- /* reference name is before target name, reference name is missing from target */
27460- AddMissing (parent, reference_list[m]);
27461+ if (isSealed && reference_list[m].Name.Contains ("~")) {
27462+ // Ignore finalizer differences in sealed classes
27463+ } else {
27464+ /* reference name is before target name, reference name is missing from target */
27465+ AddMissing (parent, reference_list[m]);
27466+ }
27467+
27468 m++;
27469 }
27470 else {
27471- /* reference name is after target name, target name is extra */
27472- AddExtra (parent, target_list[a]);
27473+ if (isSealed && target_list[a].Name.Contains ("~")) {
27474+ // Ignore finalizer differences in sealed classes
27475+ } else {
27476+ /* reference name is after target name, target name is extra */
27477+ AddExtra (parent, target_list[a]);
27478+ }
27479+
27480 a++;
27481 }
27482 }
27483diff --git a/gui-compare/InfoManager.cs b/gui-compare/InfoManager.cs
27484index 1f8199d..246b2cd 100644
27485--- a/gui-compare/InfoManager.cs
27486+++ b/gui-compare/InfoManager.cs
27487@@ -205,6 +205,7 @@ namespace GuiCompare
27488 "System.AddIn",
27489 "System.AddIn.Contract",
27490 "System.Configuration",
27491+ "System.ComponentModel.DataAnnotations",
27492 "System.Core",
27493 // "System.Configuration.Install",
27494 "System.Data",
27495@@ -364,12 +365,132 @@ namespace GuiCompare
27496 "WindowsBase",
27497 // "XamlBuildTask"
27498 };
27499-
27500+
27501+ string [] api_4_5 = {
27502+ "mscorlib",
27503+
27504+ "System.Activities",
27505+ "System.Activities.Core.Presentation",
27506+ "System.Activities.DurableInstancing",
27507+ "System.Activities.Design",
27508+ "System.AddIn.Contract",
27509+ "System.AddIn",
27510+ "System.ComponentModel.Composition",
27511+ "System.ComponentModel.DataAnnotations",
27512+ "System.configuration",
27513+ // "System.Configuration.Install",
27514+ "System.Core",
27515+ "System.Data.DataSetExtensions",
27516+ "System.Data",
27517+ "System.Data.Entity.Design",
27518+ "System.Data.Entity",
27519+ "System.Data.Linq",
27520+ "System.Data.OracleClient",
27521+ "System.Data.Services.Client",
27522+ "System.Data.Services.Design",
27523+ "System.Data.Services",
27524+ "System.Data.SqlXml",
27525+ "System.Deployment",
27526+ "System.Design",
27527+ "System.Device",
27528+ // "System.DirectoryServices.AccountManagement",
27529+ "System.DirectoryServices",
27530+ // "System.DirectoryServices.Protocols",
27531+ "System",
27532+ "System.Drawing.Design",
27533+ "System.Drawing",
27534+ "System.Dynamic",
27535+ "System.EnterpriseServices",
27536+ "System.EnterpriseServices.Thunk",
27537+ "System.EnterpriseServices.Wrapper",
27538+ "System.IdentityModel",
27539+ "System.IdentityModel.Selectors",
27540+ "System.IO.Log",
27541+ "System.IO.Compression",
27542+ "System.IO.Compression.FileSystem",
27543+ "System.Management",
27544+ // "System.Management.Instrumentation",
27545+ "System.Messaging",
27546+ "System.Net",
27547+ "System.Net.Http",
27548+ "System.Net.Http.WebRequest",
27549+ "System.Numerics",
27550+ "System.Printing",
27551+ "System.Runtime.Caching",
27552+ "System.Runtime.Remoting",
27553+ "System.Runtime.Serialization",
27554+ "System.Runtime.Serialization.Formatters.Soap",
27555+ "System.Security",
27556+ "System.ServiceModel.Activation",
27557+ "System.ServiceModel.Activities",
27558+ "System.ServiceModel.Channels",
27559+ "System.ServiceModel.Discovery",
27560+ "System.ServiceModel",
27561+ "System.ServiceModel.Routing",
27562+ "System.ServiceModel.Web",
27563+ "System.ServiceProcess",
27564+ "System.Speech",
27565+ "System.Threading.Tasks.Dataflow",
27566+ "System.Transactions",
27567+ "System.Web.Abstractions",
27568+ "System.Web.ApplicationServices",
27569+ "System.Web.DataVisualization.Design",
27570+ "System.Web.DataVisualization",
27571+ "System.Web",
27572+ "System.Web.DynamicData.Design",
27573+ "System.Web.DynamicData",
27574+ "System.Web.Entity.Design",
27575+ "System.Web.Entity",
27576+ // "System.Web.Extensions.Design",
27577+ "System.Web.Extensions",
27578+ // "System.Web.Mobile",
27579+ // "System.Web.RegularExpressions",
27580+ "System.Web.Routing",
27581+ "System.Web.Services",
27582+ "System.Windows.Forms.DataVisualization.Design",
27583+ "System.Windows.Forms.DataVisualization",
27584+ "System.Windows.Forms",
27585+ "System.Windows.Presentation",
27586+ "System.Workflow.Activities",
27587+ "System.Workflow.ComponentModel",
27588+ "System.Workflow.Runtime",
27589+ "System.WorkflowServices",
27590+ "System.Xaml",
27591+ "System.Xaml.Hosting",
27592+ "System.Xml",
27593+ "System.Xml.Linq",
27594+
27595+ "Microsoft.Build.Conversion.v4.0",
27596+ "Microsoft.Build",
27597+ "Microsoft.Build.Engine",
27598+ "Microsoft.Build.Framework",
27599+ "Microsoft.Build.Tasks.v4.0",
27600+ "Microsoft.Build.Utilities.v4.0",
27601+ "Microsoft.CSharp",
27602+ "Microsoft.JScript",
27603+ "Microsoft.VisualBasic.Compatibility.Data",
27604+ "Microsoft.VisualBasic.Compatibility",
27605+ "Microsoft.VisualBasic",
27606+
27607+ "PresentationBuildTasks",
27608+ "PresentationCore",
27609+ "PresentationFramework.Aero",
27610+ "PresentationFramework.Classic",
27611+ "PresentationFramework",
27612+ "PresentationFramework.Luna",
27613+ "PresentationFramework.Royale",
27614+ "PresentationUI",
27615+ "ReachFramework",
27616+
27617+ "WindowsBase",
27618+ // "XamlBuildTask"
27619+ };
27620+
27621 const string masterinfos_version = "2.8";
27622
27623 static Uri GetMasterInfoUri (string file)
27624 {
27625- return new Uri (string.Format ("http://mono.ximian.com/masterinfos/{0}/{1}", masterinfos_version, file));
27626+ return new Uri (string.Format ("http://go-mono.com/masterinfos/{0}/{1}", masterinfos_version, file));
27627 }
27628
27629 public static void Init ()
27630@@ -417,9 +538,13 @@ namespace GuiCompare
27631 break;
27632
27633 case "4.0":
27634- u = GetMasterInfoUri ("masterinfos-4.0.tar.gz");
27635+ u = GetMasterInfoUri ("masterinfos-4.0.tar.gz");
27636 break;
27637-
27638+
27639+ case "4.5":
27640+ u = GetMasterInfoUri ("masterinfos-4.5.tar.gz");
27641+ break;
27642+
27643 case "SL2":
27644 u = GetMasterInfoUri ("masterinfos-SL2.tar.gz");
27645 break;
27646@@ -564,6 +689,8 @@ namespace GuiCompare
27647 main.Title = String.Format ("{0} to {1}", assemblyfile, masterinfo);
27648 });
27649 });
27650+
27651+ main.SetComparedProfile (profile);
27652 }
27653
27654 void Populate (Menu container, string caption, string pdir, string collection, string [] elements)
27655@@ -572,7 +699,7 @@ namespace GuiCompare
27656 string MONO_GAC_PREFIX = Environment.GetEnvironmentVariable ("MONO_GAC_PREFIX");
27657 string[] gac_prefixes = null;
27658
27659- if (MONO_GAC_PREFIX != null)
27660+ if (!string.IsNullOrEmpty (MONO_GAC_PREFIX))
27661 gac_prefixes = MONO_GAC_PREFIX.Split (':');
27662
27663 MenuItem item = new MenuItem (caption);
27664@@ -671,12 +798,17 @@ namespace GuiCompare
27665 //
27666 // Constructor
27667 //
27668- public InfoManager (MainWindow main)
27669+ public InfoManager (MainWindow main, string profilePath)
27670 {
27671 this.main = main;
27672
27673- string corlibdir = System.IO.Path.GetDirectoryName (typeof (int).Assembly.Location);
27674- monodir = System.IO.Path.GetFullPath (System.IO.Path.Combine (corlibdir, ".."));
27675+ if (profilePath == null) {
27676+ string corlibdir = System.IO.Path.GetDirectoryName (typeof (int).Assembly.Location);
27677+ monodir = System.IO.Path.GetFullPath (System.IO.Path.Combine (corlibdir, ".."));
27678+ } else {
27679+ monodir = profilePath;
27680+ }
27681+
27682 moondir = System.IO.Path.Combine (monodir, @"../moonlight/plugin");
27683
27684 // Work around limitation in Stetic, there is no way
27685@@ -728,14 +860,15 @@ namespace GuiCompare
27686 Populate (sub, "API 3.0 sp1", GetVersionPath ("2.0", "net_2_0"), "3.0", api_3_0);
27687 Populate (sub, "API 3.5 sp1", GetVersionPath ("2.0", "net_2_0"), "3.5", api_3_5);
27688 Populate (sub, "API 4.0", GetVersionPath ("4.0", "net_4_0"), "4.0", api_4_0);
27689+ Populate (sub, "API 4.5", GetVersionPath ("4.5", "net_4_5"), "4.5", api_4_5);
27690 // Populate (sub, "Silverlight 2.0", GetVersionPath ("2.1", "net_2_1"), "SL2", api_sl2);
27691 // Populate (sub, "Silverlight 3.0", GetVersionPath ("2.1", "net_2_1"), "SL3", api_sl2);
27692 Populate (sub, "Silverlight 4.0", GetVersionPath ("2.1", "net_2_1"), "SL4", api_sl4);
27693 }
27694
27695- static string GetVersionPath (string version, string profile)
27696+ string GetVersionPath (string version, string profile)
27697 {
27698- if (string.IsNullOrEmpty (Environment.GetEnvironmentVariable ("MONO_PATH")))
27699+ if (!monodir.Contains (Path.Combine ("mcs", "class", "lib")))
27700 return version;
27701
27702 // Developer's version pointing to /mcs/class/lib/<profile>/
27703diff --git a/gui-compare/Main.cs b/gui-compare/Main.cs
27704index 49c4617..e522501 100644
27705--- a/gui-compare/Main.cs
27706+++ b/gui-compare/Main.cs
27707@@ -36,7 +36,7 @@ namespace GuiCompare
27708 {
27709 Application.Init ();
27710
27711- try {
27712+ try {
27713 InfoManager.Init ();
27714 } catch (Exception e) {
27715 Dialog d = new Dialog ("Error", null, DialogFlags.Modal, new object [] {
27716@@ -46,7 +46,12 @@ namespace GuiCompare
27717 d.Run ();
27718 return;
27719 }
27720- MainWindow win = new MainWindow ();
27721+
27722+ string profile_path = null;
27723+ if (args.Length != 0 && args[0].StartsWith ("--profile-path="))
27724+ profile_path = args[0].Substring (15);
27725+
27726+ MainWindow win = new MainWindow (profile_path);
27727 win.Show ();
27728 if (args.Length == 2 && File.Exists (args [0]) && File.Exists (args [1])){
27729 win.ComparePaths (args [0], args [1]);
27730diff --git a/gui-compare/MainWindow.cs b/gui-compare/MainWindow.cs
27731index 0da25a4..2792d0d 100644
27732--- a/gui-compare/MainWindow.cs
27733+++ b/gui-compare/MainWindow.cs
27734@@ -38,6 +38,7 @@ public partial class MainWindow: Gtk.Window
27735 InfoManager info_manager;
27736 Func<CompAssembly> reference_loader, target_loader;
27737 CompareContext context;
27738+ string active_profile;
27739
27740 static readonly Regex markupRegex = new Regex (@"<(?:[^""']+?|.+?(?:""|').*?(?:""|')?.*?)*?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
27741 static Gdk.Pixbuf classPixbuf, delegatePixbuf, enumPixbuf;
27742@@ -103,7 +104,7 @@ public partial class MainWindow: Gtk.Window
27743 Gdk.Color.Parse ("#000000", ref black);
27744 }
27745
27746- public MainWindow () : base(Gtk.WindowType.Toplevel)
27747+ public MainWindow (string profilePath) : base(Gtk.WindowType.Toplevel)
27748 {
27749 Build ();
27750 notebook1.Page = 1;
27751@@ -113,7 +114,7 @@ public partial class MainWindow: Gtk.Window
27752 //
27753 // Configure the GUI
27754 //
27755- info_manager = new InfoManager (this);
27756+ info_manager = new InfoManager (this, profilePath);
27757
27758 treeStore = new Gtk.TreeStore (typeof (string), // Name
27759 typeof (Gdk.Pixbuf), typeof (Gdk.Pixbuf), // TypeIcon, StatusIcon
27760@@ -245,7 +246,7 @@ public partial class MainWindow: Gtk.Window
27761
27762 string msdnUrl = n != null ? n.MSDNUrl : null;
27763 if (!String.IsNullOrEmpty (msdnUrl))
27764- Status = msdnUrl;
27765+ Status = GetMSDNVersionedUrl (msdnUrl);
27766 else
27767 Status = String.Empty;
27768 }
27769@@ -261,7 +262,7 @@ public partial class MainWindow: Gtk.Window
27770 return;
27771
27772 System.Diagnostics.Process browser = new System.Diagnostics.Process ();
27773- browser.StartInfo.FileName = n.MSDNUrl;
27774+ browser.StartInfo.FileName = GetMSDNVersionedUrl (n.MSDNUrl);
27775 browser.StartInfo.UseShellExecute = true;
27776 browser.Start ();
27777 };
27778@@ -361,6 +362,22 @@ public partial class MainWindow: Gtk.Window
27779 tag.Underline = Pango.Underline.Single;
27780 buffer.TagTable.Add (tag);
27781 }
27782+
27783+ string GetMSDNVersionedUrl (string url)
27784+ {
27785+ switch (active_profile) {
27786+ case "2.0":
27787+ return url.Replace (".aspx", "(v=VS.80).aspx");
27788+ case "3.0":
27789+ return url.Replace (".aspx", "(v=VS.90).aspx");
27790+ case "4.0":
27791+ return url.Replace (".aspx", "(v=VS.100).aspx");
27792+ case "4.5":
27793+ return url.Replace (".aspx", "(v=VS.110).aspx");
27794+ default:
27795+ return url;
27796+ }
27797+ }
27798
27799 void InsertWithMarkup (TextBuffer buffer, ref TextIter iter, string text)
27800 {
27801@@ -509,6 +526,11 @@ public partial class MainWindow: Gtk.Window
27802 SetTarget (delegate { return new CecilAssembly (cd.TargetPath); });
27803 }
27804
27805+ public void SetComparedProfile (string profile)
27806+ {
27807+ active_profile = profile;
27808+ }
27809+
27810 public void StartCompare (WaitCallback done)
27811 {
27812 AdditionalInfoWindow.Visible = false;
27813diff --git a/gui-compare/Makefile.am b/gui-compare/Makefile.am
27814index ef805eb..59829b2 100644
27815--- a/gui-compare/Makefile.am
27816+++ b/gui-compare/Makefile.am
27817@@ -56,4 +56,4 @@ assemblies = -r:System -r:System.Core -r:Mono.Posix -r:System.Xml
27818 ress= $(foreach res,$(gui_compare_resources), $(addprefix -resource:,$(res)),$(notdir $(res)))
27819
27820 gui-compare.exe: $(gui_compare_sources) $(gui_compare_resources)
27821- $(GMCS) -noconfig -codepage:utf8 -warn:4 -optimize+ -debug -define:DEBUG -target:exe -out:gui-compare.exe $(gui_compare_sources) $(ress) $(packages) $(assemblies)
27822+ $(DMCS) -noconfig -codepage:utf8 -warn:4 -optimize+ -debug -define:DEBUG -target:exe -out:gui-compare.exe $(gui_compare_sources) $(ress) $(packages) $(assemblies)
27823diff --git a/gui-compare/MasterMetadata.cs b/gui-compare/MasterMetadata.cs
27824index f25468e..189b42c 100644
27825--- a/gui-compare/MasterMetadata.cs
27826+++ b/gui-compare/MasterMetadata.cs
27827@@ -841,6 +841,9 @@ namespace GuiCompare {
27828 if (props.Count == 0)
27829 return;
27830
27831+ foreach (var entry in props)
27832+ Properties.Add (entry.Key, entry.Value);
27833+
27834 if (name == "System.Runtime.CompilerServices.TypeForwardedToAttribute") {
27835 string dest;
27836 if (props.TryGetValue ("Destination", out dest) && !String.IsNullOrEmpty (dest))
27837diff --git a/gui-compare/Masterinfo.cs b/gui-compare/Masterinfo.cs
27838index b91f99b..bc13a63 100644
27839--- a/gui-compare/Masterinfo.cs
27840+++ b/gui-compare/Masterinfo.cs
27841@@ -205,8 +205,13 @@ namespace GuiCompare {
27842 string name = n.Attributes ["name"].Value;
27843 if (CheckIfAdd (name, n)) {
27844 string key = GetNodeKey (name, n);
27845- //keys.Add (key, name);
27846- keys [key] = name;
27847+ if (keys.Contains (key)) {
27848+ if ((string) keys[key] != name)
27849+ throw new NotImplementedException ("Attribute with same name but diffent value");
27850+ } else {
27851+ keys.Add (key, name);
27852+ }
27853+
27854 LoadExtraData (key, n);
27855 }
27856 }
27857@@ -532,24 +537,10 @@ namespace GuiCompare {
27858
27859 public class XMLAttributeProperties: XMLNameGroup
27860 {
27861- static Dictionary <string, string> ignored_properties;
27862 SortedDictionary <string, string> properties;
27863
27864 static XMLAttributeProperties ()
27865 {
27866-
27867- ignored_properties = new Dictionary <string, string> ();
27868- ignored_properties.Add ("System.Reflection.AssemblyKeyFileAttribute", "KeyFile");
27869- ignored_properties.Add ("System.Reflection.AssemblyCompanyAttribute", "Company");
27870- ignored_properties.Add ("System.Reflection.AssemblyConfigurationAttribute", "Configuration");
27871- ignored_properties.Add ("System.Reflection.AssemblyCopyrightAttribute", "Copyright");
27872- ignored_properties.Add ("System.Reflection.AssemblyProductAttribute", "Product");
27873- ignored_properties.Add ("System.Reflection.AssemblyTrademarkAttribute", "Trademark");
27874- ignored_properties.Add ("System.Reflection.AssemblyInformationalVersionAttribute", "InformationalVersion");
27875-
27876- ignored_properties.Add ("System.ObsoleteAttribute", "Message");
27877- ignored_properties.Add ("System.IO.IODescriptionAttribute", "Description");
27878- ignored_properties.Add ("System.Diagnostics.MonitoringDescriptionAttribute", "Description");
27879 }
27880
27881 string attribute;
27882@@ -571,15 +562,9 @@ namespace GuiCompare {
27883 if (node.ChildNodes == null)
27884 return;
27885
27886- string ignored;
27887-
27888- if (!ignored_properties.TryGetValue (attribute, out ignored))
27889- ignored = null;
27890
27891 foreach (XmlNode n in node.ChildNodes) {
27892 string name = n.Attributes["name"].Value;
27893- if (ignored != null && ignored == name)
27894- continue;
27895
27896 if (n.Attributes["null"] != null) {
27897 Properties.Add (name, null);
27898@@ -1045,9 +1030,11 @@ namespace GuiCompare {
27899
27900 public override string GetNodeKey (string name, XmlNode node)
27901 {
27902- if (genericParameters != null)
27903- name = name + ":" + genericParameters.Count;
27904-
27905+ XmlNode genericNode = node.SelectSingleNode ("generic-parameters");
27906+ if (genericNode != null) {
27907+ name = name + "`" + genericNode.ChildNodes.Count;
27908+ }
27909+
27910 // for explicit/implicit operators we need to include the return
27911 // type in the key to allow matching; as a side-effect, differences
27912 // in return types will be reported as extra/missing methods
27913diff --git a/gui-compare/Metadata.cs b/gui-compare/Metadata.cs
27914index f365f7c..a04f39e 100644
27915--- a/gui-compare/Metadata.cs
27916+++ b/gui-compare/Metadata.cs
27917@@ -69,6 +69,8 @@ namespace GuiCompare {
27918
27919 public interface ICompMemberContainer
27920 {
27921+ bool IsSealed { get; }
27922+
27923 List<CompNamed> GetInterfaces ();
27924 List<CompNamed> GetConstructors();
27925 List<CompNamed> GetMethods();
27926@@ -130,27 +132,33 @@ namespace GuiCompare {
27927
27928 public static int Compare (CompNamed x, CompNamed y)
27929 {
27930- int res = string.Compare (x.Name, y.Name);
27931- if (res != 0)
27932- return res;
27933-
27934 var x_g = x as CompMethod;
27935 var y_g = y as CompMethod;
27936+
27937 if (x_g == null || y_g == null)
27938- return res;
27939+ return string.Compare (x.Name, y.Name);
27940
27941 var x_tp = x_g.GetTypeParameters ();
27942+ if (x_tp != null && x_tp.Count == 0)
27943+ x_tp = null;
27944+
27945 var y_tp = y_g.GetTypeParameters ();
27946+ if (y_tp != null && y_tp.Count == 0)
27947+ y_tp = null;
27948+
27949 if (x_tp == null && y_tp != null)
27950 return -1;
27951
27952 if (x_tp != null && y_tp == null)
27953 return 1;
27954
27955- if (x_tp == null && y_tp == null)
27956- return res;
27957-
27958- return x_tp.Count.CompareTo (y_tp.Count);
27959+ if (x_tp != null && y_tp != null) {
27960+ var res = x_tp.Count.CompareTo (y_tp.Count);
27961+ if (res != 0)
27962+ return res;
27963+ }
27964+
27965+ return string.Compare (x.Name, y.Name);
27966 }
27967
27968 string displayName;
27969@@ -338,7 +346,10 @@ namespace GuiCompare {
27970 public CompAttribute (string typename)
27971 : base (typename, CompType.Attribute)
27972 {
27973+ Properties = new SortedDictionary<string, string> ();
27974 }
27975+
27976+ public IDictionary<string, string> Properties { get; private set; }
27977 }
27978
27979 public abstract class CompGenericParameter : CompNamed, ICompAttributeContainer {
27980diff --git a/gui-compare/gtk-gui/GuiCompare.CustomCompare.cs b/gui-compare/gtk-gui/GuiCompare.CustomCompare.cs
27981index 7ca40c7..a027fb2 100644
27982--- a/gui-compare/gtk-gui/GuiCompare.CustomCompare.cs
27983+++ b/gui-compare/gtk-gui/GuiCompare.CustomCompare.cs
27984@@ -5,17 +5,27 @@ namespace GuiCompare
27985 public partial class CustomCompare
27986 {
27987 private global::Gtk.HBox hbox1;
27988+
27989 private global::Gtk.Frame frame1;
27990+
27991 private global::Gtk.Alignment GtkAlignment2;
27992+
27993 private global::guicompare.ProviderSelector reference;
27994+
27995 private global::Gtk.Label GtkLabel4;
27996+
27997 private global::Gtk.Frame frame2;
27998+
27999 private global::Gtk.Alignment GtkAlignment3;
28000+
28001 private global::guicompare.ProviderSelector target;
28002+
28003 private global::Gtk.Label GtkLabel9;
28004+
28005 private global::Gtk.Button buttonCancel;
28006+
28007 private global::Gtk.Button buttonOk;
28008-
28009+
28010 protected virtual void Build ()
28011 {
28012 global::Stetic.Gui.Initialize (this);
28013@@ -40,7 +50,9 @@ namespace GuiCompare
28014 this.GtkAlignment2.Name = "GtkAlignment2";
28015 this.GtkAlignment2.LeftPadding = ((uint)(12));
28016 // Container child GtkAlignment2.Gtk.Container+ContainerChild
28017- this.reference = null;
28018+ this.reference = new guicompare.ProviderSelector();
28019+ this.reference.Events = ((Gdk.EventMask)(256));
28020+ this.reference.Name = "reference";
28021 this.GtkAlignment2.Add (this.reference);
28022 this.frame1.Add (this.GtkAlignment2);
28023 this.GtkLabel4 = new global::Gtk.Label ();
28024@@ -61,7 +73,9 @@ namespace GuiCompare
28025 this.GtkAlignment3.Name = "GtkAlignment3";
28026 this.GtkAlignment3.LeftPadding = ((uint)(12));
28027 // Container child GtkAlignment3.Gtk.Container+ContainerChild
28028- this.target = null;
28029+ this.target = new guicompare.ProviderSelector();
28030+ this.target.Events = ((Gdk.EventMask)(256));
28031+ this.target.Name = "target";
28032 this.GtkAlignment3.Add (this.target);
28033 this.frame2.Add (this.GtkAlignment3);
28034 this.GtkLabel9 = new global::Gtk.Label ();
28035diff --git a/gui-compare/gtk-gui/MainWindow.cs b/gui-compare/gtk-gui/MainWindow.cs
28036index 6e2d738..addb7cd 100644
28037--- a/gui-compare/gtk-gui/MainWindow.cs
28038+++ b/gui-compare/gtk-gui/MainWindow.cs
28039@@ -4,53 +4,99 @@
28040 public partial class MainWindow
28041 {
28042 private global::Gtk.UIManager UIManager;
28043+
28044 private global::Gtk.Action File;
28045+
28046 private global::Gtk.Action quit;
28047+
28048 private global::Gtk.Action Compare;
28049+
28050 private global::Gtk.Action Custom;
28051+
28052 private global::Gtk.Action a;
28053+
28054 private global::Gtk.Action b;
28055+
28056 private global::Gtk.Action View;
28057+
28058 private global::Gtk.ToggleAction ShowMissing;
28059+
28060 private global::Gtk.ToggleAction ShowExtra;
28061+
28062 private global::Gtk.ToggleAction ShowPresent;
28063+
28064 private global::Gtk.ToggleAction ShowErrors;
28065+
28066 private global::Gtk.Action Refresh;
28067+
28068 private global::Gtk.ToggleAction ShowTodo;
28069+
28070 private global::Gtk.Action RecentComparisonsAction;
28071+
28072 private global::Gtk.ToggleAction ShowNotImplemented;
28073+
28074 private global::Gtk.Action ToggleRowExpansionAction;
28075+
28076 private global::Gtk.VBox vbox1;
28077+
28078 private global::Gtk.MenuBar menubar1;
28079+
28080 private global::Gtk.Notebook notebook1;
28081+
28082 private global::Gtk.ScrolledWindow GtkScrolledWindow;
28083+
28084 private global::Gtk.TreeView tree;
28085+
28086 private global::Gtk.Label label1;
28087+
28088 private global::Gtk.Label label3;
28089+
28090 private global::Gtk.Label label2;
28091+
28092 private global::Gtk.ScrolledWindow AdditionalInfoWindow;
28093+
28094 private global::Gtk.TextView AdditionalInfoText;
28095+
28096 private global::Gtk.Expander expander1;
28097+
28098 private global::Gtk.Table table1;
28099+
28100 private global::Gtk.Label label4;
28101+
28102 private global::Gtk.Label label5;
28103+
28104 private global::Gtk.Label label6;
28105+
28106 private global::Gtk.Label label7;
28107+
28108 private global::Gtk.Label label8;
28109+
28110 private global::Gtk.Label label9;
28111+
28112 private global::Gtk.Image legendImageError;
28113+
28114 private global::Gtk.Image legendImageExtra;
28115+
28116 private global::Gtk.Image legendImageMissing;
28117+
28118 private global::Gtk.Image legendImageNIEX;
28119+
28120 private global::Gtk.Image legendImageOK;
28121+
28122 private global::Gtk.Image legendImageTODO;
28123+
28124 private global::Gtk.VSeparator vseparator1;
28125+
28126 private global::Gtk.VSeparator vseparator2;
28127+
28128 private global::Gtk.VSeparator vseparator3;
28129+
28130 private global::Gtk.Label GtkLabel4;
28131+
28132 private global::Gtk.Statusbar statusbar1;
28133+
28134 private global::Gtk.ProgressBar progressbar1;
28135-
28136+
28137 protected virtual void Build ()
28138 {
28139 global::Stetic.Gui.Initialize (this);
28140diff --git a/gui-compare/gtk-gui/generated.cs b/gui-compare/gtk-gui/generated.cs
28141index 75935e2..71410df 100644
28142--- a/gui-compare/gtk-gui/generated.cs
28143+++ b/gui-compare/gtk-gui/generated.cs
28144@@ -5,7 +5,7 @@ namespace Stetic
28145 internal class Gui
28146 {
28147 private static bool initialized;
28148-
28149+
28150 internal static void Initialize (Gtk.Widget iconRenderer)
28151 {
28152 if ((Stetic.Gui.initialized == false)) {
28153@@ -13,12 +13,13 @@ namespace Stetic
28154 }
28155 }
28156 }
28157-
28158+
28159 internal class BinContainer
28160 {
28161 private Gtk.Widget child;
28162+
28163 private Gtk.UIManager uimanager;
28164-
28165+
28166 public static BinContainer Attach (Gtk.Bin bin)
28167 {
28168 BinContainer bc = new BinContainer ();
28169@@ -27,32 +28,32 @@ namespace Stetic
28170 bin.Added += new Gtk.AddedHandler (bc.OnAdded);
28171 return bc;
28172 }
28173-
28174+
28175 private void OnSizeRequested (object sender, Gtk.SizeRequestedArgs args)
28176 {
28177 if ((this.child != null)) {
28178 args.Requisition = this.child.SizeRequest ();
28179 }
28180 }
28181-
28182+
28183 private void OnSizeAllocated (object sender, Gtk.SizeAllocatedArgs args)
28184 {
28185 if ((this.child != null)) {
28186 this.child.Allocation = args.Allocation;
28187 }
28188 }
28189-
28190+
28191 private void OnAdded (object sender, Gtk.AddedArgs args)
28192 {
28193 this.child = args.Widget;
28194 }
28195-
28196+
28197 public void SetUiManager (Gtk.UIManager uim)
28198 {
28199 this.uimanager = uim;
28200 this.child.Realized += new System.EventHandler (this.OnRealized);
28201 }
28202-
28203+
28204 private void OnRealized (object sender, System.EventArgs args)
28205 {
28206 if ((this.uimanager != null)) {
28207@@ -65,14 +66,14 @@ namespace Stetic
28208 }
28209 }
28210 }
28211-
28212+
28213 internal class ActionGroups
28214 {
28215 public static Gtk.ActionGroup GetActionGroup (System.Type type)
28216 {
28217 return Stetic.ActionGroups.GetActionGroup (type.FullName);
28218 }
28219-
28220+
28221 public static Gtk.ActionGroup GetActionGroup (string name)
28222 {
28223 return null;
28224diff --git a/gui-compare/gtk-gui/gui.stetic b/gui-compare/gtk-gui/gui.stetic
28225index ce143e5..da239dc 100644
28226--- a/gui-compare/gtk-gui/gui.stetic
28227+++ b/gui-compare/gtk-gui/gui.stetic
28228@@ -1,8 +1,8 @@
28229 <?xml version="1.0" encoding="utf-8"?>
28230 <stetic-interface>
28231 <configuration>
28232- <images-root-path>..</images-root-path>
28233- <target-gtk-version>2.10</target-gtk-version>
28234+ <images-root-path>../../gui-compare</images-root-path>
28235+ <target-gtk-version>2.12</target-gtk-version>
28236 </configuration>
28237 <import>
28238 <widget-library name="glade-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
28239diff --git a/gui-compare/gtk-gui/guicompare.ProviderSelector.cs b/gui-compare/gtk-gui/guicompare.ProviderSelector.cs
28240index dbc910a..32b051f 100644
28241--- a/gui-compare/gtk-gui/guicompare.ProviderSelector.cs
28242+++ b/gui-compare/gtk-gui/guicompare.ProviderSelector.cs
28243@@ -5,12 +5,17 @@ namespace guicompare
28244 public partial class ProviderSelector
28245 {
28246 private global::Gtk.Table table2;
28247+
28248 private global::Gtk.FileChooserButton filechooserbutton1;
28249+
28250 private global::Gtk.FileChooserButton filechooserbutton2;
28251+
28252 private global::Gtk.Label label2;
28253+
28254 private global::Gtk.RadioButton radiobutton1;
28255+
28256 private global::Gtk.RadioButton radiobutton2;
28257-
28258+
28259 protected virtual void Build ()
28260 {
28261 global::Stetic.Gui.Initialize (this);
28262diff --git a/gui-compare/gui-compare.csproj b/gui-compare/gui-compare.csproj
28263new file mode 100644
28264index 0000000..33408f6
28265--- /dev/null
28266+++ b/gui-compare/gui-compare.csproj
28267@@ -0,0 +1,142 @@
28268+<?xml version="1.0" encoding="utf-8"?>
28269+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
28270+ <PropertyGroup>
28271+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
28272+ <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
28273+ <ProductVersion>10.0.0</ProductVersion>
28274+ <SchemaVersion>2.0</SchemaVersion>
28275+ <ProjectGuid>{CB1CD99D-21A1-4C8B-BC71-C5B384EB50E7}</ProjectGuid>
28276+ <OutputType>WinExe</OutputType>
28277+ <RootNamespace>guicompare</RootNamespace>
28278+ <AssemblyName>gui-compare</AssemblyName>
28279+ </PropertyGroup>
28280+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
28281+ <DebugSymbols>true</DebugSymbols>
28282+ <DebugType>full</DebugType>
28283+ <Optimize>false</Optimize>
28284+ <OutputPath>bin\Debug</OutputPath>
28285+ <DefineConstants>DEBUG;</DefineConstants>
28286+ <ErrorReport>prompt</ErrorReport>
28287+ <WarningLevel>4</WarningLevel>
28288+ <ConsolePause>false</ConsolePause>
28289+ <PlatformTarget>x86</PlatformTarget>
28290+ </PropertyGroup>
28291+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
28292+ <DebugType>none</DebugType>
28293+ <Optimize>true</Optimize>
28294+ <OutputPath>bin\Release</OutputPath>
28295+ <ErrorReport>prompt</ErrorReport>
28296+ <WarningLevel>4</WarningLevel>
28297+ <ConsolePause>false</ConsolePause>
28298+ <PlatformTarget>x86</PlatformTarget>
28299+ </PropertyGroup>
28300+ <ItemGroup>
28301+ <Reference Include="System" />
28302+ <Reference Include="Mono.Posix" />
28303+ <Reference Include="gtk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
28304+ <Reference Include="gdk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
28305+ <Reference Include="glib-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
28306+ <Reference Include="glade-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
28307+ <Reference Include="pango-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
28308+ <Reference Include="atk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
28309+ <Reference Include="System.Xml" />
28310+ <Reference Include="System.Core" />
28311+ <Reference Include="Mono.Cecil, Version=0.9.5.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756">
28312+ <Private>False</Private>
28313+ </Reference>
28314+ </ItemGroup>
28315+ <ItemGroup>
28316+ <EmbeddedResource Include="gtk-gui\gui.stetic">
28317+ <LogicalName>gui.stetic</LogicalName>
28318+ </EmbeddedResource>
28319+ <EmbeddedResource Include="cm\d.gif">
28320+ <LogicalName>d.gif</LogicalName>
28321+ </EmbeddedResource>
28322+ <EmbeddedResource Include="cm\e.gif">
28323+ <LogicalName>e.gif</LogicalName>
28324+ </EmbeddedResource>
28325+ <EmbeddedResource Include="cm\en.gif">
28326+ <LogicalName>en.gif</LogicalName>
28327+ </EmbeddedResource>
28328+ <EmbeddedResource Include="cm\f.gif">
28329+ <LogicalName>f.gif</LogicalName>
28330+ </EmbeddedResource>
28331+ <EmbeddedResource Include="cm\i.gif">
28332+ <LogicalName>i.gif</LogicalName>
28333+ </EmbeddedResource>
28334+ <EmbeddedResource Include="cm\m.gif">
28335+ <LogicalName>m.gif</LogicalName>
28336+ </EmbeddedResource>
28337+ <EmbeddedResource Include="cm\mn.png">
28338+ <LogicalName>mn.png</LogicalName>
28339+ </EmbeddedResource>
28340+ <EmbeddedResource Include="cm\n.gif">
28341+ <LogicalName>n.gif</LogicalName>
28342+ </EmbeddedResource>
28343+ <EmbeddedResource Include="cm\p.gif">
28344+ <LogicalName>p.gif</LogicalName>
28345+ </EmbeddedResource>
28346+ <EmbeddedResource Include="cm\r.gif">
28347+ <LogicalName>r.gif</LogicalName>
28348+ </EmbeddedResource>
28349+ <EmbeddedResource Include="cm\s.gif">
28350+ <LogicalName>s.gif</LogicalName>
28351+ </EmbeddedResource>
28352+ <EmbeddedResource Include="cm\sc.gif">
28353+ <LogicalName>sc.gif</LogicalName>
28354+ </EmbeddedResource>
28355+ <EmbeddedResource Include="cm\se.gif">
28356+ <LogicalName>se.gif</LogicalName>
28357+ </EmbeddedResource>
28358+ <EmbeddedResource Include="cm\sm.gif">
28359+ <LogicalName>sm.gif</LogicalName>
28360+ </EmbeddedResource>
28361+ <EmbeddedResource Include="cm\st.gif">
28362+ <LogicalName>st.gif</LogicalName>
28363+ </EmbeddedResource>
28364+ <EmbeddedResource Include="cm\sx.gif">
28365+ <LogicalName>sx.gif</LogicalName>
28366+ </EmbeddedResource>
28367+ <EmbeddedResource Include="cm\tb.gif">
28368+ <LogicalName>tb.gif</LogicalName>
28369+ </EmbeddedResource>
28370+ <EmbeddedResource Include="cm\tm.gif">
28371+ <LogicalName>tm.gif</LogicalName>
28372+ </EmbeddedResource>
28373+ <EmbeddedResource Include="cm\tp.gif">
28374+ <LogicalName>tp.gif</LogicalName>
28375+ </EmbeddedResource>
28376+ <EmbeddedResource Include="cm\w.gif">
28377+ <LogicalName>w.gif</LogicalName>
28378+ </EmbeddedResource>
28379+ <EmbeddedResource Include="cm\y.gif">
28380+ <LogicalName>y.gif</LogicalName>
28381+ </EmbeddedResource>
28382+ <EmbeddedResource Include="cm\c.gif">
28383+ <LogicalName>c.gif</LogicalName>
28384+ </EmbeddedResource>
28385+ </ItemGroup>
28386+ <ItemGroup>
28387+ <Compile Include="gtk-gui\generated.cs" />
28388+ <Compile Include="MainWindow.cs" />
28389+ <Compile Include="gtk-gui\MainWindow.cs" />
28390+ <Compile Include="Main.cs" />
28391+ <Compile Include="AssemblyInfo.cs" />
28392+ <Compile Include="gtk-gui\guicompare.ProviderSelector.cs" />
28393+ <Compile Include="gtk-gui\GuiCompare.CustomCompare.cs" />
28394+ <Compile Include="CecilMetadata.cs" />
28395+ <Compile Include="CompareContext.cs" />
28396+ <Compile Include="Comparison.cs" />
28397+ <Compile Include="CustomCompare.cs" />
28398+ <Compile Include="InfoManager.cs" />
28399+ <Compile Include="Masterinfo.cs" />
28400+ <Compile Include="MasterMetadata.cs" />
28401+ <Compile Include="Metadata.cs" />
28402+ <Compile Include="ProviderSelector.cs" />
28403+ <Compile Include="Config.cs" />
28404+ </ItemGroup>
28405+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
28406+ <ItemGroup>
28407+ <Folder Include="cm\" />
28408+ </ItemGroup>
28409+</Project>
28410\ No newline at end of file
28411diff --git a/gui-compare/gui-compare.in b/gui-compare/gui-compare.in
28412index 456a9fa..aa39b8f 100644
28413--- a/gui-compare/gui-compare.in
28414+++ b/gui-compare/gui-compare.in
28415@@ -1,3 +1,5 @@
28416 #!/bin/sh
28417
28418+export DYLD_FALLBACK_LIBRARY_PATH=/Library/Frameworks/Mono.framework/Versions/Current/lib:/usr/lib
28419+
28420 exec mono $MONO_OPTIONS "@prefix@/lib/gui-compare/gui-compare.exe" "$@"
This page took 4.9629 seconds and 4 git commands to generate.